content
stringlengths 5
1.05M
|
---|
import os
import shutil
import pytest
from olive.optimization_config import OptimizationConfig
from olive.optimize import optimize
ONNX_MODEL_PATH = os.path.join(os.path.dirname(__file__), "onnx_mnist", "model.onnx")
SAMPLE_INPUT_DATA_PATH = os.path.join(os.path.dirname(__file__), "onnx_mnist", "sample_input_data.npz")
@pytest.mark.parametrize('quantization_enabled', [False, True])
def test_optimize_quantization(quantization_enabled):
model_path = os.path.join(os.path.dirname(__file__), "other_models", "TFBertForQuestionAnswering.onnx")
result_path = "quantization_opt_{}".format(quantization_enabled)
inputs_spec = {"attention_mask": [1, 7], "input_ids": [1, 7], "token_type_ids": [1, 7]}
opt_config = OptimizationConfig(model_path=model_path, inputs_spec=inputs_spec,
quantization_enabled=quantization_enabled, result_path=result_path)
optimize(opt_config)
assert os.path.exists(result_path)
shutil.rmtree(result_path)
@pytest.mark.parametrize('transformer_enabled', [False, True])
def test_optimize_transformer(transformer_enabled):
model_path = os.path.join(os.path.dirname(__file__), "other_models", "TFBertForQuestionAnswering.onnx")
result_path = "transformer_opt_{}".format(transformer_enabled)
inputs_spec = {"attention_mask": [1, 7],"input_ids": [1, 7], "token_type_ids": [1, 7]}
if transformer_enabled:
transformer_args = "--model_type bert --num_heads 12"
opt_config = OptimizationConfig(model_path=model_path, inputs_spec=inputs_spec, result_path=result_path,
transformer_enabled=transformer_enabled, transformer_args=transformer_args)
optimize(opt_config)
else:
opt_config = OptimizationConfig(model_path=model_path, inputs_spec=inputs_spec, result_path=result_path)
optimize(opt_config)
assert os.path.exists(result_path)
shutil.rmtree(result_path)
@pytest.mark.parametrize('providers_list', [None, ["cpu"]])
def test_optimize_providers(providers_list):
result_path = "ep_opt_{}".format(providers_list)
opt_config = OptimizationConfig(model_path=ONNX_MODEL_PATH, providers_list=providers_list, result_path=result_path)
optimize(opt_config)
assert os.path.exists(result_path)
shutil.rmtree(result_path)
@pytest.mark.parametrize('concurrency_num', [2])
def test_optimize_concurrency(concurrency_num):
result_path = "concurrency_opt_{}".format(concurrency_num)
opt_config = OptimizationConfig(model_path=ONNX_MODEL_PATH, concurrency_num=concurrency_num,
result_path=result_path)
optimize(opt_config)
shutil.rmtree(result_path)
@pytest.mark.parametrize('sample_input_data_path', [SAMPLE_INPUT_DATA_PATH])
def test_optimize_sample_data(sample_input_data_path):
result_path = "sample_data_opt"
opt_config = OptimizationConfig(model_path=ONNX_MODEL_PATH, sample_input_data_path=sample_input_data_path,
result_path=result_path)
optimize(opt_config)
shutil.rmtree(result_path)
@pytest.mark.parametrize('openmp_enabled', [True, False])
def test_optimize_openmp(openmp_enabled):
result_path = "openmp_opt"
opt_config = OptimizationConfig(model_path=ONNX_MODEL_PATH, openmp_enabled=openmp_enabled,
result_path=result_path)
optimize(opt_config)
shutil.rmtree(result_path)
@pytest.mark.parametrize('dynamic_batching_size', [1, 4])
def test_throughput_tuning(dynamic_batching_size):
result_path = "throughput_tuning_res"
model_path = os.path.join(os.path.dirname(__file__), "other_models", "TFBertForQuestionAnswering.onnx")
opt_config = OptimizationConfig(model_path=model_path,
inputs_spec={"attention_mask": [-1, 7], "input_ids": [-1, 7], "token_type_ids": [-1, 7]},
throughput_tuning_enabled=True,
max_latency_percentile=0.95,
max_latency_ms=100,
threads_num=1,
dynamic_batching_size=dynamic_batching_size,
result_path=result_path,
min_duration_sec=1)
optimize(opt_config)
shutil.rmtree(result_path)
|
__version__ = '0.2.7.dev'
|
import unittest,os
import pandas as pd
from igf_data.utils.fileutils import get_temp_dir,remove_dir
from igf_airflow.seqrun.calculate_seqrun_file_size import calculate_seqrun_file_list
class Calculate_seqrun_file_list_testA(unittest.TestCase):
def setUp(self):
self.workdir = get_temp_dir()
self.seqrun_id = 'seqrun1'
os.mkdir(os.path.join(self.workdir,self.seqrun_id))
file1 = os.path.join(self.workdir,self.seqrun_id,'Data')
os.mkdir(file1)
file1 = os.path.join(file1,'f1')
self.file1 = os.path.relpath(file1,os.path.join(self.workdir,self.seqrun_id))
with open(file1,'w') as fp:
fp.write('ATGC')
self.file1_size = os.path.getsize(file1)
file2 = os.path.join(self.workdir,self.seqrun_id,'Thumbnail_Images')
os.mkdir(file2)
file2 = os.path.join(file2,'f2')
self.file2 = os.path.relpath(file2,os.path.join(self.workdir,self.seqrun_id))
with open(file2,'w') as fp:
fp.write('CGTA')
def tearDown(self):
remove_dir(self.workdir)
def test_calculate_seqrun_file_list(self):
output_dir = get_temp_dir()
output_json = \
calculate_seqrun_file_list(
seqrun_id=self.seqrun_id,
seqrun_base_dir=self.workdir,
output_path=output_dir)
df = pd.read_json(output_json)
self.assertTrue('file_path' in df.columns)
file1_entry = df[df['file_path']==self.file1]
self.assertEqual(len(file1_entry.index),1)
self.assertEqual(file1_entry['file_size'].values[0],self.file1_size)
file2_entry = df[df['file_path']==self.file2]
self.assertEqual(len(file2_entry.index),0)
if __name__=='__main__':
unittest.main() |
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import threading
from datetime import datetime
from os import getpid
from time import sleep
from scout_apm.core.commands import ApplicationEvent
from scout_apm.core.context import AgentContext
from scout_apm.core.samplers.cpu import Cpu
from scout_apm.core.samplers.memory import Memory
logger = logging.getLogger(__name__)
class Samplers(object):
_thread_lock = threading.Semaphore()
@classmethod
def ensure_running(cls):
if cls._thread_lock.acquire(False):
th = threading.Thread(target=Samplers.run_samplers)
th.daemon = True
th.start()
cls._thread_lock.release()
@classmethod
def run_samplers(cls):
logger.debug("Starting Samplers. Acquiring samplers lock.")
try:
if cls._thread_lock.acquire(True):
logger.debug("Acquired samplers lock.")
instances = [Cpu(), Memory()]
while True:
for instance in instances:
event = ApplicationEvent()
event.event_value = instance.run()
event.event_type = (
instance.metric_type() + "/" + instance.metric_name()
)
event.timestamp = datetime.utcnow()
event.source = "Pid: " + str(getpid())
if event.event_value is not None:
AgentContext.socket().send(event)
sleep(60)
finally:
logger.debug("Shutting down samplers thread.")
cls._thread_lock.release()
|
# -*- coding: utf-8 -*-
"""
Created on Jul 21 2017
@author: J. C. Vasquez-Correa
"""
from scipy.io.wavfile import read
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman"
import pysptk
try:
from .phonation_functions import jitter_env, logEnergy, shimmer_env, APQ, PPQ
except:
from phonation_functions import jitter_env, logEnergy, shimmer_env, APQ, PPQ
import pandas as pd
path_app = os.path.dirname(os.path.abspath(__file__))
sys.path.append(path_app+'/../')
from utils import dynamic2statict, save_dict_kaldimat,get_dict
import praat.praat_functions as praat_functions
from script_mananger import script_manager
import torch
from tqdm import tqdm
class Phonation:
"""
Compute phonation features from sustained vowels and continuous speech.
For continuous speech, the features are computed over voiced segments
Seven descriptors are computed:
1. First derivative of the fundamental Frequency
2. Second derivative of the fundamental Frequency
3. Jitter
4. Shimmer
5. Amplitude perturbation quotient
6. Pitch perturbation quotient
7. Logaritmic Energy
Static or dynamic matrices can be computed:
Static matrix is formed with 29 features formed with (seven descriptors) x (4 functionals: mean, std, skewness, kurtosis) + degree of Unvoiced
Dynamic matrix is formed with the seven descriptors computed for frames of 40 ms.
Notes:
1. In dynamic features the first 11 frames of each recording are not considered to be able to stack the APQ and PPQ descriptors with the remaining ones.
2. The fundamental frequency is computed the RAPT algorithm. To use the PRAAT method, change the "self.pitch method" variable in the class constructor.
Script is called as follows
>>> python phonation.py <file_or_folder_audio> <file_features> <static (true or false)> <plots (true or false)> <format (csv, txt, npy, kaldi, torch)>
Examples command line:
>>> python phonation.py "../audios/001_a1_PCGITA.wav" "phonationfeaturesAst.txt" "true" "true" "txt"
>>> python phonation.py "../audios/098_u1_PCGITA.wav" "phonationfeaturesUst.csv" "true" "true" "csv"
>>> python phonation.py "../audios/098_u1_PCGITA.wav" "phonationfeaturesUdyn.pt" "false" "true" "torch"
>>> python phonation.py "../audios/" "phonationfeaturesst.txt" "true" "false" "txt"
>>> python phonation.py "../audios/" "phonationfeaturesst.csv" "true" "false" "csv"
>>> python phonation.py "../audios/" "phonationfeaturesdyn.pt" "false" "false" "torch"
Examples directly in Python
>>> from disvoice.phonation import Phonation
>>> phonation=Phonation()
>>> file_audio="../audios/001_a1_PCGITA.wav"
>>> features=phonation.extract_features_file(file_audio, static, plots=True, fmt="numpy")
>>> features2=phonation.extract_features_file(file_audio, static, plots=True, fmt="dataframe")
>>> features3=phonation.extract_features_file(file_audio, dynamic, plots=True, fmt="torch")
>>> path_audios="../audios/"
>>> features1=phonation.extract_features_path(path_audios, static, plots=False, fmt="numpy")
>>> features2=phonation.extract_features_path(path_audios, static, plots=False, fmt="torch")
>>> features3=phonation.extract_features_path(path_audios, static, plots=False, fmt="dataframe")
"""
def __init__(self):
self.pitch_method="rapt"
self.size_frame=0.04
self.size_step=0.02
self.minf0=60
self.maxf0=350
self.voice_bias=-0.2
self.energy_thr_percent=0.025
self.PATH = os.path.dirname(os.path.abspath(__file__))
self.head=["DF0", "DDF0", "Jitter", "Shimmer", "apq", "ppq", "logE"]
def plot_phon(self, data_audio,fs,F0,logE):
"""Plots of the phonation features
:param data_audio: speech signal.
:param fs: sampling frequency
:param F0: contour of the fundamental frequency
:param logE: contour of the log-energy
:returns: plots of the phonation features.
"""
plt.figure(figsize=(6,6))
plt.subplot(211)
ax1=plt.gca()
t=np.arange(len(data_audio))/float(fs)
ax1.plot(t, data_audio, 'k', label="speech signal", alpha=0.8)
ax1.set_ylabel('Amplitude', fontsize=12)
ax1.set_xlabel('Time (s)', fontsize=12)
ax1.set_xlim([0, t[-1]])
plt.grid(True)
ax2 = ax1.twinx()
fsp=len(F0)/t[-1]
t2=np.arange(len(F0))/fsp
ax2.plot(t2, F0, 'r', linewidth=2,label=r"F_0")
ax2.set_ylabel(r'$F_0$ (Hz)', color='r', fontsize=12)
ax2.tick_params('y', colors='r')
plt.grid(True)
plt.subplot(212)
Esp=len(logE)/t[-1]
t2=np.arange(len(logE))/float(Esp)
plt.plot(t2, logE, color='k', linewidth=2.0)
plt.xlabel('Time (s)', fontsize=14)
plt.ylabel('Energy (dB)', fontsize=14)
plt.xlim([0, t[-1]])
plt.grid(True)
plt.tight_layout()
plt.show()
def extract_features_file(self, audio, static=True, plots=False, fmt="npy", kaldi_file=""):
"""Extract the phonation features from an audio file
:param audio: .wav audio file.
:param static: whether to compute and return statistic functionals over the feature matrix, or return the feature matrix computed over frames
:param plots: timeshift to extract the features
:param fmt: format to return the features (npy, dataframe, torch, kaldi)
:param kaldi_file: file to store kaldi features, only valid when fmt=="kaldi"
:returns: features computed from the audio file.
>>> phonation=Phonation()
>>> file_audio="../audios/001_a1_PCGITA.wav"
>>> features1=phonation.extract_features_file(file_audio, static=True, plots=True, fmt="npy")
>>> features2=phonation.extract_features_file(file_audio, static=True, plots=True, fmt="dataframe")
>>> features3=phonation.extract_features_file(file_audio, static=False, plots=True, fmt="torch")
>>> phonation.extract_features_file(file_audio, static=False, plots=False, fmt="kaldi", kaldi_file="./test")
"""
fs, data_audio=read(audio)
data_audio=data_audio-np.mean(data_audio)
data_audio=data_audio/float(np.max(np.abs(data_audio)))
size_frameS=self.size_frame*float(fs)
size_stepS=self.size_step*float(fs)
overlap=size_stepS/size_frameS
if self.pitch_method == 'praat':
name_audio=audio.split('/')
temp_uuid='phon'+name_audio[-1][0:-4]
if not os.path.exists(self.PATH+'/../tempfiles/'):
os.makedirs(self.PATH+'/../tempfiles/')
temp_filename_vuv=self.PATH+'/../tempfiles/tempVUV'+temp_uuid+'.txt'
temp_filename_f0=self.PATH+'/../tempfiles/tempF0'+temp_uuid+'.txt'
praat_functions.praat_vuv(audio, temp_filename_f0, temp_filename_vuv, time_stepF0=self.size_step, minf0=self.minf0, maxf0=self.maxf0)
F0,_=praat_functions.decodeF0(temp_filename_f0,len(data_audio)/float(fs),self.size_step)
os.remove(temp_filename_vuv)
os.remove(temp_filename_f0)
elif self.pitch_method == 'rapt':
data_audiof=np.asarray(data_audio*(2**15), dtype=np.float32)
F0=pysptk.sptk.rapt(data_audiof, fs, int(size_stepS), min=self.minf0, max=self.maxf0, voice_bias=self.voice_bias, otype='f0')
F0nz=F0[F0!=0]
Jitter=jitter_env(F0nz, len(F0nz))
nF=int((len(data_audio)/size_frameS/overlap))-1
Amp=[]
logE=[]
apq=[]
ppq=[]
DF0=np.diff(F0nz, 1)
DDF0=np.diff(DF0,1)
lnz=0
for l in range(nF):
data_frame=data_audio[int(l*size_stepS):int(l*size_stepS+size_frameS)]
energy=10*logEnergy(data_frame)
if F0[l]!=0:
Amp.append(np.max(np.abs(data_frame)))
logE.append(energy)
if lnz>=12: # TODO:
amp_arr=np.asarray([Amp[j] for j in range(lnz-12, lnz)])
#print(amp_arr)
apq.append(APQ(amp_arr))
if lnz>=6: # TODO:
f0arr=np.asarray([F0nz[j] for j in range(lnz-6, lnz)])
ppq.append(PPQ(1/f0arr))
lnz=lnz+1
Shimmer=shimmer_env(Amp, len(Amp))
apq=np.asarray(apq)
ppq=np.asarray(ppq)
logE=np.asarray(logE)
if len(apq)==0:
print("warning, there is not enough long voiced segments to compute the APQ, in this case APQ=shimmer")
apq=Shimmer
if plots:
self.plot_phon(data_audio,fs,F0,logE)
if len(Shimmer)==len(apq):
feat_mat=np.vstack((DF0[5:], DDF0[4:], Jitter[6:], Shimmer[6:], apq[6:], ppq, logE[6:])).T
else:
feat_mat=np.vstack((DF0[11:], DDF0[10:], Jitter[12:], Shimmer[12:], apq, ppq[6:], logE[12:])).T
feat_v=dynamic2statict([DF0, DDF0, Jitter, Shimmer, apq, ppq, logE])
if fmt in("npy","txt"):
if static:
return feat_v
return feat_mat
if fmt in("dataframe","csv"):
if static:
head_st=[]
df={}
for k in ["avg", "std", "skewness", "kurtosis"]:
for h in self.head:
head_st.append(k+" "+h)
for e, k in enumerate(head_st):
df[k]=[feat_v[e]]
return pd.DataFrame(df)
else:
df={}
for e, k in enumerate(self.head):
df[k]=feat_mat[:,e]
return pd.DataFrame(df)
if fmt=="torch":
if static:
feat_t=torch.from_numpy(feat_v)
return feat_t
return torch.from_numpy(feat_mat)
if fmt=="kaldi":
if static:
raise ValueError("Kaldi is only supported for dynamic features")
name_all=audio.split('/')
dictX={name_all[-1]:feat_mat}
save_dict_kaldimat(dictX, kaldi_file)
else:
raise ValueError(fmt+" is not supported")
def extract_features_path(self, path_audio, static=True, plots=False, fmt="npy", kaldi_file=""):
"""Extract the phonation features for audios inside a path
:param path_audio: directory with (.wav) audio files inside, sampled at 16 kHz
:param static: whether to compute and return statistic functionals over the feature matrix, or return the feature matrix computed over frames
:param plots: timeshift to extract the features
:param fmt: format to return the features (npy, dataframe, torch, kaldi)
:param kaldi_file: file to store kaldifeatures, only valid when fmt=="kaldi"
:returns: features computed from the audio file.
>>> phonation=Phonation()
>>> path_audio="../audios/"
>>> features1=phonation.extract_features_path(path_audio, static=True, plots=False, fmt="npy")
>>> features2=phonation.extract_features_path(path_audio, static=True, plots=False, fmt="csv")
>>> features3=phonation.extract_features_path(path_audio, static=False, plots=True, fmt="torch")
>>> phonation.extract_features_path(path_audio, static=False, plots=False, fmt="kaldi", kaldi_file="./test.ark")
"""
hf=os.listdir(path_audio)
hf.sort()
pbar=tqdm(range(len(hf)))
ids=[]
Features=[]
for j in pbar:
pbar.set_description("Processing %s" % hf[j])
audio_file=path_audio+hf[j]
feat=self.extract_features_file(audio_file, static=static, plots=plots, fmt="npy")
Features.append(feat)
if static:
ids.append(hf[j])
else:
ids.append(np.repeat(hf[j], feat.shape[0]))
Features=np.vstack(Features)
ids=np.hstack(ids)
if fmt in("npy","txt"):
return Features
if fmt in("dataframe","csv"):
if static:
head_st=[]
df={}
for k in ["avg", "std", "skewness", "kurtosis"]:
for h in self.head:
head_st.append(k+" "+h)
for e, k in enumerate(head_st):
df[k]=Features[:,e]
else:
df={}
for e, k in enumerate(self.head):
df[k]=Features[:,e]
df["id"]=ids
return pd.DataFrame(df)
if fmt=="torch":
return torch.from_numpy(Features)
if fmt=="kaldi":
if static:
raise ValueError("Kaldi is only supported for dynamic features")
dictX=get_dict(Features, ids)
save_dict_kaldimat(dictX, kaldi_file)
else:
raise ValueError(fmt+" is not supported")
if __name__=="__main__":
if len(sys.argv)!=6:
print("python phonation.py <file_or_folder_audio> <file_features> <static (true, false)> <plots (true, false)> <format (csv, txt, npy, kaldi, torch)>")
sys.exit()
phonation=Phonation()
script_manager(sys.argv, phonation) |
'''
Created on Nov 13, 2017
@author: khoi.ngo
'''
from .constant import Colors, Constant
import asyncio
import json
from indy import wallet, pool, ledger
from indy.error import IndyError
class Common():
"""
Wrapper the common steps.
"""
# Static methods =========================================================================================================
@staticmethod
async def prepare_pool_and_wallet(pool_name, wallet_name, pool_genesis_txn_file):
"""
Prepare pool and wallet to use in a test case.
:param pool_name: Name of the pool ledger configuration.
:param wallet_name: Name of the wallet.
:param pool_genesis_txn_file: The path of the pool_genesis_transaction file.
:return: The pool handle and the wallet handle were created.
"""
pool_handle = await Common().create_and_open_pool(pool_name, pool_genesis_txn_file)
wallet_handle = await Common().create_and_open_wallet(pool_name, wallet_name)
return pool_handle, wallet_handle
@staticmethod
async def clean_up_pool_and_wallet(pool_name, pool_handle, wallet_name, wallet_handle):
"""
Clean up pool and wallet. Using as a post condition of a test case.
:param pool_name: The name of the pool.
:param pool_handle: The handle of the pool.
:param wallet_name: The name of the wallet.
:param wallet_handle: The handle of the wallet.
"""
await Common().close_pool_and_wallet(pool_handle, wallet_handle)
await Common().delete_pool_and_wallet(pool_name, wallet_name)
@staticmethod
def clean_up_pool_and_wallet_folder(pool_name, wallet_name):
"""
Delete pool and wallet folder without using lib-indy.
:param pool_name: The name of the pool.
:param wallet_name: The name of the wallet.
"""
import os
import shutil
print(Colors.HEADER + "\n\tCheck if the wallet and pool for this test already exist and delete them...\n"
+ Colors.ENDC)
work_dir = Constant.work_dir
if os.path.exists(work_dir + "/pool/" + pool_name):
try:
shutil.rmtree(work_dir + "/pool/" + pool_name)
except IOError as E:
print(Colors.FAIL + str(E) + Colors.ENDC)
if os.path.exists(work_dir + "/wallet/" + wallet_name):
try:
shutil.rmtree(work_dir + "/wallet/" + wallet_name)
except IOError as E:
print(Colors.FAIL + str(E) + Colors.ENDC)
@staticmethod
def run(test_case):
loop = asyncio.new_event_loop()
loop.run_until_complete(test_case())
loop.close()
@staticmethod
def final_result(test_report, steps, begin_time):
import time
from utils.report import Status
for step in steps:
test_report.add_step(step)
if step.get_status() == Status.FAILED:
print('%s: ' % str(step.get_id()) + Colors.FAIL + 'failed\n' + Colors.ENDC)
test_report.set_test_failed()
test_report.set_duration(time.time() - begin_time)
test_report.write_result_to_file()
@staticmethod
async def build_and_send_nym_request(pool_handle, wallet_handle, submitter_did,
target_did, target_verkey, alias, role):
"""
Build a nym request and send it.
:param pool_handle: pool handle returned by indy_open_pool_ledger.
:param wallet_handle: wallet handle returned by indy_open_wallet.
:param submitter_did: Id of Identity stored in secured Wallet.
:param target_did: Id of Identity stored in secured Wallet.
:param target_verkey: verification key
:param alias: alias
:param role: Role of a user NYM record
:raise Exception if the method has error.
"""
try:
nym_txn_req = await ledger.build_nym_request(submitter_did, target_did, target_verkey, alias, role)
await ledger.sign_and_submit_request(pool_handle, wallet_handle, submitter_did, nym_txn_req)
except IndyError as E:
print(Colors.FAIL + str(E) + Colors.ENDC)
raise
# Methods ==========================================================================================================
async def create_and_open_pool(self, pool_name, pool_genesis_txn_file):
"""
Creates a new local pool ledger configuration.
Then open that pool and return the pool handle that can be used later to connect pool nodes.
:param pool_name: Name of the pool ledger configuration.
:param pool_genesis_txn_file: Pool configuration json. if NULL, then default config will be used.
:return: The pool handle was created.
"""
print(Colors.HEADER + "\nCreate Ledger\n" + Colors.ENDC)
pool_config = json.dumps({"genesis_txn": str(pool_genesis_txn_file)})
# Create pool
try:
await pool.create_pool_ledger_config(pool_name, pool_config)
except IndyError as E:
raise E
print(Colors.HEADER + "\nOpen pool ledger\n" + Colors.ENDC)
# get pool handle
try:
pool_handle = await pool.open_pool_ledger(pool_name, None)
except IndyError as E:
raise E
await asyncio.sleep(0)
return pool_handle
async def create_and_open_wallet(self, pool_name, wallet_name):
"""
Creates a new secure wallet with the given unique name.
Then open that wallet and get the wallet handle that can
be used later to use in methods that require wallet access.
:param pool_name: Name of the pool that corresponds to this wallet.
:param wallet_name: Name of the wallet.
:return: The wallet handle was created.
"""
print(Colors.HEADER + "\nCreate wallet\n" + Colors.ENDC)
try:
await wallet.create_wallet(pool_name, wallet_name, None, None, None)
except IndyError as E:
raise E
print(Colors.HEADER + "\nGet wallet handle\n" + Colors.ENDC)
try:
wallet_handle = await wallet.open_wallet(wallet_name, None, None)
except IndyError as E:
raise E
await asyncio.sleep(0)
return wallet_handle
async def close_pool_and_wallet(self, pool_handle, wallet_handle):
"""
Close the pool and wallet with the pool and wallet handle.
:param pool_handle: pool handle returned by indy_open_pool_ledger.
:param wallet_handle: wallet handle returned by indy_open_wallet.
:raise Exception if the method has error.
"""
print(Colors.HEADER + "\nClose pool\n" + Colors.ENDC)
try:
await pool.close_pool_ledger(pool_handle)
except IndyError as E:
raise E
print(Colors.HEADER + "\nClose wallet\n" + Colors.ENDC)
try:
await wallet.close_wallet(wallet_handle)
except IndyError as E:
raise E
await asyncio.sleep(0)
async def delete_pool_and_wallet(self, pool_name, wallet_name):
"""
Delete the pool and wallet with the pool and wallet name.
:param pool_name: Name of the pool that corresponds to this wallet.
:param wallet_name: Name of the wallet to delete.
:raise Exception if the method has error.
"""
print(Colors.HEADER + "\nDelete pool\n" + Colors.ENDC)
try:
await pool.delete_pool_ledger_config(pool_name)
except IndyError as E:
raise E
print(Colors.HEADER + "\nDelete wallet\n" + Colors.ENDC)
try:
await wallet.delete_wallet(wallet_name, None)
except IndyError as E:
raise E
await asyncio.sleep(0)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#stdlib import
import json
class ErrorEllipseAxis:
"""
A conversion class usd to create, parse, and validate error ellipse axis data
"""
# JSON Keys
ERROR_KEY = "Error" # Required
AZIMUTH_KEY = "Azimuth" # Required
DIP_KEY = "Dip" # Required
def __init__ (self, newError = None, newAzimuth = None, newDip = None):
''' Initializing the object. Constructs an empty object if all arguments are None.
newError: a double containing the length of the error ellipse axis
in kilometers
newAzimuth: a double containing the azimuth of the error ellipse axis
in degrees
newDip: a double containing the dip of the error ellipse axis
in degrees
'''
if newError is not None:
self.error = newError
if newAzimuth is not None:
self.azimuth = newAzimuth
if newDip is not None:
self.dip = newDip
def fromJSONString (self, JSONString):
''' Populates object from a JSON string
JSONString: a required string containing the JSON formatted text
'''
JSONObject = json.loads(JSONString)
self.fromDict(JSONObject)
def fromDict (self, aDict):
''' Populates object from a dictionary
aDict: a required dictionary
'''
#Required Keys
try:
self.error = aDict[self.ERROR_KEY]
self.azimuth = aDict[self.AZIMUTH_KEY]
self.dip = aDict[self.DIP_KEY]
except(ValueError, KeyError, TypeError) as e:
print("Dictionary format error, missing required keys: %s" % e)
def toJSONString(self):
''' Converts object to a JSON formatted string
Returns: JSON formatted message as a string
'''
JSONObject = self.toDict()
return json.dumps(JSONObject, ensure_ascii = False)
def toDict(self):
''' Converts object to a dictionary
Returns: the dictionary
'''
aDict = {}
#Required Keys
try:
aDict[self.ERROR_KEY] = self.error
aDict[self.AZIMUTH_KEY] = self.azimuth
aDict[self.DIP_KEY] = self.dip
except(NameError, AttributeError) as e:
print("Missing required data error: %s" % e)
return aDict
def isValid(self):
''' Checks to see if object is valid
Returns: true if object is valid, false otherwise
'''
errorList = self.getErrors()
return not errorList
def getErrors (self):
''' Gets a list of object validation errors
Returns: a list of string containing the validation error messages
'''
errorList = []
# required keys
# error
try:
self.error
except(NameError, AttributeError):
errorList.append('No Error in ErrorEllipseAxis Class.')
# azimuth
try:
self.azimuth
except(NameError, AttributeError):
errorList.append('No Azimuth in ErrorEllipseAxis Class')
# dip
try:
self.dip
except(NameError, AttributeError):
errorList.append('No Dip in ErrorEllipseAxis Class.')
return errorList
def isEmpty(self):
''' Checks to see if object is empty
Returns: True if the object has no attributes, False otherwise
'''
if hasattr(self, 'error'):
return False
if hasattr(self, 'azimuth'):
return False
if hasattr(self, 'dip'):
return False
return True |
#!/usr/bin/python
''' Visual genome data analysis and preprocessing.'''
import json
import os
from collections import Counter
import xml.etree.cElementTree as ET
from xml.dom import minidom
dataDir = '/home/new/file/dataset/VRD'
outDir = '/home/new/file/rel_det/ProcessVG-master/data/vrd'
# Set maximum values for number of object / attribute / relation classes,
# filter it further later
max_objects = 100
max_attributes = 50
max_predicates = 70
common_attributes = set(['white', 'black', 'blue', 'green', 'red', 'brown', 'yellow',
'small', 'large', 'silver', 'wooden', 'orange', 'gray', 'grey', 'metal', 'pink', 'tall',
'long', 'dark'])
def clean_string(string):
string = string.lower().strip()
if len(string) >= 1 and string[-1] == '.':
return string[:-1].strip()
return string
def clean_objects(string, common_attributes):
''' Return object and attribute lists '''
string = clean_string(string)
words = string.split()
if len(words) > 1:
prefix_words_are_adj = True
for att in words[:-1]:
if not att in common_attributes:
prefix_words_are_adj = False
if prefix_words_are_adj:
return words[-1:], words[:-1]
else:
return [string], []
else:
return [string], []
def clean_attributes(string):
''' Return attribute list '''
string = clean_string(string)
if string == "black and white":
return [string]
else:
return [word.lower().strip() for word in string.split(" and ")]
def clean_relations(string):
string = clean_string(string)
if len(string) > 0:
return [string]
else:
return []
def prettify(elem):
''' Return a pretty-printed XML string for the Element '''
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
def get_image_names(json_file):
with open(json_file, "r") as f:
data=json.load(f)
return data.keys()
def get_predicate_id():
pred_dict = {}
with open("/home/new/file/dataset/VRD/predicates.json", "r") as f:
ids = json.load(f)
for index, obj_id in enumerate(ids):
pred_dict[index] = obj_id
return pred_dict
def get_object_id():
"""
get the correspondence between objects and labels
:return: id-object dict
"""
id_dict={}
with open("/home/new/file/dataset/VRD/objects.json","r") as f:
ids=json.load(f)
for index,obj_id in enumerate(ids):
id_dict[index]=obj_id
return id_dict
# object_dict={}
# keys=data.keys()
# for key in keys:# one image
# obj_cat=[]
# obj_lst=[]
# file_name=key
# relationships=data[key]
# for relationship in relationships:
# obj=relationship["object"]
#
# if obj["category"] not in obj_cat:
# object={}
# obj_cat.append(obj["category"])
# object["object_id"]=obj["category"]
# object["y_min"]=obj["bbox"][0]
# object["y_max"]=obj["bbox"][1]
# object["x_min"]=obj["bbox"][2]
# object["x_max"]=obj["bbox"][3]
# object["names"]=id_dict[int(obj["category"])]
# obj_lst.append(object)
#
# obj = relationship["subject"]
#
# if obj["category"] not in obj_cat:
# object = {}
# obj_cat.append(obj["category"])
# object["object_id"] = obj["category"]
# object["y_min"] = obj["bbox"][0]
# object["y_max"] = obj["bbox"][1]
# object["x_min"] = obj["bbox"][2]
# object["x_max"] = obj["bbox"][3]
# object["names"] = id_dict[int(obj["category"])]
# obj_lst.append(object)
# object_dict[file_name]=obj_lst
#
# return object_dict
def build_vocabs_and_xml(json_file):
objects = Counter()
attributes = Counter()
relations = Counter()
print("loading date...")
with open(os.path.join(dataDir, json_file)) as f:
data = json.load(f)
print("loading date finished")
obj_dict=get_object_id()
pred_dict=get_predicate_id()
# First extract attributes and relations
for vrd in data:
for rel in vrd['relationships']:
relations.update(clean_relations(rel['relationship']))
# Create full-sized vocabs
objects = obj_dict.values()
relations = pred_dict.values()
with open(os.path.join(outDir, "objects_vocab_%s.txt" % max_objects), "w") as text_file:
for item in objects:
text_file.write("%s\n" % item)
with open(os.path.join(outDir, "relations_vocab_%s.txt" % max_predicates), "w") as text_file:
for item in relations:
text_file.write("%s\n" % item)
out_folder = 'xml'
if not os.path.exists(os.path.join(outDir, out_folder)):
os.mkdir(os.path.join(outDir, out_folder))
for vrd in data:
ann = ET.Element("annotation")
ET.SubElement(ann, "folder").text = json_file[:-5]
ET.SubElement(ann, "filename").text =vrd['filename']
source = ET.SubElement(ann, "source")
ET.SubElement(source, "database").text = "vrd dataset"
ET.SubElement(source, "image_id").text = vrd['filename'][:-4]
size = ET.SubElement(ann, "size")
ET.SubElement(size, "width").text = str(vrd["width"])
ET.SubElement(size, "height").text = str(vrd["height"])
ET.SubElement(size, "depth").text = "3"
ET.SubElement(ann, "segmented").text = "0"
object_set = set()
for obj in vrd['objects']:
o, a = clean_objects(obj['names'][0], common_attributes)
if o[0] in objects:
ob = ET.SubElement(ann, "object")
ET.SubElement(ob, "name").text = o[0]
ET.SubElement(ob, "object_id").text = str(objects.index(o[0]))
object_set.add(objects.index(o[0]))
ET.SubElement(ob, "difficult").text = "0"
bbox = ET.SubElement(ob, "bndbox")
ET.SubElement(bbox, "xmin").text = str(obj['bbox']['x'])
ET.SubElement(bbox, "ymin").text = str(obj['bbox']['y'])
ET.SubElement(bbox, "xmax").text = str(obj['bbox']['x'] + obj['bbox']['w'])
ET.SubElement(bbox, "ymax").text = str(obj['bbox']['y'] + obj['bbox']['h'])
for rel in vrd['relationships']:
predicate = clean_string(rel["relationship"])
if rel["text"][0] in objects and rel["text"][2] in objects:
if predicate in relations:
re = ET.SubElement(ann, "relation")
ET.SubElement(re, "subject_id").text = str(objects.index(rel["text"][0]))
ET.SubElement(re, "object_id").text = str(objects.index(rel["text"][2]))
ET.SubElement(re, "predicate").text = predicate
outFile = vrd['filename'][:-4]+".xml"
tree = ET.ElementTree(ann)
if len(tree.findall('object')) > 0:
tree.write(os.path.join(outDir, out_folder, outFile))
if __name__ == "__main__":
# First, use visual genome library to merge attributes and scene graphs
# vg.AddAttrsToSceneGraphs(dataDir=dataDir)
# Next, build xml files
build_vocabs_and_xml("sg_train_annotations.json")
|
def date_formatter(string_date: str) -> str:
"""
Args:
string_date: string containing date in format 22.08.2018 12:27:00
Returns:
string of date in format YYYY-mm-dd-hh
"""
if string_date[11].isspace():
pos = 0
srr = ""
for i in string_date:
if pos == 10:
srr = srr + '0'
else:
srr = srr + i
pos = pos + 1
string_date = srr
return_date = string_date[6:10] + '-' + string_date[
3:5] + '-' + string_date[:2]
return return_date
def date_time_formatter(string_date: str) -> str:
"""
Converts one type of date format "dd.mm.yyyy hh.mm.ss" to date format YYYY-mm-dd-hh
Args:
string_date: string containing date in format 22.08.2018 12:27:00
Returns:
string of date in format YYYY-mm-dd-hh
"""
if string_date[11].isspace():
pos = 0
srr = ""
for i in string_date:
if pos == 10:
srr = srr + '0'
else:
srr = srr + i
pos = pos + 1
string_date = srr
return_date = string_date[6:10] + '-' + string_date[
3:5] + '-' + string_date[:2] + '-' + string_date[11:13]
return return_date
|
class Error:
def __init__(self, file_name, line_number, error_name, error_details = None) -> None:
self.file_name = file_name
self.line_number = line_number
self.error_name = error_name
self. error_details = error_details
def __repr__(self) -> str:
if self.file_name != None:
error_info = f'{self.error_name} in line {self.line_number} of {self.file_name}'
else:
error_info = f'{self.error_name} in line {self.line_number}'
if self.error_details != None: return f'{error_info}\n Details : {self.error_details}'
return f'{error_info}'
class ErrorIllegalChar(Error):
def __init__(self,file_name, line_number, details) -> None:
super().__init__(file_name, line_number,'Illegal Character Detected', details)
|
import math
def get_sum(n: int) -> int:
sum = 0
i = 1
while i <= math.sqrt(n):
if n % i == 0:
if n / i == i:
sum += i
else:
sum += i
sum = sum + (n / i)
i += 1
sum = sum - n
return sum
def is_abundant(n: int) -> bool:
if get_sum(n) > n:
return True
return False
def find_nth_value() -> None:
n = int(input("Enter the nth value to find: "))
count = 0
ans = []
i = 0
while n >= count:
if is_abundant(i):
ans.append(i)
count += 1
i += 1
print(f"The value of Abundant Number is {ans[n]}")
if __name__ == "__main__":
find_nth_value()
|
test = { 'name': 'q3',
'points': 3,
'suites': [ { 'cases': [ {'code': '>>> hailstone(4)\n4\n2\n1\n3', 'hidden': False, 'locked': False},
{'code': '>>> hailstone(10)\n10\n5\n16\n8\n4\n2\n1\n7', 'hidden': False, 'locked': False},
{'code': '>>> hailstone(15)\n15\n46\n23\n70\n35\n106\n53\n160\n80\n40\n20\n10\n5\n16\n8\n4\n2\n1\n18', 'hidden': False, 'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
r"""Utility functions."""
import json
import math
import os
from urllib.parse import urlparse
import urllib.request
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
EPSILON_DOUBLE = torch.tensor(2.220446049250313e-16, dtype=torch.float64)
EPSILON_SINGLE = torch.tensor(1.19209290E-07, dtype=torch.float32)
SQRT_TWO_DOUBLE = torch.tensor(math.sqrt(2), dtype=torch.float32)
SQRT_TWO_SINGLE = SQRT_TWO_DOUBLE.to(torch.float32)
_DEFAULT_CONFIG = {
'mongo': {
'server': 'mongod',
'hostname': 'localhost',
'port': 27017,
'database': './data/db'
},
'benchmark': {
'voc_dir': './data/datasets/voc',
'coco_dir': './data/datasets/coco',
'coco_anno_dir': './data/datasets/coco/annotations',
'imagenet_dir': './data/datasets/imagenet',
'models_dir': './data/models',
'experiments_dir': './data'
}
}
_config_read = False
def get_config():
"""Read the TorchRay config file.
Read the config file from the current directory or the user's home
directory and return the configuration.
Returns:
dict: configuration.
"""
global _config_read
config = _DEFAULT_CONFIG
if _config_read:
return config
def _update(source, delta):
if isinstance(source, dict):
assert isinstance(delta, dict)
for k in source.keys():
if k in delta:
source[k] = _update(source[k], delta[k])
for k in delta.keys():
# Catch name errors in config file.
assert k in source
else:
source = delta
return source
config = _DEFAULT_CONFIG
for curr_dir in os.curdir, os.path.expanduser('~'):
path = os.path.join(curr_dir, '.torchrayrc')
if os.path.exists(path):
with open(path, 'r') as file:
config_ = json.load(file)
_update(config, config_)
break
_config_read = True
return config
def get_device(gpu=0):
r"""Get the :class`torch.device` to use; specify device with :attr:`gpu`.
Args:
gpu (int, optional): Index of the GPU device; specify ``None`` to
force CPU. Default: ``0``.
Returns:
:class:`torch.device`: device to use.
"""
device = torch.device(
f'cuda:{gpu}'
if torch.cuda.is_available() and gpu is not None
else 'cpu')
return device
def xmkdir(path):
r"""Create a directory path recursively.
The function creates :attr:`path` if the directory does not exist.
Args::
path (str): path to create.
"""
if path is not None and not os.path.exists(path):
try:
os.makedirs(path)
except FileExistsError:
# Race condition in multi-processing.
pass
def is_url(obj):
r"""Check if an object is an URL.
Args:
obj (object): object to test.
Returns:
bool: ``True`` if :attr:`x` is an URL string; otherwise ``False``.
"""
try:
result = urlparse(obj)
return all([result.scheme, result.netloc, result.path])
except Exception:
return False
def tensor_to_im(tensor):
r"""Reshape a tensor as a grayscale image stack.
The function reshapes the tensor :attr:`x` of size
:math:`N\times K\times H\times W`
to have shape :math:`(NK)\times 1\times H\times W`.
Args:
tensor (:class:`torch.Tensor`): tensor to rearrange.
Returns:
:class:`torch.Tensor`: Reshaped tensor.
"""
return tensor.reshape(-1, *tensor.shape[2:])[:, None, :, :]
def pil_to_tensor(pil_image):
r"""Convert a PIL image to a tensor.
Args:
pil_image (:class:`PIL.Image`): PIL image.
Returns:
:class:`torch.Tensor`: the image as a :math:`3\times H\times W` tensor
in the [0, 1] range.
"""
pil_image = np.array(pil_image)
if len(pil_image.shape) == 2:
pil_image = pil_image[:, :, None]
return torch.tensor(pil_image, dtype=torch.float32).permute(2, 0, 1) / 255
def im_to_numpy(tensor):
r"""Convert a tensor image to a NumPy image.
The function converts the :math:`K\times H\times W` tensor :attr:`tensor`
to a corresponding :math:`H\times W\times K` NumPy array.
Args:
tensor (:class:`torch.Tensor`): input tensor.
Returns:
:class:`numpy.ndarray`: NumPy array.
"""
tensor_reshaped = tensor.expand(3, *tensor.shape[1:]).permute(1, 2, 0)
return tensor_reshaped.detach().cpu().numpy()
def imread(file, as_pil=False, resize=None, to_rgb=False):
r"""
Read an image as a tensor.
The function reads the image :attr:`file` as a PyTorch tensor.
`file` can also be an URL.
To reshape the image use the option :attr:`reshape`, passing the desired
shape ``(W, H)`` as tuple. Passing an integer sets the shortest side to
that length while preserving the aspect ratio.
Args:
file (str): Path or ULR to the image.
resize (float, int, tuple or list): Resize the image to this size.
as_pil (bool): If ``True``, returns the PIL image instead of converting
to a tensor.
to_rgb (optional, bool): If `True`, convert the PIL image to RGB.
Default: ``False``.
Returns:
:class:`torch.Tensor`:
The image read as a :math:`3\times H\times W` tensor in
the [0, 1] range.
"""
# Read an example image as a numpy array.
if is_url(file):
hdr = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 '
'(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.'
'11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*'
'/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'
}
req = urllib.request.Request(file, headers=hdr)
file = urllib.request.urlopen(req)
img = Image.open(file)
if to_rgb:
img = img.convert('RGB')
if resize is not None:
if not isinstance(resize, tuple) and not isinstance(resize, list):
scale = float(resize) / float(min(img.size[0], img.size[1]))
resize = [round(scale * h) for h in img.size]
if resize != img.size:
img = img.resize(resize, Image.ANTIALIAS)
if as_pil:
return img
return pil_to_tensor(img)
def imsc(img, *args, quiet=False, lim=None, interpolation='lanczos', **kwargs):
r"""Rescale and displays an image represented as a img.
The function scales the img :attr:`im` to the [0 ,1] range.
The img is assumed to have shape :math:`3\times H\times W` (RGB)
:math:`1\times H\times W` (grayscale).
Args:
img (:class:`torch.Tensor` or :class:`PIL.Image`): image.
quiet (bool, optional): if False, do not display image.
Default: ``False``.
lim (list, optional): maximum and minimum intensity value for
rescaling. Default: ``None``.
interpolation (str, optional): The interpolation mode to use with
:func:`matplotlib.pyplot.imshow` (e.g. ``'lanczos'`` or
``'nearest'``). Default: ``'lanczos'``.
Returns:
:class:`torch.Tensor`: Rescaled image img.
"""
if isinstance(img, Image.Image):
img = pil_to_tensor(img)
handle = None
with torch.no_grad():
if not lim:
lim = [img.min(), img.max()]
img = img - lim[0] # also makes a copy
img.mul_(1 / (lim[1] - lim[0]))
img = torch.clamp(img, min=0, max=1)
if not quiet:
bitmap = img.expand(3,
*img.shape[1:]).permute(1, 2, 0).cpu().numpy()
handle = plt.imshow(
bitmap, *args, interpolation=interpolation, **kwargs)
curr_ax = plt.gca()
curr_ax.axis('off')
return img, handle
def resample(source, target_size, transform):
r"""Spatially resample a tensor.
The function resamples the :attr:`source` tensor generating a
:attr:`target` tensors of size :attr:`target_size`. Resampling uses the
transform :attr:`transform`, specified as a :math:`2\times 2` matrix in the
form
.. math::
\begin{bmatrix}
s_u & t_u\\
s_v & t_v
\end{bmatrix}
where :math:`s_u` is the scaling factor along the horizontal spatial
direction, :math:`t_u` the horizontal offset, and :math:`s_v, t_v` the
corresponding quantity for the vertical direction.
Internally, the function uses :func:`torch.nn.functional.grid_sample` with
bilinear interpolation and zero padding.
The transformation defines the forward
mapping, so that a pixel :math:`(u,v)` in the source tensro is mapped to
pixel :math:`u' = s_u u + t_u, v' = s_v v + tv`.
The reference frames are defined as follows. Pixels are unit squares, so
that a :math:`H\times W` tensor maps to the rectangle :math:`[0, W) \times
[0, H)`. Hence element :math:`x_{ncij}` of a tensor :math:`x` maps
to a unit square whose center is :math:`(u,v) = (i + 1/2, j+1/2)`.
Example:
In order to stretch an :math:`H \times W` source tensor to a target
:math:`H' \times W'` tensor, one would use the transformation matrix
.. math::
\begin{bmatrix}
W'/W & 0\\
H'/H & 0\\
\end{bmatrix}
Args:
source (:class:`torch.Tensor`): :math:`N\times C\times H\times W`
tensor.
target_size (tuple of int): target size.
transform (:class:`torch.Tensor`): :math:`2\times 2` transformation
tensor.
Returns:
:class:`torch.Tensor`: resampled tensor.
"""
dtype = source.dtype
dev = source.device
height_, width_ = target_size
ur_ = torch.arange(width_, dtype=dtype, device=dev) + 0.5
vr_ = torch.arange(height_, dtype=dtype, device=dev) + 0.5
height, weight = source.shape[2:]
ur = 2 * ((ur_ + transform[0, 1]) / transform[0, 0]) / weight - 1
vr = 2 * ((vr_ + transform[1, 1]) / transform[1, 0]) / height - 1
v, u = torch.meshgrid(vr, ur)
v = v.unsqueeze(2)
u = u.unsqueeze(2)
grid = torch.cat((u, v), dim=2)
grid = grid.unsqueeze(0).expand(len(source), -1, -1, -1)
return torch.nn.functional.grid_sample(source, grid)
def imsmooth(tensor,
sigma,
stride=1,
padding=0,
padding_mode='constant',
padding_value=0):
r"""Apply a 2D Gaussian filter to a tensor.
The 2D filter itself is implementing by separating the 2D convolution in
two 1D convolutions, first along the vertical direction and then along
the horizontal one. Each 1D Gaussian kernel is given by:
.. math::
f_i \propto \exp\left(-\frac{1}{2} \frac{i^2}{\sigma^2} \right),
~~~ i \in \{-W,\dots,W\},
~~~ W = \lceil 4\sigma \rceil.
This kernel is normalized to sum to one exactly. Given the latter, the
function calls `torch.nn.functional.conv2d`
to perform the actual convolution. Various padding parameters and the
stride are passed to the latter.
Args:
tensor (:class:`torch.Tensor`): :math:`N\times C\times H\times W`
image tensor.
sigma (float): standard deviation of the Gaussian kernel.
stride (int, optional): subsampling factor. Default: ``1``.
padding (int, optional): extra padding. Default: ``0``.
padding_mode (str, optional): ``'constant'``, ``'reflect'`` or
``'replicate'``. Default: ``'constant'``.
padding_value (float, optional): constant value for the `constant`
padding mode. Default: ``0``.
Returns:
:class:`torch.Tensor`: :math:`N\times C\times H\times W` tensor with
the smoothed images.
"""
assert sigma >= 0
width = math.ceil(4 * sigma)
filt = (torch.arange(-width,
width + 1,
dtype=torch.float32,
device=tensor.device) /
(SQRT_TWO_SINGLE * sigma + EPSILON_SINGLE))
filt = torch.exp(-filt * filt)
filt /= torch.sum(filt)
num_channels = tensor.shape[1]
width = width + padding
if padding_mode == 'constant' and padding_value == 0:
other_padding = width
x = tensor
else:
# pad: (before, after) pairs starting from last dimension backward
x = F.pad(tensor,
(width, width, width, width),
mode=padding_mode,
value=padding_value)
other_padding = 0
padding = 0
x = F.conv2d(x,
filt.reshape((1, 1, -1, 1)).expand(num_channels, -1, -1, -1),
padding=(other_padding, padding),
stride=(stride, 1),
groups=num_channels)
x = F.conv2d(x,
filt.reshape((1, 1, 1, -1)).expand(num_channels, -1, -1, -1),
padding=(padding, other_padding),
stride=(1, stride),
groups=num_channels)
return x
def imarraysc(tiles,
spacing=0,
quiet=False,
lim=None,
interpolation='lanczos'):
r"""Display or arrange an image or tensor batch as a mosaic.
The function displays the tensor `tiles` as a set of tiles. `tiles` has
shape :math:`K\times C\times H\times W` and the generated mosaic
is a *new* tensor with shape :math:`C\times (MH) \times (NW)` where
:math:`MN \geq K`.
Missing tiles are filled with zeros.
The range of each tile is individually scaled to the range [0, 1].
Args:
tiles (:class:`torch.Tensor`): tensor to display or rearrange.
spacing (int, optional): thickness of the border (infilled
with zeros) around each tile. Default: ``0``.
quiet (bool, optional): If False, do not display the mosaic.
Default: ``False``.
lim (list, optional): maximum and minimum intensity value for
rescaling. Default: ``None``.
interpolation (str, optional): interpolation to use with
:func:`matplotlib.pyplot.imshow`. Default: ``'lanczos'``.
Returns:
class:`torch.Tensor`: The rearranged tensor.
"""
num = tiles.shape[0]
num_cols = math.ceil(math.sqrt(num))
num_rows = (num + num_cols - 1) // num_cols
num_channels = tiles.shape[1]
height = tiles.shape[2]
width = tiles.shape[3]
mosaic = torch.zeros(num_channels,
height * num_rows + spacing * (num_rows - 1),
width * num_cols + spacing * (num_cols - 1))
for t in range(num):
u = t % num_cols
v = t // num_cols
mosaic[0:num_channels,
v*(height+spacing):v*(height+spacing)+height,
u*(width+spacing):u*(width+spacing)+width] = imsc(tiles[t],
quiet=True,
lim=lim)[0]
return imsc(mosaic, quiet=quiet, interpolation=interpolation)
|
import json
from django.conf import settings
from django.http import HttpResponse, Http404
from django.shortcuts import redirect
from django.contrib import messages
from django.core.mail import send_mail
from django.urls import reverse_lazy
from django.views import View
from django.views.generic.edit import FormView
from allauth.account import views as allauth_views
from invitations.views import SendInvite
from intake.services.mailgun_api_service import is_a_valid_mailgun_post
from . import forms
from user_accounts.base_views import StaffOnlyMixin
import intake.services.events_service as EventsService
class CustomLoginView(allauth_views.LoginView):
template_name = "user_accounts/login.jinja"
def get_form_class(self):
return forms.LoginForm
def form_invalid(self, *args):
# get the email entered, if it exists
login_email = self.request.POST.get('login', '')
# save it in the session, in case the go to password reset
if login_email:
self.request.session['failed_login_email'] = login_email
EventsService.user_failed_login(self)
return super().form_invalid(*args)
class CustomSignupView(allauth_views.SignupView):
template_name = "user_accounts/signup.jinja"
def get_form_class(self):
return forms.CustomSignUpForm
def closed(self):
return redirect('intake-home')
def form_valid(self, form):
response = super().form_valid(form)
self.request.user = self.user
EventsService.user_account_created(self)
return response
class CustomSendInvite(StaffOnlyMixin, SendInvite):
template_name = "user_accounts/invite_form.jinja"
form_class = forms.InviteForm
success_url = reverse_lazy("user_accounts-profile")
def form_valid(self, form):
invite = form.save(inviter=self.request.user)
invite.send_invitation(self.request)
messages.success(self.request,
'An email invite was sent to {}'.format(invite.email))
return redirect(self.success_url)
class UserProfileView(FormView):
template_name = "user_accounts/userprofile_form.jinja"
form_class = forms.UserProfileForm
success_url = reverse_lazy("user_accounts-profile")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = None
self.profile = None
def get_user_and_profile(self):
self.user = self.user or self.request.user
self.profile = self.profile or self.user.profile
def get_initial(self):
self.get_user_and_profile()
return {
'name': self.profile.name
}
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
self.get_user_and_profile()
context.update(
user=self.user, profile=self.profile)
EventsService.user_login(self)
return context
def form_valid(self, form, *args, **kwargs):
profile = self.request.user.profile
profile.name = form.cleaned_data['name']
profile.save()
return super().form_valid(form)
class PasswordResetView(allauth_views.PasswordResetView):
template_name = 'user_accounts/request_password_reset.jinja'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# if there is an login email in the session
login_email = self.request.session.get('failed_login_email', '')
initial_email = context['form'].initial.get('email', '')
if not initial_email:
context['form'].initial['email'] = login_email
EventsService.user_reset_password(self, initial_email)
return context
class PasswordResetSentView(allauth_views.PasswordResetDoneView):
template_name = 'user_accounts/password_reset_sent.jinja'
class PasswordResetFromKeyView(allauth_views.PasswordResetFromKeyView):
template_name = 'user_accounts/change_password.jinja'
def get_form_class(self):
return forms.SetPasswordForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['reset_user'] = getattr(self, 'reset_user', None)
return context
class PasswordChangeView(allauth_views.PasswordChangeView):
template_name = 'user_accounts/change_password.jinja'
success_url = reverse_lazy("user_accounts-profile")
def get_form_class(self):
return forms.SetPasswordForm
class MailgunBouncedEmailView(View):
def post(self, request):
if not is_a_valid_mailgun_post(request):
raise Http404
to = request.POST['recipient']
error = request.POST['error']
headers = dict(json.loads(request.POST['message-headers']))
sender = headers['Sender']
subject = headers['Subject']
date = headers['Date']
bounce_message = """
A notification you sent through Clear My Record could not be delivered.
Date: {date}
Applicant email: {to}
Email subject: {subject}
Error:
{error}
Let us know if you have any questions,
Clear My Record Team
[email protected]
""".format(date=date, to=to, subject=subject, error=error)
send_mail(
subject='Clear My Record: An applicant notification bounced',
message=bounce_message,
html_message=bounce_message.replace('\n', '<br>'),
from_email=settings.MAIL_DEFAULT_SENDER,
recipient_list=[sender],
fail_silently=False)
return HttpResponse()
|
from .opt_setup import *
def test_project_to_ball():
n = 32
x = random.normal(keys[0], (n,))
y = opt.project_to_ball(x)
def test_project_to_box():
n = 32
x = random.normal(keys[0], (n,))
y = opt.project_to_box(x)
def test_project_to_real_upper_limit():
n = 32
x = random.normal(keys[0], (n,))
y = opt.project_to_real_upper_limit(x)
def test_shrinkage():
n = 32
x = random.normal(keys[0], (n,))
y = opt.shrink(x, 0.5)
|
import json
import os
import unittest
from onedrivesdk.helpers.http_provider_with_proxy import HttpProviderWithProxy
from onedrived import get_resource, od_auth, od_api_session
def get_sample_authenticator():
auth = od_auth.OneDriveAuthenticator()
session_params = json.loads(get_resource('data/session_response.json', pkg_name='tests'))
session_params['token_type'] = 'code'
session_params['client_id'] = auth.APP_CLIENT_ID
session_params['scope_string'] = session_params['scope']
session_params['redirect_uri'] = auth.APP_REDIRECT_URL
session_params['auth_server_url'] = 'https://localhost/auth'
del session_params['scope']
auth.client.auth_provider._session = od_api_session.OneDriveAPISession(**session_params)
auth.refresh_session = lambda x: None
return auth
class TestOneDriveAuthenticator(unittest.TestCase):
def test_get_auth_url(self):
authenticator = od_auth.OneDriveAuthenticator()
self.assertIsInstance(authenticator.get_auth_url(), str)
def test_get_proxies(self):
for k in ('http_proxy', 'HTTP_PROXY', 'https_proxy', 'HTTPS_PROXY'):
os.environ[k] = 'http://foo/bar'
authenticator = od_auth.OneDriveAuthenticator()
self.assertIsInstance(authenticator.client.http_provider, HttpProviderWithProxy)
self.assertEqual({k.split('_')[0].lower(): 'http://foo/bar'}, authenticator.client.http_provider.proxies)
del os.environ[k]
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
"""
tossi.coda
~~~~~~~~~~
Coda is final consonant in a Korean syllable. That is important because
required when determining a particle allomorph in Korean.
This module implements :func:`guess_coda` and related functions to guess a
coda from any words as correct as possible.
:copyright: (c) 2016-2017 by What! Studio
:license: BSD, see LICENSE for more details.
"""
from bisect import bisect_right
from decimal import Decimal
import re
import unicodedata
from tossi.hangul import split_phonemes
__all__ = ['filter_only_significant', 'guess_coda',
'guess_coda_from_significant_word', 'pick_coda_from_decimal',
'pick_coda_from_letter']
#: Matches to a decimal at the end of a word.
DECIMAL_PATTERN = re.compile(r'[0-9]+(\.[0-9]+)?$')
def guess_coda(word):
"""Guesses the coda of the given word as correct as possible. If it fails
to guess the coda, returns ``None``.
"""
word = filter_only_significant(word)
return guess_coda_from_significant_word(word)
def guess_coda_from_significant_word(word):
if not word:
return None
decimal_m = DECIMAL_PATTERN.search(word)
if decimal_m:
return pick_coda_from_decimal(decimal_m.group(0))
return pick_coda_from_letter(word[-1])
# Patterns which match to significant or insignificant letters at the end of
# words.
INSIGNIFICANT_PARENTHESIS_PATTERN = re.compile(r'\(.*?\)$')
SIGNIFICANT_UNICODE_CATEGORY_PATTERN = re.compile(r'^([LN].|S[cmo])$')
def filter_only_significant(word):
"""Gets a word which removes insignificant letters at the end of the given
word::
>>> pick_significant(u'넥슨(코리아)')
넥슨
>>> pick_significant(u'메이플스토리...')
메이플스토리
"""
if not word:
return word
# Unwrap a complete parenthesis.
if word.startswith(u'(') and word.endswith(u')'):
return filter_only_significant(word[1:-1])
x = len(word)
while x > 0:
x -= 1
l = word[x]
# Skip a complete parenthesis.
if l == u')':
m = INSIGNIFICANT_PARENTHESIS_PATTERN.search(word[:x + 1])
if m is not None:
x = m.start()
continue
# Skip unreadable characters such as punctuations.
unicode_category = unicodedata.category(l)
if not SIGNIFICANT_UNICODE_CATEGORY_PATTERN.match(unicode_category):
continue
break
return word[:x + 1]
def pick_coda_from_letter(letter):
"""Picks only a coda from a Hangul letter. It returns ``None`` if the
given letter is not Hangul.
"""
try:
__, __, coda = \
split_phonemes(letter, onset=False, nucleus=False, coda=True)
except ValueError:
return None
else:
return coda
# Data for picking coda from a decimal.
DIGITS = u'영일이삼사오육칠팔구'
EXPS = {1: u'십', 2: u'백', 3: u'천', 4: u'만',
8: u'억', 12: u'조', 16: u'경', 20: u'해',
24: u'자', 28: u'양', 32: u'구', 36: u'간',
40: u'정', 44: u'재', 48: u'극', 52: u'항하사',
56: u'아승기', 60: u'나유타', 64: u'불가사의', 68: u'무량대수',
72: u'겁', 76: u'업'}
DIGIT_CODAS = [pick_coda_from_letter(x[-1]) for x in DIGITS]
EXP_CODAS = {exp: pick_coda_from_letter(x[-1]) for exp, x in EXPS.items()}
EXP_INDICES = list(sorted(EXPS.keys()))
# Mark the first unreadable exponent.
_unreadable_exp = max(EXP_INDICES) + 4
EXP_CODAS[_unreadable_exp] = None
EXP_INDICES.append(_unreadable_exp)
del _unreadable_exp
def pick_coda_from_decimal(decimal):
"""Picks only a coda from a decimal."""
decimal = Decimal(decimal)
__, digits, exp = decimal.as_tuple()
if exp < 0:
return DIGIT_CODAS[digits[-1]]
__, digits, exp = decimal.normalize().as_tuple()
index = bisect_right(EXP_INDICES, exp) - 1
if index < 0:
return DIGIT_CODAS[digits[-1]]
else:
return EXP_CODAS[EXP_INDICES[index]]
|
#!/usr/bin/env python
# Copyright (c) 2015, Robot Control and Pattern Recognition Group,
# Institute of Control and Computation Engineering
# Warsaw University of Technology
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Warsaw University of Technology nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYright HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Dawid Seredynski
#
import roslib
roslib.load_manifest('velma_scripts')
import rospy
import tf
from std_msgs.msg import *
from sensor_msgs.msg import *
from geometry_msgs.msg import *
from visualization_msgs.msg import *
import tf
from tf import *
from tf.transformations import *
import tf_conversions.posemath as pm
from tf2_msgs.msg import *
import PyKDL
import math
import numpy as np
import velma_common.velmautils as velmautils
import random
class TestQ5Q6:
"""
"""
def __init__(self):
self.pub_marker = velmautils.MarkerPublisher()
def spin(self):
from sensor_msgs.msg import JointState
js = {}
def jsCallback(data):
joint_idx = 0
for joint_name in data.name:
js[joint_name] = data.position[joint_idx]
joint_idx += 1
joint_states_listener = rospy.Subscriber('/joint_states', JointState, jsCallback)
tab2=[
[ -0.397855401039,-2.90307354927],
[ 1.79,-2.91307354927],
[ 1.78,-1.43123674393],
[ 0.77621114254,-1.39720571041],
[ 0.36,-1.00585031509],
[ 0.35,0.414940297604],
[ 0.8,0.942419290543],
[ 1.8,1.01898884773],
[ 1.81,2.88],
[ -0.4,2.89],
[ -0.81,2.27813267708],
[ -1.82,2.29514837265],
[ -1.83,-1.66945314407],
[ -0.84,-1.73751521111],
[ -0.423378348351,-2.09483933449]]
m_id = 0
for pt in tab2:
m_id = self.pub_marker.publishSinglePointMarker(PyKDL.Vector(pt[0], pt[1], 0.0), m_id, r=1, g=0, b=0, m_type=Marker.SPHERE, frame_id='world', namespace='edges', scale=Vector3(0.05, 0.05, 0.05))
rospy.sleep(0.01)
# print velmautils.point_inside_polygon(0.390823, 0.15054, tab2)
# m_id = self.pub_marker.publishSinglePointMarker(PyKDL.Vector(0.390823, 0.15054, 0.0), m_id, r=1, g=1, b=1, m_type=Marker.SPHERE, frame_id='world', namespace='edges', scale=Vector3(0.05, 0.05, 0.05))
# rospy.sleep(1.01)
# return
# for i in range(10000):
# x = random.uniform(-1.9, 1.9)
# y = random.uniform(-2.92, 2.9)
# if not velmautils.point_inside_polygon(x, y, tab2):
# m_id = self.pub_marker.publishSinglePointMarker(PyKDL.Vector(x, y, 0.0), m_id, r=1, g=0, b=0, m_type=Marker.SPHERE, frame_id='world', namespace='edges', scale=Vector3(0.05, 0.05, 0.05))
# if (i%1000) == 0:
# rospy.sleep(0.01)
print "ok"
# return
q5_prev = 0.0
q6_prev = 0.0
while not rospy.is_shutdown():
rospy.sleep(0.01)
if not "left_arm_5_joint" in js or not "left_arm_6_joint" in js:
continue
# q5 = -js["left_arm_5_joint"]
# q6 = -js["left_arm_6_joint"]
q5 = js["right_arm_5_joint"]
q6 = js["right_arm_6_joint"]
# print velmautils.point_inside_polygon(q5,q6,tab2)
q5_d = q5-q5_prev
q6_d = q6-q6_prev
dist = math.sqrt(q5_d*q5_d + q6_d*q6_d)
if dist > 2.0/180.0*math.pi:
q5_prev = q5
q6_prev = q6
m_id = self.pub_marker.publishSinglePointMarker(PyKDL.Vector(q5, q6, 0.0), m_id, r=1, g=1, b=1, m_type=Marker.SPHERE, frame_id='world', namespace='edges', scale=Vector3(0.05, 0.05, 0.05))
if __name__ == '__main__':
rospy.init_node('q5q6_self_collision_test')
task = TestQ5Q6()
rospy.sleep(1)
task.spin()
|
from django import template
import readtime
import math
register = template.Library()
def read(html):
with_text = readtime.of_html(html)
result = math.ceil(with_text.seconds / 60)
return result
register.filter('readtime', read)
|
from .telebot import TeleBot
from .wxworkbot import WxWorkBot
from .dingbot import DingBot |
import rdflib
import rdfextras
rdfextras.registerplugins()
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
from pandas import DataFrame
'''
sparql.py: part of the nidmviewer package
Sparwl queries
'''
def do_query(ttl_file,query,rdf_format="turtle",serialize_format="csv",output_df=True):
g = rdflib.Graph()
g.parse(ttl_file,format=rdf_format)
result = g.query(query)
result = result.serialize(format=serialize_format)
if output_df == True:
result = StringIO(result)
return DataFrame.from_csv(result,sep=",")
else:
return result
def get_coordinates(ttl_file):
query = """
SELECT DISTINCT ?name ?coordinate ?z_score ?peak_name ?pvalue_uncorrected
WHERE {?coord a nidm:NIDM_0000015 ;
rdfs:label ?name ;
nidm:NIDM_0000086 ?coordinate .
?peak prov:atLocation ?coord ;
nidm:NIDM_0000092 ?z_score ;
rdfs:label ?peak_name ;
nidm:NIDM_0000116 ?pvalue_uncorrected .}
ORDER BY ?name
"""
return do_query(ttl_file,query)
def get_brainmaps(ttl_file):
query = """
PREFIX nidm: <http://purl.org/nidash/nidm#>
PREFIX prov: <http://www.w3.org/ns/prov#>
prefix nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>
SELECT ?filename ?location WHERE
{ ?file prov:atLocation ?location .
?file nfo:fileName ?filename .
FILTER regex(?filename, "TS*")
}
"""
return do_query(ttl_file,query)
def get_coordinates_and_maps(ttl_file):
query = """
PREFIX nidm: <http://purl.org/nidash/nidm#>
PREFIX prov: <http://www.w3.org/ns/prov#>
prefix nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>
prefix spm: <http://purl.org/nidash/spm#>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix peak: <http://purl.org/nidash/nidm#NIDM_0000062>
prefix significant_cluster: <http://purl.org/nidash/nidm#NIDM_0000070>
prefix coordinate: <http://purl.org/nidash/nidm#NIDM_0000086>
prefix equivalent_zstatistic: <http://purl.org/nidash/nidm#NIDM_0000092>
prefix pvalue_fwer: <http://purl.org/nidash/nidm#NIDM_0000115>
prefix pvalue_uncorrected: <http://purl.org/nidash/nidm#NIDM_0000116>
prefix statistic_map: <http://purl.org/nidash/nidm#NIDM_0000076>
prefix statistic_type: <http://purl.org/nidash/nidm#NIDM_0000123>
SELECT DISTINCT ?statmap ?statmap_location ?statmap_type ?z_score ?pvalue_uncorrected ?coordinate_id ?coord_name ?coordinate
WHERE {
?statmap a statistic_map: ;
statistic_type: ?statmap_type ;
prov:atLocation ?statmap_location .
?peak prov:wasDerivedFrom/prov:wasDerivedFrom/prov:wasGeneratedBy/prov:used ?statmap ;
prov:atLocation ?coord ;
equivalent_zstatistic: ?z_score ;
pvalue_uncorrected: ?pvalue_uncorrected ;
prov:atLocation ?coordinate_id .
?coordinate_id rdfs:label ?coord_name ;
coordinate: ?coordinate .
}
"""
return do_query(ttl_file,query)
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Request body validating middleware for OpenStack Identity resources."""
import functools
from keystone.common.validation import validators
def validated(request_body_schema, resource_to_validate):
"""Register a schema to validate a resource reference.
Registered schema will be used for validating a request body just before
API method execution.
:param request_body_schema: a schema to validate the resource reference
:param resource_to_validate: the reference to validate
"""
schema_validator = validators.SchemaValidator(request_body_schema)
def add_validator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if resource_to_validate in kwargs:
schema_validator.validate(kwargs[resource_to_validate])
return func(*args, **kwargs)
return wrapper
return add_validator
def nullable(property_schema):
"""Clone a property schema into one that is nullable.
:param dict property_schema: schema to clone into a nullable schema
:returns: a new dict schema
"""
# TODO(dstanek): deal with the case where type is already a list; we don't
# do that yet so I'm not wasting time on it
new_schema = property_schema.copy()
new_schema['type'] = [property_schema['type'], 'null']
return new_schema
def add_array_type(property_schema):
"""Convert the parameter schema to be of type list.
:param dict property_schema: schema to add array type to
:returns: a new dict schema
"""
new_schema = property_schema.copy()
new_schema['type'] = [property_schema['type'], 'array']
return new_schema
|
class Solution:
def calPoints(self, ops: List[str]) -> int:
scores = []
for op in ops:
if op=="D":
scores.append(scores[-1] * 2)
elif op=="+":
scores.append(scores[-1] +scores[-2])
elif op=="C":
scores.pop()
else:
scores.append(int(op))
return sum(scores) |
import os
from invoke import task
@task
def clean(ctx):
"""
Clean pyc files and build assets.
"""
join = os.path.join
rm_files = []
rm_dirs = []
for base, subdirs, files in os.walk("."):
if "__pycache__" in subdirs:
rm_dirs.append(join(base, "__pycache__"))
elif os.path.basename(base) == "__pycache__":
rm_files.extend(join(base, f) for f in files)
print("Removing compiled bytecode files")
for path in rm_files:
os.unlink(path)
for path in rm_dirs:
os.rmdir(path)
|
import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
from src.util import init_weights, init_gate
from src.module import VGGExtractor, CNNExtractor, RNNLayer, ScaleDotAttention, LocationAwareAttention
class ASR(nn.Module):
''' ASR model, including Encoder/Decoder(s)'''
def __init__(self, input_size, vocab_size, init_adadelta, ctc_weight, encoder, attention, decoder, emb_drop=0.0):
super(ASR, self).__init__()
# Setup
assert 0 <= ctc_weight <= 1
self.vocab_size = vocab_size
self.ctc_weight = ctc_weight
self.enable_ctc = ctc_weight > 0
self.enable_att = ctc_weight != 1
self.lm = None
# Modules
self.encoder = Encoder(input_size, **encoder) ## NOTE: Encoder Here
if self.enable_ctc:
self.ctc_layer = nn.Linear(self.encoder.out_dim, vocab_size) ## why?
if self.enable_att:
self.dec_dim = decoder['dim']
self.pre_embed = nn.Embedding(vocab_size, self.dec_dim)
self.embed_drop = nn.Dropout(emb_drop)
self.decoder = Decoder(
self.encoder.out_dim+self.dec_dim, vocab_size, **decoder) ## NOTE: Decoder Here
query_dim = self.dec_dim*self.decoder.layer
self.attention = Attention(
self.encoder.out_dim, query_dim, **attention)
# Init
if init_adadelta:
self.apply(init_weights)
if self.enable_att:
for l in range(self.decoder.layer):
## LSTM/GRU layer here is a group of N layers of network, so each layer needs to init their weights.
bias = getattr(self.decoder.layers, 'bias_ih_l{}'.format(l))
bias = init_gate(bias)
def set_state(self, prev_state, prev_attn):
''' Setting up all memory states for beam decoding'''
self.decoder.set_state(prev_state)
self.attention.set_mem(prev_attn)
def create_msg(self):
# Messages for user
msg = []
msg.append('Model spec.| Encoder\'s downsampling rate of time axis is {}.'.format(
self.encoder.sample_rate))
if self.encoder.vgg:
msg.append(' | VGG Extractor w/ time downsampling rate = 4 in encoder enabled.')
if self.encoder.cnn:
msg.append(' | CNN Extractor w/ time downsampling rate = 4 in encoder enabled.')
if self.enable_ctc:
msg.append(' | CTC training on encoder enabled ( lambda = {}).'.format(
self.ctc_weight))
if self.enable_att:
msg.append(' | {} attention decoder enabled ( lambda = {}).'.format(
self.attention.mode, 1-self.ctc_weight))
return msg
def forward(self, audio_feature, feature_len, decode_step, tf_rate=0.0, teacher=None,
emb_decoder=None, get_dec_state=False):
'''
Arguments
audio_feature - [BxTxD] Acoustic feature with shape
feature_len - [B] Length of each sample in a batch
decode_step - [int] The maximum number of attention decoder steps
tf_rate - [0,1] The probability to perform teacher forcing for each step
teacher - [BxL] Ground truth for teacher forcing with sentence length L
emb_decoder - [obj] Introduces the word embedding decoder, different behavior for training/inference
At training stage, this ONLY affects self-sampling (output remains the same)
At inference stage, this affects output to become log prob. with distribution fusion
get_dec_state - [bool] If true, return decoder state [BxLxD] for other purpose
'''
# Init
bs = audio_feature.shape[0]
ctc_output, att_output, att_seq = None, None, None
dec_state = [] if get_dec_state else None
# Encode
encode_feature, encode_len = self.encoder(audio_feature, feature_len)
# CTC based decoding
if self.enable_ctc:
ctc_output = F.log_softmax(self.ctc_layer(encode_feature), dim=-1)
# Attention based decoding
if self.enable_att:
# Init (init char = <SOS>, reset all rnn state and cell)
self.decoder.init_state(bs)
self.attention.reset_mem()
last_char = self.pre_embed(torch.zeros(
(bs), dtype=torch.long, device=encode_feature.device))
att_seq, output_seq = [], []
# Preprocess data for teacher forcing
if teacher is not None:
teacher = self.embed_drop(self.pre_embed(teacher))
# Decode
for t in range(decode_step):
## NOTE: ATTEND
# Attend (inputs current state of first layer, encoded features)
attn, context = self.attention(
self.decoder.get_query(), encode_feature, encode_len)
## NOTE: DECODE
# Decode (inputs context + embedded last character)
decoder_input = torch.cat([last_char, context], dim=-1)
cur_char, d_state = self.decoder(decoder_input)
# Prepare output as input of next step
if (teacher is not None):
# Training stage
if (tf_rate == 1) or (torch.rand(1).item() <= tf_rate):
# teacher forcing
last_char = teacher[:, t, :]
else:
# self-sampling (replace by argmax may be another choice)
with torch.no_grad():
if (emb_decoder is not None) and emb_decoder.apply_fuse:
_, cur_prob = emb_decoder(
d_state, cur_char, return_loss=False)
else:
cur_prob = cur_char.softmax(dim=-1)
sampled_char = Categorical(cur_prob).sample()
last_char = self.embed_drop(
self.pre_embed(sampled_char))
else:
# Inference stage
if (emb_decoder is not None) and emb_decoder.apply_fuse:
_, cur_char = emb_decoder(
d_state, cur_char, return_loss=False)
# argmax for inference
last_char = self.pre_embed(torch.argmax(cur_char, dim=-1))
# save output of each step
output_seq.append(cur_char)
att_seq.append(attn)
if get_dec_state:
dec_state.append(d_state)
att_output = torch.stack(output_seq, dim=1) # BxTxV
att_seq = torch.stack(att_seq, dim=2) # BxNxDtxT
if get_dec_state:
dec_state = torch.stack(dec_state, dim=1)
return ctc_output, encode_len, att_output, att_seq, dec_state
class Decoder(nn.Module):
''' Decoder (a.k.a. Speller in LAS) '''
# ToDo: More elegant way to implement decoder
def __init__(self, input_dim, vocab_size, module, dim, layer, dropout):
super(Decoder, self).__init__()
self.in_dim = input_dim
self.layer = layer
self.dim = dim
self.dropout = dropout
# Init
assert module in ['LSTM', 'GRU'], NotImplementedError
self.hidden_state = None
self.enable_cell = module == 'LSTM'
# Modules
'''getattr Calls with str, equals nn.${module}'''
self.layers = getattr(nn, module)(
input_dim, dim, num_layers=layer, dropout=dropout, batch_first=True)
self.char_trans = nn.Linear(dim, vocab_size)
self.final_dropout = nn.Dropout(dropout)
def init_state(self, bs):
''' Set all hidden states to zeros '''
device = next(self.parameters()).device
if self.enable_cell:
self.hidden_state = (torch.zeros((self.layer, bs, self.dim), device=device),
torch.zeros((self.layer, bs, self.dim), device=device))
else:
self.hidden_state = torch.zeros(
(self.layer, bs, self.dim), device=device)
return self.get_state()
def set_state(self, hidden_state):
''' Set all hidden states/cells, for decoding purpose'''
device = next(self.parameters()).device
if self.enable_cell:
self.hidden_state = (hidden_state[0].to(
device), hidden_state[1].to(device))
else:
self.hidden_state = hidden_state.to(device)
def get_state(self):
''' Return all hidden states/cells, for decoding purpose'''
if self.enable_cell:
return (self.hidden_state[0].cpu(), self.hidden_state[1].cpu())
else:
return self.hidden_state.cpu()
def get_query(self):
''' Return state of all layers as query for attention '''
if self.enable_cell:
return self.hidden_state[0].transpose(0, 1).reshape(-1, self.dim*self.layer)
else:
return self.hidden_state.transpose(0, 1).reshape(-1, self.dim*self.layer)
def forward(self, x):
''' Decode and transform into vocab '''
if not self.training:
self.layers.flatten_parameters()
x, self.hidden_state = self.layers(x.unsqueeze(1), self.hidden_state)
x = x.squeeze(1)
char = self.char_trans(self.final_dropout(x))
return char, x
class Attention(nn.Module):
''' Attention mechanism
please refer to http://www.aclweb.org/anthology/D15-1166 section 3.1 for more details about Attention implementation
Input : Decoder state with shape [batch size, decoder hidden dimension]
Compressed feature from Encoder with shape [batch size, T, encoder feature dimension]
Output: Attention score with shape [batch size, num head, T (attention score of each time step)]
Context vector with shape [batch size, encoder feature dimension]
(i.e. weighted (by attention score) sum of all timesteps T's feature) '''
def __init__(self, v_dim, q_dim, mode, dim, num_head, temperature, v_proj,
loc_kernel_size, loc_kernel_num):
super(Attention, self).__init__()
# Setup
self.v_dim = v_dim
self.dim = dim
self.mode = mode.lower()
self.num_head = num_head
# Linear proj. before attention
## Q, K, V
self.proj_q = nn.Linear(q_dim, dim*num_head)
self.proj_k = nn.Linear(v_dim, dim*num_head)
self.v_proj = v_proj
if v_proj:
self.proj_v = nn.Linear(v_dim, v_dim*num_head)
# Attention
if self.mode == 'dot':
self.att_layer = ScaleDotAttention(temperature, self.num_head)
elif self.mode == 'loc':
self.att_layer = LocationAwareAttention(
loc_kernel_size, loc_kernel_num, dim, num_head, temperature)
else:
raise NotImplementedError
# Layer for merging MHA
if self.num_head > 1:
self.merge_head = nn.Linear(v_dim*num_head, v_dim)
# Stored feature
self.key = None
self.value = None
self.mask = None
def reset_mem(self):
self.key = None
self.value = None
self.mask = None
self.att_layer.reset_mem()
def set_mem(self, prev_attn):
self.att_layer.set_mem(prev_attn)
def forward(self, dec_state, enc_feat, enc_len):
# Preprecessing
bs, ts, _ = enc_feat.shape
query = torch.tanh(self.proj_q(dec_state))
query = query.view(bs, self.num_head, self.dim).view(
bs*self.num_head, self.dim) # BNxD
if self.key is None:
# Maskout attention score for padded states
self.att_layer.compute_mask(enc_feat, enc_len.to(enc_feat.device))
# Store enc state to lower computational cost
self.key = torch.tanh(self.proj_k(enc_feat))
self.value = torch.tanh(self.proj_v(
enc_feat)) if self.v_proj else enc_feat # BxTxN
if self.num_head > 1:
self.key = self.key.view(bs, ts, self.num_head, self.dim).permute(
0, 2, 1, 3) # BxNxTxD
self.key = self.key.contiguous().view(bs*self.num_head, ts, self.dim) # BNxTxD
if self.v_proj:
self.value = self.value.view(
bs, ts, self.num_head, self.v_dim).permute(0, 2, 1, 3) # BxNxTxD
self.value = self.value.contiguous().view(
bs*self.num_head, ts, self.v_dim) # BNxTxD
else:
self.value = self.value.repeat(self.num_head, 1, 1)
# Calculate attention
context, attn = self.att_layer(query, self.key, self.value)
if self.num_head > 1:
context = context.view(
bs, self.num_head*self.v_dim) # BNxD -> BxND
context = self.merge_head(context) # BxD
return attn, context
class Encoder(nn.Module):
''' Encoder (a.k.a. Listener in LAS)
Encodes acoustic feature to latent representation, see config file for more details.'''
def __init__(self, input_size, prenet, module, bidirection, dim, dropout, layer_norm, proj, sample_rate, sample_style):
super(Encoder, self).__init__()
# Hyper-parameters checking
self.vgg = prenet == 'vgg'
self.cnn = prenet == 'cnn'
self.sample_rate = 1
assert len(sample_rate) == len(dropout), 'Number of layer mismatch'
assert len(dropout) == len(dim), 'Number of layer mismatch'
num_layers = len(dim)
assert num_layers >= 1, 'Encoder should have at least 1 layer'
# Construct model
module_list = []
input_dim = input_size
# Prenet on audio feature
if self.vgg:
extractor = VGGExtractor(input_size)
if self.cnn:
extractor = CNNExtractor(input_size, out_dim=dim[0])
module_list.append(extractor)
input_dim = vgg_extractor.out_dim
self.sample_rate = self.sample_rate*4
# Recurrent encoder
if module in ['LSTM', 'GRU']:
for l in range(num_layers):
module_list.append(
RNNLayer(input_dim, module, dim[l], bidirection,
dropout[l], layer_norm[l],sample_rate[l], sample_style, proj[l]))
input_dim = module_list[-1].out_dim
self.sample_rate = self.sample_rate*sample_rate[l]
else:
raise NotImplementedError
# Build model
self.in_dim = input_size
self.out_dim = input_dim
self.layers = nn.ModuleList(module_list)
def forward(self, input_x, enc_len):
for _, layer in enumerate(self.layers):
input_x, enc_len = layer(input_x, enc_len) ## NOTE: Simple sequential passing.
return input_x, enc_len
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 21 12:37:40 2018
@author: slauniai
"""
import os
#import spotpy
import pickle
import numpy as np
from scipy import stats
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from spathy_sve import SpatHy, initialize_netCDF, read_setup
from iotools import create_catchment
eps = np.finfo(float).eps
spathy_path = os.path.join('c:\\repositories\\spathy')
setupfile = os.path.join(spathy_path, 'ini', 'spathy_default.ini')
""" catchment data: id, start_date, end_date, spinup_end, top_m """
chm=[['1', '2013-01-01', '2015-12-31', '2013-12-31', 0.025], # lompolojanganoja 514 ha
['2', '2005-01-01', '2008-12-31', '2005-12-31', 0.006], # liuhapuro 170 ha
['3', '2005-01-01', '2015-12-31', '2005-12-31', 0.026], # porkkavaara 72 ha
['10', '2005-01-01', '2013-12-31', '2005-12-31', 0.011], # kelopuro 74 ha. 2014 gappy, 2015 runoff is low
['11', '2014-01-01', '2015-12-31', '2014-12-31', 0.012], # hauklammenoja 137 ha
['13', '2014-01-01', '2015-12-31', '2014-12-31', 0.007], # rudbacken 436 ha
['14', '2005-01-01', '2015-12-31', '2005-12-31', 0.007], # paunulanpuro 154 ha
['16', '2005-01-01', '2015-12-31', '2005-12-31', 0.007], # huhtisuonoja 500 ha. very flat, large fraction is drained peatlands
['17', '2005-01-01', '2015-12-31', '2005-12-31', 0.006], # kesselinpuro 2100 ha
# ['18','2011-01-01', '2015-12-31', '2011-12-31'], # korpijoki, area 12200 ha so not suitable
['19', '2005-01-01', '2015-12-31', '2005-12-31', 0.006], # pahkaoja 2344 ha
['20', '2005-01-01', '2015-12-31', '2005-12-31', 0.009], # vaarajoki 1900 ha
['21', '2005-01-01', '2015-12-31', '2005-12-31', 0.01], # myllypuro 1053 ha
['22', '2005-01-01', '2015-12-31', '2005-12-31', 0.0095], # vaha-askanjoki 1600 ha
# [ '23','2011-01-01', '2015-12-31', '2011-12-31'], # ylijoki 5600 ha, very large and slow
['24', '2005-01-01', '2015-12-31', '2005-12-31', 0.0066], # kotioja 1800 ha
['25', '2005-01-01', '2015-12-31', '2005-12-31', 0.0095], # kohisevanpuro 1070 ha
['26', '2005-01-01', '2015-12-31', '2005-12-31', 0.02], # iittovuoma 1160 ha
['27', '2005-01-01', '2015-12-31', '2005-12-31', 0.014], # laanioja 1362 ha
['28', '2013-01-01', '2015-12-31', '2013-12-31', 0.0057], # kroopinsuo 179 ha
['29', '2012-01-01', '2015-12-31', '2012-12-31', 0.0089], # surnui 71 ha, poor data quality
['30', '2011-01-01', '2015-12-31', '2011-12-31', 0.0064], # pakopirtti 795 ha, uncertain catchment boundaries
['31', '2011-01-01', '2015-12-31', '2011-12-31', 0.0064], # ojakorpi 33 ha
['32', '2011-01-01', '2015-12-31', '2011-12-31', 0.0077], # rantainrahka 38 ha
['33', '2005-01-01', '2015-12-31', '2005-12-31', 0.009], # kivipuro 54 ha
]
# chm = chm[0:2]
"""read default parameter file into dicts"""
pgen0, pcpy0, pbu0, ptop0 = read_setup(setupfile)
# full path to soil_file
pgen0['soil_file'] = unicode(os.path.join(spathy_path, pgen0['soil_file']))
ff = [[1.0, 1.0, 1.0, 1.0], [0.8, 0.8, 0.8, 0.8], [1.2, 1.2, 1.2, 1.2]] # gsref, Wmax, Wmaxsnow, LAI multipliers
ss = ['base', 'lowET', 'hiET']
for k in [0, 1, 2]: # loop et-cases
res = []
for n in range(0, len(chm)): # loop catchments
print(chm[n])
pgen = pgen0.copy()
pcpy = pcpy0.copy()
pbu = pbu0.copy()
ptop = ptop0.copy()
# n -loop parameters
pgen['catchment_id'] = chm[n][0]
pgen['start_date'] = chm[n][1]
pgen['end_date'] = chm[n][2]
pgen['spinup_end'] = chm[n][3]
pgen['outname'] = 'Ch' + pgen['catchment_id'] + '-' + ss[k] + '.nc'
ptop['m'] = chm[n][4]
# k -loop changes
pcpy['gsref_conif'] *= ff[k][0]
pcpy['gsref_decid'] *= ff[k][0]
pcpy['wmax'] *= ff[k][1]
pcpy['wmaxsnow'] *= ff[k][2]
pcpy['lai_multip'] =ff[k][3]
print(k, n, pgen['outname'])
# run baseline simulation, return nothing
# if k == 0:
# spa = spathy_run_sve(cid, pgen, pcpy, pbu, ptop)
# else:
spa = spathy_run_sve(pgen, pcpy, pbu, ptop, ncf=False, ave_outputs=True)
res.append(spa.results)
del pgen, pbu, ptop
# dump into pickle
ou = os.path.join(pgen0['output_folder'], 'R-' + ss[k] + '.pkl')
pickle.dump(res, open(ou, 'wb'))
#%%
def spathy_run_sve(pgen, pcpy, pbu, ptop, ncf=True, ave_outputs=True, flatten=True):
"""
Spathy_driver for running sve catchments
OUT:
spa - spathy object
outf - filepath to netCDF-file. if ncf=False, returns None
"""
gisdata = create_catchment(pgen['catchment_id'], fpath=pgen['gis_folder'],
plotgrids=False, plotdistr=False)
gisdata['LAI_conif'] *= pcpy['lai_multip']
gisdata['LAI_decid'] *= pcpy['lai_multip']
""" greate SpatHy object """
spa = SpatHy(pgen, pcpy, pbu, ptop, gisdata, ave_outputs=ave_outputs, flatten=True)
Nsteps = spa.Nsteps
""" create netCDF output file """
if ncf:
ncf, _= initialize_netCDF(spa.id, spa.GisData, spa.FORC,
fpath=spa.pgen['output_folder'],
fname=pgen['outname'])
#3d array indexing: dim1=time, dim2=rows(lat), dim3=cols(lon). W[1,:,:] --> grid at 1st timestep.
""" ----- MAIN CALCULATION LOOP ----- """
print '******* Running Spathy ********'
spa._run(0, Nsteps, calibr=False, ncf=ncf)
print '********* done *********'
return spa
|
"""
[ #476580 ] 'del obj.non_member' : wrong exception
"""
import support
class C : pass
o = C()
try:
o.foo
except AttributeError:
pass
try:
del o.foo
except AttributeError:
pass
|
from django.test import TestCase
import requests, json
# Create your tests here.
base = 'http://localhost:8000/api/'
header = {'Content-Type': 'application/json'}
class myTest(TestCase):
@classmethod
def setUpTestData(cls):
# print("setUpTestData: Run once to set up non-modified data for all class methods.")
pass
def setUp(self):
# print("setUp: Run once for every test method to setup clean data.")
pass
'''
Test case signup
'''
def test_signup(self):
payload = {'username': 'aa', 'password': 'aa', 'email': 'gg'+'@gmail.com'}
r = requests.post(base + 'register', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,201)
'''
Test case login
'''
def test_login(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,202)
payload = {'email': '[email protected]', 'password': 'a'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,403)
'''
Test case logout
'''
def test_logout(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,202)
token = r.json()['token']
header['Authorization'] = 'Token ' + token
r = requests.post(base + 'logout', headers = header)
self.assertEqual(r.status_code,200)
'''
Test case getUser
'''
def test_get_user(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,202)
token = r.json()['token']
header['Authorization'] = 'Token ' + token
r = requests.get(base + 'get_personal_info', headers = header)
self.assertEqual(r.json()['username'],'[email protected]')
r = requests.get(base+'get_user_by_id?uid=2')
self.assertEqual(r.json()['username'],'[email protected]')
r = requests.get(base+'get_user_by_id?uid=-1')
self.assertEqual(r.status_code,404)
r = requests.get(base+'[email protected]')
self.assertEqual(r.json()['username'],'[email protected]')
'''
Test follow and unfollow for user
'''
def test_follow(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
token = r.json()['token']
header['Authorization'] = 'Token ' + token
payload = {'uid': 1}
r = requests.post(base + 'follow_by_id', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,404)
header['Authorization'] = 'Token ' + token
payload = {'uid': 3}
r = requests.post(base + 'follow_by_id', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,201)
r = requests.post(base + 'unfollow_by_id', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,200)
'''
Test get and upload video
'''
def test_video(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
token = r.json()['token']
payload = {'name': 'video1', 'description':'1', 'address':'1', 'category':'1'}
r = requests.post(base + 'upload_video', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,201)
r = requests.get(base + 'get_video_by_id?vid=5', headers = header)
self.assertEqual(r.json()['name'], 'video1')
payload = {'name': 'video2', 'description':'1', 'address':'1', 'category':'1'}
r = requests.post(base + 'upload_video', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,201)
r = requests.get(base + '[email protected]', headers = header)
print(r.json())
'''
Test like video
'''
def test_like_video(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
token = r.json()['token']
header['Authorization'] = 'Token ' + token
payload = {'vid': 5}
r = requests.post(base + 'like_video', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,200)
r = requests.delete(base + 'like_video_cancel', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,200)
r = requests.post(base + 'dislike_video', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,200)
r = requests.delete(base + 'dislike_video_cancel', data=json.dumps(payload), headers = header)
self.assertEqual(r.status_code,200)
'''
Test add and get comment
'''
def test_comment(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
token = r.json()['token']
header['Authorization'] = 'Token ' + token
payload = {'vid':5, 'content':'hhhh', 'parent_cid':-1}
r = requests.post(base + 'add_comment', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,200)
r = requests.get(base + 'get_comments?vid=5')
print(r.json())
'''
Test add and get community message
'''
def test_community_message(self):
payload = {'email': '[email protected]', 'password': 'aa'}
r = requests.post(base + 'login', data=json.dumps(payload), headers=header)
token = r.json()['token']
header['Authorization'] = 'Token ' + token
payload = {'message':'lol'}
r = requests.post(base + 'add_message', data=json.dumps(payload), headers=header)
self.assertEqual(r.status_code,201)
r = requests.get(base + 'get_messages_by_user_id?uid=2')
print(r.json()) |
""" Module Logger """
from app import app # retreive app object
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from time import strftime
from flask import Flask, render_template, request
if not app.debug:
# Mail Logging
if app.config['MAIL_LOGGING']:
auth = None
if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
secure = None
if app.config['MAIL_USE_TLS']:
secure = ()
mail_handler = SMTPHandler(
mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
fromaddr='no-reply@' + app.config['MAIL_SERVER'],
toaddrs=app.config['ADMINS'], subject='Microblog Failure',
credentials=auth, secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
# File Logging
if app.config['FILE_LOGGING']:
if not os.path.exists(app.config['LOGGING_PATH']):
os.mkdir('logs')
file_handler = RotatingFileHandler(
app.config['LOGGING_PATH'] + '/' + app.config['LOGFILE'], maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(app.config['LOGGING_FORMAT']))
file_handler.setLevel(app.config['LOGGING_LEVEL'])
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info("\n\n*** " + app.config['LOGFILE'] + ' startup')
def logTrace(code_info="missing code information", exc_info="user log info missing"):
app.logger.error(
"""
--------------------------------------------------------------------
Date : {dt}
Request: {method} {path}
IP: {ip}
User: {user}
Agent: {agent_platform} | {agent_browser} {agent_browser_version}
Raw Agent: {agent}
Code Info: {code_info}
""".format(
dt=strftime('[%Y-%b-%d %H:%M]'),
method=request.method,
path=request.path,
ip=request.remote_addr,
agent_platform=request.user_agent.platform,
agent_browser=request.user_agent.browser,
agent_browser_version=request.user_agent.version,
agent=request.user_agent.string,
user="tdb",
code_info=code_info
), exc_info=exc_info
)
@app.errorhandler(405)
def page_not_found(error):
logTrace('Error 404')
return render_template('404.html'), 404
@app.errorhandler(404)
def page_not_found(error):
logTrace('Error 404')
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
logTrace('Error 500')
return render_template('500.html'), 500
|
# coding: utf-8
# In[1]:
print("Hello UTC")
|
# This program displays ten balls with random colors and placed at random locations,
from tkinter import * # Import tkinter
from random import randint
class RandomBalls:
def __init__(self):
window = Tk() # Create a window
window.title("Random Balls") # Set title
x = 100
y = 100
self.canvas = Canvas(window, width=width, height=height)
self.canvas.pack()
Button(window, text="Display", command=self.display).pack()
window.mainloop() # Create an event loop
def display(self):
self.canvas.delete("ball")
for i in range(10):
x = randint(0, width - 1)
y = randint(0, height - 1)
color = "#"
for j in range(6):
color += toHexChar(randint(0, 15))
self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill=color, tags="ball")
width = 300
height = 150
radius = 4
# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
if hexValue <= 9 and hexValue >= 0:
return chr(hexValue + ord('0'))
else: # hexValue <= 15 && hexValue >= 10
return chr(hexValue - 10 + ord('A'))
RandomBalls() |
"""Provides hooks for session life-cycle events."""
import asyncio
import iterm2
class SessionTerminationMonitor:
"""
Watches for session termination.
A session is said to terminate when its command (typically `login`) has exited. If the user closes a window, tab, or split pane they can still undo closing it for some amount of time. Session termination will be delayed until it is no longer undoable.
:param connection: The :class:`~iterm2.connection.Connection` to use.
Example:
.. code-block:: python
async with iterm2.SessionTerminationMonitor(connection) as mon:
while True:
session_id = await mon.async_get()
print("Session {} closed".format(session_id))
"""
def __init__(self, connection: iterm2.Connection):
self.__connection = connection
self.__queue: asyncio.Queue = asyncio.Queue(loop=asyncio.get_event_loop())
async def __aenter__(self):
async def callback(_connection, message):
"""Called when a session terminates."""
await self.__queue.put(message.session_id)
self.__token = await iterm2.notifications.async_subscribe_to_terminate_session_notification(
self.__connection,
callback)
return self
async def async_get(self) -> str:
"""
Returns the `session_id` of a just-terminated session.
"""
session_id = await self.__queue.get()
return session_id
async def __aexit__(self, exc_type, exc, _tb):
await iterm2.notifications.async_unsubscribe(
self.__connection,
self.__token)
class LayoutChangeMonitor:
"""
Watches for changes to the composition of sessions, tabs, and windows.
:param connection: The :class:`~iterm2.connection.Connection` to use.
"""
def __init__(self, connection: iterm2.Connection):
self.__connection = connection
self.__queue: asyncio.Queue = asyncio.Queue(loop=asyncio.get_event_loop())
async def __aenter__(self):
async def callback(_connection, message):
"""Called when the layout changes."""
await self.__queue.put(message)
self.__token = await iterm2.notifications.async_subscribe_to_layout_change_notification(self.__connection, callback)
return self
async def async_get(self):
"""
Blocks until the layout changes.
Will block until any of the following occurs:
* A session moves from one tab to another (including moving into its own window).
* The relative position of sessions within a tab changes.
* A tab moves from one window to another.
* The order of tabs within a window changes.
* A session is buried or disintered.
Use :class:`~iterm2.App` to examine the updated application state.
Example:
.. code-block:: python
async with iterm2.LayoutChangeMonitor(connection) as mon:
while True:
await mon.async_get()
print("layout changed")
"""
await self.__queue.get()
async def __aexit__(self, exc_type, exc, _tb):
await iterm2.notifications.async_unsubscribe(self.__connection, self.__token)
class NewSessionMonitor:
"""Watches for the creation of new sessions.
:param connection: The :class:`~iterm2.connection.Connection` to use.
.. seealso::
* Example ":ref:`colorhost_example`"
* Example ":ref:`random_color_example`"
Example:
.. code-block:: python
async with iterm2.NewSessionMonitor(connection) as mon:
while True:
session_id = await mon.async_get()
print("Session ID {} created".format(session_id))
"""
def __init__(self, connection: iterm2.Connection):
self.__connection = connection
self.__queue: asyncio.Queue = asyncio.Queue(loop=asyncio.get_event_loop())
async def __aenter__(self):
async def callback(_connection, message):
"""Called when a new session is created."""
await self.__queue.put(message)
self.__token = await iterm2.notifications.async_subscribe_to_new_session_notification(
self.__connection,
callback)
return self
async def async_get(self) -> str:
"""Returns the new session ID."""
result = await self.__queue.get()
session_id = result.session_id
return session_id
async def __aexit__(self, exc_type, exc, _tb):
await iterm2.notifications.async_unsubscribe(self.__connection, self.__token)
|
from marshmallow import ValidationError
from marshmallow_jsonapi import fields
class CompleteNestedRelationship(fields.Relationship):
def extract_value(self, data):
"""Extract the object with data and validate the request structure."""
errors = []
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self.type_:
errors.append('Invalid `type` specified')
if errors:
raise ValidationError(errors)
data = {'data': data}
schema = self.schema
return schema.load(data)
def _serialize(self, value, attr, obj):
dict_class = self.parent.dict_class if self.parent else dict
ret = dict_class()
self_url = self.get_self_url(obj)
related_url = self.get_related_url(obj)
if self_url or related_url:
ret['links'] = dict_class()
if self_url:
ret['links']['self'] = self_url
if related_url:
ret['links']['related'] = related_url
if self.include_resource_linkage or self.include_data:
if value is None:
ret['data'] = [] if self.many else None
else:
ret['data'] = self._serialize_included(value)
return ret
def _serialize_included(self, value):
if self.many:
included_resource = []
for item in value:
data = self._serialize_included_child(item)
included_resource.append(data)
else:
included_resource = self._serialize_included_child(value)
return included_resource
def _serialize_included_child(self, value):
result = self.schema.dump(value, **self._id_map_if_exist_in_parent_schema())
if result.errors:
raise ValidationError(result.errors)
return result.data['data']
def _id_map_if_exist_in_parent_schema(self):
return {'id_map': self.parent.id_map} if hasattr(self.parent, 'id_map') else {}
|
from .reaction_classifier import classify, is_transport, is_complex_assembly
|
#!/usr/bin/env python
# coding: utf-8
"""
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
def process(node: TreeNode) -> (int, int):
"""Return the best path, and best path including node"""
if node is None:
return (0, 0, None)
lb, lp, lv = process(node.left)
rb, rp, rv = process(node.right)
bb = bp = 1
if lv == node.val:
bb += lp
bp = max(bp, 1 + lp)
if rv == node.val:
bb += rp
bp = max(bp, 1 + rp)
bb = max([bb, lb, rb])
return (bb, bp, node.val)
return process(root)[0] - 1
if __name__ == '__main__':
root = TreeNode(1)
sol = Solution().longestUnivaluePath
print(sol)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# from __future__ import annotations # isort:skip
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
from typing import Sequence
import libcst as cst
import libcst.matchers as m
from fixit import CstLintRule
from fixit import InvalidTestCase as Invalid
from fixit import ValidTestCase as Valid
class NoAssertTrueForComparisonsRule(CstLintRule):
"""
Finds incorrect use of ``assertTrue`` when the intention is to compare two values.
These calls are replaced with ``assertEqual``.
Comparisons with True, False and None are replaced with one-argument
calls to ``assertTrue``, ``assertFalse`` and ``assertIsNone``.
"""
MESSAGE: str = '"assertTrue" does not compare its arguments, use "assertEqual" or other ' + "appropriate functions."
VALID = [
Valid("self.assertTrue(a == b)"),
Valid('self.assertTrue(data.is_valid(), "is_valid() method")'),
Valid("self.assertTrue(validate(len(obj.getName(type=SHORT))))"),
Valid("self.assertTrue(condition, message_string)"),
]
INVALID = [
Invalid("self.assertTrue(a, 3)", expected_replacement="self.assertEqual(a, 3)"),
Invalid(
"self.assertTrue(hash(s[:4]), 0x1234)",
expected_replacement="self.assertEqual(hash(s[:4]), 0x1234)",
),
Invalid(
"self.assertTrue(list, [1, 3])",
expected_replacement="self.assertEqual(list, [1, 3])",
),
Invalid(
"self.assertTrue(optional, None)",
expected_replacement="self.assertIsNone(optional)",
),
Invalid(
"self.assertTrue(b == a, True)",
expected_replacement="self.assertTrue(b == a)",
),
Invalid(
"self.assertTrue(b == a, False)",
expected_replacement="self.assertFalse(b == a)",
),
]
def visit_Call(self, node: cst.Call) -> None:
result = m.extract(
node,
m.Call(
func=m.Attribute(value=m.Name("self"), attr=m.Name("assertTrue")),
args=[
m.DoNotCare(),
m.Arg(
value=m.SaveMatchedNode(
m.OneOf(
m.Integer(),
m.Float(),
m.Imaginary(),
m.Tuple(),
m.List(),
m.Set(),
m.Dict(),
m.Name("None"),
m.Name("True"),
m.Name("False"),
),
"second",
)
),
],
),
)
if result:
second_arg = result["second"]
if isinstance(second_arg, Sequence):
second_arg = second_arg[0]
if m.matches(second_arg, m.Name("True")):
new_call = node.with_changes(
args=[node.args[0].with_changes(comma=cst.MaybeSentinel.DEFAULT)],
)
elif m.matches(second_arg, m.Name("None")):
new_call = node.with_changes(
func=node.func.with_deep_changes(
old_node=cst.ensure_type(node.func, cst.Attribute).attr,
value="assertIsNone",
),
args=[node.args[0].with_changes(comma=cst.MaybeSentinel.DEFAULT)],
)
elif m.matches(second_arg, m.Name("False")):
new_call = node.with_changes(
func=node.func.with_deep_changes(
old_node=cst.ensure_type(node.func, cst.Attribute).attr,
value="assertFalse",
),
args=[node.args[0].with_changes(comma=cst.MaybeSentinel.DEFAULT)],
)
else:
new_call = node.with_deep_changes(
old_node=cst.ensure_type(node.func, cst.Attribute).attr,
value="assertEqual",
)
self.report(node, replacement=new_call)
|
"""Main module
"""
# Standard library imports
import string
# Third party imports
import numpy as np
import justpy as jp
import pandas as pd
START_INDEX: int = 1
END_INDEX: int = 20
GRID_OPTIONS = """
{
class: 'ag-theme-alpine',
defaultColDef: {
filter: true,
sortable: false,
resizable: true,
headerClass: 'font-bold',
editable: true
},
rowSelection: 'single',
}
"""
def on_input_key(self, msg):
"""On input key event.
Update the clicked cell with the new value from the input field.
Args:
msg (object): Event data object.
"""
if self.last_cell is not None:
self.grid.options['rowData'][self.last_cell['row']
][self.last_cell['col']] = msg.value
def on_cell_clicked(self, msg):
"""On cell clicked event.
Update the cell label value with the coordinates of the cell and set
the value of the cell in the input field.
Args:
msg (object): Event data object.
"""
self.cell_label.value = msg.colId + str(msg.rowIndex)
self.input_field.value = msg.data[msg.colId]
self.input_field.last_cell = {"row": msg.rowIndex, "col": msg.colId}
self.last_row = msg.row
def on_cell_value_changed(self, msg):
"""On input key event.
Update the input field value to match the cell value.
Args:
msg (object): Event data object.
"""
self.input_field.value = msg.data[msg.colId]
def grid_test():
"""Grid test app.
"""
headings = list(string.ascii_uppercase)
index = np.arange(START_INDEX, END_INDEX)
data_frame = pd.DataFrame(index=index, columns=headings)
data_frame = data_frame.fillna('')
# data = np.array([np.arange(10)]*3).T
# css_values = """
# .ag-theme-alpine .ag-ltr .ag-cell {
# border-right: 1px solid #aaa;
# }
# .ag-theme-balham .ag-ltr .ag-cell {
# border-right: 1px solid #aaa;
# }
# """
web_page = jp.WebPage()
root_div = jp.Div(classes='q-pa-md', a=web_page)
in_root_div = jp.Div(classes='q-gutter-md', a=root_div)
cell_label = jp.Input(
a=in_root_div, style='width: 32px; margin-left: 16px', disabled=True)
input_field = jp.Input(classes=jp.Styles.input_classes,
a=in_root_div, width='32px')
input_field.on("input", on_input_key)
input_field.last_cell = None
grid = jp.AgGrid(a=web_page, options=GRID_OPTIONS)
grid.load_pandas_frame(data_frame)
grid.options.pagination = True
grid.options.paginationAutoPageSize = True
grid.cell_label = cell_label
grid.input_field = input_field
grid.on('cellClicked', on_cell_clicked)
grid.on('cellValueChanged', on_cell_value_changed)
input_field.grid = grid
return web_page
def main():
"""Main app.
"""
jp.justpy(grid_test)
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
#
# Copyright 2017 AVSystem <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import socket
from framework.lwm2m_test import *
class DisableServerTest(test_suite.Lwm2mSingleServerTest):
def assertSocketsPolled(self, num):
self.assertEqual(num,
int(self.communicate('socket-count',
match_regex='SOCKET_COUNT==([0-9]+)\n').group(1)))
def runTest(self):
self.serv.set_timeout(timeout_s=1)
# Write Disable Timeout
req = Lwm2mWrite('/1/1/5', '6')
self.serv.send(req)
self.assertMsgEqual(Lwm2mChanged.matching(req)(), self.serv.recv())
# Execute Disable
req = Lwm2mExecute('/1/1/4')
self.serv.send(req)
self.assertMsgEqual(Lwm2mChanged.matching(req)(), self.serv.recv())
self.assertDemoDeregisters(timeout_s=5)
# no message for now
with self.assertRaises(socket.timeout):
print(self.serv.recv(timeout_s=5))
self.assertSocketsPolled(0)
# we should get another Register
self.assertDemoRegisters(timeout_s=3)
# no message for now
with self.assertRaises(socket.timeout):
print(self.serv.recv(timeout_s=2))
self.assertSocketsPolled(1)
|
import sys
import os
import builtins
print('Hi')
os.chdir(sys.argv[-1])
PYDK= os.environ.get('PYDK',"/data/cross/pydk")
ASSETS = "./assets"
sys.path[0]='./assets'
def rootfn(fn):
return os.path.join( ASSETS, fn )
log = print
def CLI():
print('CLI')
def STI():
print('STI')
ver = f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}'
for notwanted in (
f'/lib/python3{sys.version_info.minor}.zip',
f'local/lib/python3.{sys.version_info.minor}/site-packages',
f'{ver}/site-packages',
f'/python{ver}',
f'/python3.{sys.version_info.minor}',
'.egg'
):
todel = []
for p in sys.path:
if p.endswith(notwanted):
if not p in todel:
todel.append(p)
while len(todel):
sys.path.remove(todel.pop())
stdlib = f'python3.{sys.version_info.minor}.zip'
if not os.path.isfile( stdlib ):
print(" -- stdlib zip archive is missing --")
sys.path.append(f"{PYDK}/host/lib/python3.{sys.version_info.minor}")
sys.path.append(f"{PYDK}/wapy-lib/readline")
else:
sys.path.append( stdlib)
#sys.path.append('/')
sys.path.append('./assets/packages')
sys.path.append('/data/git/aioprompt')
sys.path.append('/data/git/wapy-lib/cpython-usocket')
sys.path.append('/data/git/aiovm')
#print(sys.path)
# to get the one from site-packages
# import panda3d
import pythons
import pythons.aio
print("\n"*4)
if 0:
import uasyncio
import oscpy
import oscpy.parser
SKIP = []
async def udp_req(addr):
sock = uasyncio.udp.socket()
sock.setsockopt(uasyncio.usocket.SOL_SOCKET, uasyncio.usocket.SO_REUSEADDR, 1)
print(sock, addr)
sock.bind(addr)
sock.sendto(b"eeeee", ("192.168.0.61",3333))
resp = None
while 1:
try:
resp = sock.recv(1024)
except BlockingIOError:
continue
try:
if resp.startswith(b'#bundle'):
msg = oscpy.parser.read_packet(resp)
else:
print("?:", resp)
msg = ()
except ValueError:
print("Err:",resp)
continue
for m in msg:
if m[0] == b'/tuio/2Dcur':
if m[1] in ( b'ss', b's' ):
h = hash(repr(m))
if not h in SKIP:
print(m )
if len(SKIP)<4:
SKIP.append(h)
else:
raise
continue
if m[1] == b'si' and m[2][0]==b'fseq':
continue
print("RESP:", m)
print()
#addr = uasyncio.usocket.getaddrinfo("192.168.0.254", 53)[0][-1]
addr = uasyncio.usocket.getaddrinfo("0.0.0.0", 3333)[0][-1]
aio.run( udp_req(addr) )
aio.loop.run_forever()
print("\n"*4)
raise SystemExit
if 0:
# byterun test
sys.path.append('/data/git/x-python')
print("\n"*8)
main_mod = sys.modules['__main__']
import os
import sys
import time
import asyncio
import byterun
from byterun.pyvm2 import VirtualMachine
print(byterun)
filename = "../hello.py"
source = open(filename,'rU').read()
# We have the source. `compile` still needs the last line to be clean,
# so make sure it is, then compile a code object from it.
if not source or source[-1] != '\n':
source += '\n'
code = compile(source, filename, "exec")
# Execute the source file.
vm = VirtualMachine()
async def host_io(vm):
while not aio.loop.is_closed():
if vm.spinlock:
print('\n ******* HOST IO/SYSCALLS ********\n')
vm.unlock()
await asyncio.sleep(1)
aio.loop.create_task( host_io(vm) )
aio.run( vm.run_code(code, f_globals=main_mod.__dict__) )
try:
aio.loop.run_forever()
except KeyboardInterrupt:
aio.loop.close()
print("\n"*8)
raise SystemExit
if 0:
# ================= async repl input ==================================
import aioprompt
import traceback
def custom_excepthook(etype, e, tb):
print(f"custom_excepthook test :", readline.get_line_buffer() )
if isinstance(e, NameError):
print("ne:",str(e))
return True
return False
aioprompt.custom_excepthook = custom_excepthook
# this will cause every input to raise syntax errors
import readline
def hook():
readline.insert_text(aioprompt.inputprompt)
readline.redisplay()
readline.set_pre_input_hook(hook)
async def inputhook(index, retry):
bytecode = None
try:
code = readline.get_history_item(index)[aioprompt.inputindent:]
if code:
if code=='q':
aio.loop.call_soon(aio.loop.stop)
await aio.sleep(0)
sys.exit(0)
return
bytecode = compile(code, "<stdin>", "exec")
except Exception as e:
print('CODE[rewrite]:',e,"\n",code)
for i,l in enumerate(code.split('\n')):
print(i,l)
try:
await retry(index, aioprompt.inputindent)
except SystemExit:
sys.exit(0)
return
if bytecode:
try:
exec(bytecode, __import__('__main__').__dict__, globals())
except SystemExit:
sys.exit(0)
aioprompt.inputprompt = "$$❯ "
aioprompt.inputindent = len(aioprompt.inputprompt)
aioprompt.inputhook = inputhook
# this one automatically handle aio loop, but linux only
import aiovm.repl as repl
#============================= main ==============================
# menu bar
import aiovm.tui as tui
#=====================================================
def execfile(fn):
exec(open(fn).read(), globals(), globals(),)
def test():
execfile('assets/test.py')
builtins.test = test
class AppStepper(aio.Runnable):
async def run(self, frametime, *argv, **kw):
aio.proc(self).rt(frametime)
del frametime
while not (await self):
python3.on_step(Applications, python3)
aio.service( AppStepper(), .016 )
def local_echo(fd, enabled):
import termios
(iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(fd)
if enabled:
lflag |= termios.ECHO
else:
lflag &= ~termios.ECHO
new_attr = [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
termios.tcsetattr(fd, termios.TCSANOW, new_attr)
import pythons.aio.cpy.repl
# reserve some lines for logs
# scroll region
tui.block.top = 16
local_echo( sys.__stdin__.fileno(), False)
def cleanup():
tui.block.out('\x1b[12h')
tui.block.out('\x1b[r')
local_echo( sys.__stdin__.fileno(), True)
try:
aio.loop.run_forever()
except KeyboardInterrupt:
aio.loop.call_soon( aio.loop.stop )
aio.loop.run_forever()
except RuntimeError:
cleanup()
raise
cleanup()
|
"""Utilities for evaluating the fairness of die"""
from typing import List, Union, Tuple
from scipy.linalg import solve
from scipy.optimize import minimize
from pydantic import BaseModel, Field
import numpy as np
def _pretty_multiplier(x: float) -> str:
"""Make a prettier version of a multiplier value
Args:
x: Value for a multiplicative factor (e.g., b = x * a)
Returns:
A humanized version of it
"""
if x > 100:
return f'{x:.0f}x'
elif x > 2:
return f'{x:.1f}x'
return f'{(x-1)*100:.1f}%'
# Dice models
class DieModel:
"""Model for the rolls of the dice"""
def __init__(self, n_faces: int):
"""
Args:
n_faces: Number of faces on the dice
"""
self.n_faces = n_faces
@property
def description(self) -> str:
raise NotImplementedError()
@property
def likelihoods(self) -> List[float]:
return self.compute_likelihood(np.arange(1, self.n_faces + 1)).tolist()
def get_params(self) -> List[float]:
"""Get the parameters for the model
Returns:
List of the parameters
"""
raise NotImplementedError()
def set_params(self, x: List[float]):
"""Set the parameters for this model of the dice"""
raise NotImplementedError()
def get_bounds(self) -> List[Tuple[float, float]]:
"""Get the allowed bounds for the parameters"""
raise NotImplementedError()
def compute_likelihood(self, rolls: Union[np.ndarray, int, List[int]]) -> np.ndarray:
"""Compute the likelihood of one or more dice rolls
Args:
rolls: The roll value(s)
Returns:
The probability of those rolls
"""
raise NotImplementedError()
def compute_neg_log_likelihood(self, rolls: List[int]) -> float:
"""Compute the negative log likelihood of a certain set of dice rolls
Args:
rolls: Observed rolls
Returns:
Log-likelihood of the outcome
"""
probs = self.compute_likelihood(rolls)
return -np.log(probs).sum()
class FairDie(DieModel):
"""Model for a fair dice"""
@property
def description(self) -> str:
return "A fair die."
def get_params(self) -> List[float]:
return []
def set_params(self, x: List[float]):
return
def get_bounds(self) -> List[Tuple[float, float]]:
return []
def compute_likelihood(self, rolls: Union[np.ndarray, int, List[int]]) -> np.ndarray:
x = np.zeros_like(rolls, dtype=np.float)
x += 1. / self.n_faces
return x
class SlantedDie(DieModel):
"""Model for a die that probabilities linearly increase or decrease in value"""
def __init__(self, n_faces: int, weight: float = 1):
"""
Args:
n_faces: Number of faces on the dice
weight: Large values are this factor more likely than small values
"""
super().__init__(n_faces)
assert weight > 0, "The weight value must be positive"
self.weight = weight
@property
def description(self) -> str:
if self.weight > 1:
return f"Large values are {_pretty_multiplier(self.weight)} more likely than small."
else:
return f"Small values are {_pretty_multiplier(1. / self.weight)} more likely than large."
def get_params(self) -> List[float]:
return [self.weight]
def set_params(self, x: List[float]):
self.weight, = x
def get_bounds(self) -> List[Tuple[float, float]]:
return [(0.001, 1000)]
def compute_likelihood(self, rolls: Union[np.ndarray, int, List[int]]) -> np.ndarray:
# Get slope the low- and high-values
start = 2. / (self.weight + 1)
slope = (self.weight * start - start) / (self.n_faces - 1)
# Compute the probability for each roll
return np.multiply(1. / self.n_faces, start + np.multiply(slope, np.subtract(rolls, 1)))
class ExtremeDie(DieModel):
"""Die that prefer to roll extreme values"""
def __init__(self, n_faces: int, extremity: float = 1):
"""
Args:
n_faces: Number of faces on the die
extremity: Ratio between extreme and middle value
"""
super().__init__(n_faces)
self.extremity = extremity
@property
def description(self) -> str:
if self.extremity > 1:
return f"Extreme values are {_pretty_multiplier(self.extremity)} more likely than average."
else:
return f"Average values are {_pretty_multiplier(1. / self.extremity)} more likely than extreme."
def set_params(self, x: List[float]):
self.extremity, = x
def get_params(self) -> List[float]:
return [self.extremity]
def get_bounds(self) -> List[Tuple[float, float]]:
return [(0.001, 1000)]
def compute_likelihood(self, rolls: Union[np.ndarray, int, List[int]]) -> np.ndarray:
# Compute the curvature
# Let m be the average value: m = (d - 1) / 2 + 1 = 0.5 * (d + 1)
# Assume p(x) ~ a * (x - m) ** 2 + c
# Let p(1) = e * p(m)
# a * (1 - m) ** 2 + c = e * c
# Eq 1: (1 - m) ** 2 * a - (1 - e) * c = 0
# Let: sum_i=1^d p(i) = 1
# Eq 2: a * sum_i=1^d (i - m) ** 2 + d * c = 1
m = 0.5 * (self.n_faces + 1)
a, c = solve([
[(1 - m) ** 2, 1 - self.extremity],
[np.power(np.arange(1, self.n_faces + 1) - m, 2).sum(), self.n_faces]
], [0, 1])
return a * np.power(np.subtract(rolls, m), 2) + c
def fit_model(rolls: List[int], die_model: DieModel) -> float:
"""Fit the parameters of a die probability model
Args:
rolls: List of the observed rolls
die_model: Dice model. Will be
Returns:
Negative log-likelihood of the dice model
"""
# Special case: FairDie
if isinstance(die_model, FairDie):
return die_model.compute_neg_log_likelihood(rolls)
# Set up the optimization problem
def nll(x):
die_model.set_params(x)
return die_model.compute_neg_log_likelihood(rolls)
fx = minimize(nll, die_model.get_params(), method='powell', bounds=die_model.get_bounds())
# Set the parameters
die_model.set_params(fx.x)
return fx.fun
# Summary functions
class DieModelSummary(BaseModel):
"""Results of a dice model fitting"""
model_name: str = Field(..., description="Name of the model")
nll: float = Field(..., description="Negative log-likelihood of the model fitting")
description: str = Field(..., description="Short description for the model")
likelihoods: List[float] = Field(..., description="Likelihoods for each value of die")
@classmethod
def from_fitting(cls, rolls: List[int], model: DieModel) -> 'DieModelSummary':
"""Create a die summary
Args:
model: Model to fit and summarize
rolls: Observed rolls
"""
# Fit the model
nll = fit_model(rolls, model)
# Create the summary
return cls(
model_name=model.__class__.__name__,
nll=nll,
description=model.description,
likelihoods=model.likelihoods
)
class DiceRollStatistics(BaseModel):
"""Statistics about dice rolls"""
rolls: List[int] = Field(..., description="Values of all of the rolls")
num_faces: int = Field(..., description="Number of faces on the die")
models: List[DieModelSummary] = Field(..., description="Description of the models. Sorted by fitness")
@classmethod
def from_rolls(cls, num_faces: int, rolls: List[int]) -> 'DiceRollStatistics':
"""Generate a summary of a series of rolls
Args:
num_faces: Number of faces on the die
rolls: Value of the rolls
"""
# Run the models
fits = [DieModelSummary.from_fitting(rolls, model)
for model in [FairDie(num_faces), SlantedDie(num_faces), ExtremeDie(num_faces)]]
fits = sorted(fits, key=lambda x: x.nll) # Sort by fitness
return DiceRollStatistics(
rolls=rolls,
num_faces=num_faces,
models=fits
)
|
# BOJ 1028
# diamondmine.py
from collections import deque
import sys
input = sys.stdin.readline
dy = (-1, 1)
r, c = map(int, input().split())
mine = []
for _ in range(r):
mine.append(list(input().strip()))
max_level = round((min(r,c)+0.1) / 2)
tmp = 0
def check(lvl, x, y, r, c):
remain_x = r - x
remain_y = c - y
if remain_x < lvl or y+1 < lvl or remain_y < lvl:
return False
else:
return True
def get_size(level):
if level == 1:
return 1
else:
return 4 * (level-1)
def bfs(x, y, r, c, lvl):
global tmp, max_level
q = deque()
q.append((x, y))
tmp_level = 0
flag = False
while q:
x, y = q.popleft()
for i in range(2):
if not flag:
nx = x + 1
ny = y + dy[i]
else:
nx = x + 1
ny = y - dy[i]
if nx < 0 or nx >= r or ny < 0 or ny >= c:
return False
if mine[nx][ny] == '0':
return False
if mine[nx][ny] == '1':
tmp += 1
q.append((nx, ny))
tmp_level += 1
if tmp_level == lvl - 1:
flag = True
return True
res = []
res.append(0)
for i in range(r):
for j in range(c):
if mine[i][j] == '1':
for k in range(max_level, 0, -1):
if not check(k, i, j, r, c):
continue
tmp = 0
bfs(i, j, r, c, k)
if tmp+1 == get_size(k):
res.append(k)
print(max(res)) |
"""NDG XACML one and only functions module
NERC DataGrid
"""
__author__ = "P J Kershaw"
__date__ = "01/04/10"
__copyright__ = ""
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "[email protected]"
__revision__ = '$Id$'
from ndg.xacml.core.functions import (AbstractFunction,
FunctionClassFactoryInterface)
from ndg.xacml.core.context.exceptions import XacmlContextTypeError
class Round(AbstractFunction):
"""Base class for XACML <type>-round functions
@cvar FUNCTION_NS: namespace for this function
@type FUNCTION_NS: string
"""
FUNCTION_NS = AbstractFunction.V1_0_FUNCTION_NS + 'round'
def evaluate(self, num):
"""Execute mathematical round up of the input number
@param num: number to round up
@type num: int / long / float
@rtype: float
@raise TypeError: incorrect type for input
"""
try:
return round(num)
except TypeError, e:
raise XacmlContextTypeError('Round function: %s' % e)
class FunctionClassFactory(FunctionClassFactoryInterface):
"""Class Factory for round XACML function class
"""
def __call__(self, identifier):
'''Create class for the Round XACML function identifier
@param identifier: XACML round function identifier
@type identifier: basestring
@return: round function class or None if identifier doesn't match
@rtype: ndg.xacml.core.functions.v1.round.Round / NoneType
'''
if identifier == Round.FUNCTION_NS:
return Round
else:
return None
|
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD-TOKEN')
intents = discord.Intents.default()
client = commands.Bot(command_prefix = "m!", intents = intents)
print("Commands:\n")
for filename in os.listdir("./commands"):
client.load_extensions(f'commands.{filename[:-3]}')
print("{filename[:3]} has been loaded.")
print("Events:\n")
for filename in os.listdir("./events"):
client.load_extensions(f'events.{filename[:3]}')
print("{filename[:3]} has been loaded.")
client.run()
|
from pedal.report.imperative import MAIN_REPORT
def make_resolver(func, report=None):
'''
Decorates the given function as a Resolver. This means that when the
function is executed, the `"pedal.resolver.resolve"` event will be
triggered.
Args:
func (callable): The function to decorate.
report (Report): The Report to trigger the event on. If None, then use
the `MAIN_REPORT`.
'''
if report is None:
report = MAIN_REPORT
def resolver_wrapper():
report.execute_hooks("pedal.resolvers.resolve")
return func()
return resolver_wrapper
|
import logging
import sys
from logging import Logger, StreamHandler, FileHandler
from logging.handlers import MemoryHandler
from osbot_utils.decorators.lists.group_by import group_by
from osbot_utils.decorators.lists.index_by import index_by
from osbot_utils.utils.Misc import random_string, obj_dict
from osbot_utils.utils.Files import temp_file
DEFAULT_LOG_LEVEL = logging.DEBUG
DEFAULT_LOG_FORMAT = '%(asctime)s\t|\t%(name)s\t|\t%(levelname)s\t|\t%(message)s'
MEMORY_LOGGER_CAPACITY = 1024*10
MEMORY_LOGGER_FLUSH_LEVEL = logging.ERROR
class Python_Logger_Config:
def __init__(self):
self.elastic_host = None
self.elastic_password = None
self.elastic_port = None
self.elastic_username = None
#self.log_to_aws_s3 = False # todo
#self.log_to_aws_cloud_trail = False # todo
#self.log_to_aws_firehose = False # todo
self.log_to_console = False # todo
self.log_to_file = False # todo
#self.log_to_elastic = False # todo
self.log_to_memory = False
self.path_logs = None
self.log_format = DEFAULT_LOG_FORMAT
self.log_level = DEFAULT_LOG_LEVEL
class Python_Logger:
config : Python_Logger_Config
logger : Logger
def __init__(self, logger_name= None, logger_config : Python_Logger_Config = None):
self.logger_name = logger_name or random_string(prefix="Python_Logger_")
self.set_config(logger_config)
def manager_get_loggers(self):
return Logger.manager.loggerDict
def manager_remove_logger(self):
logger_dict = Logger.manager.loggerDict
if self.logger_name in logger_dict: # need to do it manually here since Logger.manager doesn't seem to have a way to remove loggers
del logger_dict[self.logger_name]
return True
return False
def setup(self):
self.logger = logging.getLogger(self.logger_name)
self.setup_log_methods(self)
self.set_log_level()
self.add_handler_memory()
return self
def setup_log_methods(self, target):
# adds these helper methods like this so that the filename and function values are accurate
setattr(target, "debug" , self.logger.debug )
setattr(target, "info" , self.logger.info )
setattr(target, "warning" , self.logger.warning )
setattr(target, "error" , self.logger.error )
setattr(target, "exception" , self.logger.exception )
setattr(target, "critical" , self.logger.critical )
# self.info = self.logger.info
# self.warning = self.logger.warning
# self.error = self.logger.error
# self.exception = self.logger.exception
# self.critical = self.logger.critical
# Setters
def set_config(self, config):
if type(config) is Python_Logger_Config:
self.config = config
else:
self.config = Python_Logger_Config()
return self.config
def set_log_format(self, format):
if format:
self.config.log_format = format
def set_log_level(self, level=None):
level = level or self.config.log_level
if self.logger:
self.logger.setLevel(level)
return True
return False
# Getters
def log_handlers(self):
if self.logger:
return self.logger.handlers
return []
def log_handler(self, handler_type):
for handler in self.log_handlers():
if type(handler) is handler_type:
return handler
return None
def log_handler_console(self):
return self.log_handler(StreamHandler)
def log_handler_file(self):
return self.log_handler(logging.FileHandler)
def log_handler_memory(self):
return self.log_handler(MemoryHandler)
def log_formatter(self):
return logging.Formatter(self.config.log_format)
def log_level(self):
return self.config.log_level
# Actions
def add_console_logger(self):
self.config.log_to_console = True
return self.add_handler_console()
def add_memory_logger(self):
self.config.log_to_memory = True
return self.add_handler_memory()
def add_file_logger(self,path_log_file=None):
self.config.log_to_file = True
return self.add_handler_file(path_log_file=path_log_file)
# Handlers
def add_handler_console(self):
if self.logger and self.config.log_to_console:
handler = StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
handler.setFormatter(self.log_formatter())
self.logger.addHandler(handler)
return True
return False
def add_handler_file(self, path_log_file=None):
if self.logger and self.config.log_to_file:
if path_log_file is None:
path_log_file = temp_file(extension='.log')
handler = FileHandler(path_log_file)
handler.setLevel(self.log_level())
handler.setFormatter(self.log_formatter())
self.logger.addHandler(handler)
return True
return False
def add_handler_memory(self):
if self.logger and self.config.log_to_memory:
capacity = MEMORY_LOGGER_CAPACITY
flush_level = MEMORY_LOGGER_FLUSH_LEVEL
target = None # we want the messages to only be kept in memory
memory_handler = MemoryHandler(capacity=capacity, flushLevel=flush_level, target=target,flushOnClose=True)
memory_handler.setLevel(self.log_level())
self.logger.addHandler(memory_handler)
return True
return False
# Utils
def memory_handler_exceptions(self):
return self.memory_handler_logs(index_by='levelname').get('EXCEPTIONS', {})
@index_by
@group_by
def memory_handler_logs(self):
logs = []
memory_handler = self.log_handler_memory()
if memory_handler:
for log_record in memory_handler.buffer:
logs.append(obj_dict(log_record))
return logs
def memory_handler_messages(self):
return [log_entry.get('message') for log_entry in self.memory_handler_logs()]
# Logging methods
# def debug (self, msg='', *args, **kwargs): return self._log('debug' , msg, *args, **kwargs)
# #def info (self, msg='', *args, **kwargs): return self.__log__('info' , msg, *args, **kwargs)
# def warning (self, msg='', *args, **kwargs): return self._log('warning' , msg, *args, **kwargs)
# def error (self, msg='', *args, **kwargs): return self._log('error' , msg, *args, **kwargs)
# def exception(self, msg='', *args, **kwargs): return self._log('exception' , msg, *args, **kwargs)
# def critical (self, msg='', *args, **kwargs): return self._log('critical' , msg, *args, **kwargs)
#
# def __log__(self, level, msg, *args, **kwargs):
# if self.logger:
# log_method = getattr(self.logger, level)
# log_method(msg, *args, **kwargs)
# return True
# return False
|
from functions import *
names = ['Name_sim1_scen_MQ_del2_M_28-30.dfsu', 'Name_sim3_scen_Q10_del2_M_28-30.dfsu',
'Name_sim1_scen_MQ_del2_M_28-30.m21fm', 'Name_sim3_scen_Q10_del2_M_28-30.m21fm',
'Klaralven_sim1_scen_MQ_del2_M_28-30.m21fm - Result Files',
'Klaralven_sim2_scen_MQ_klimat_del2_M_28-30.m21fm - Result Files',
'Klaralven_sim3_scen_Q10_del2_M_28-30.m21fm - Result Files',
'Klaralven_sim4_scen_Q25_del2_M_28-30.m21fm - Result Files',
'Klaralven_sim5_scen_Q50_del2_M_31-33.m21fm - Result Files',
'Klaralven_sim6_scen_Q100-klimat_del2_M_31-33.m21fm - Result Files',
'Klaralven_sim7_scen_Q200-klimat_del2_M_31-33.m21fm - Result Files',
'Klaralven_sim8_scen_Q200_del2_M_31-33.m21fm - Result Files',
'Klaralven_sim9_scen_BHF_del2_M_31-33.m21fm - Result Files']
for name in names:
print(sim_name_decoder(name, 0))
print(sim_name_decoder(name, 1))
print(sim_name_decoder(name, 2))
print(sim_name_decoder(name, 3))
print(sim_name_decoder(name, 4))
print(sim_name_decoder(name, 5))
print(sim_name_decoder(name, 6))
print(sim_name_decoder(name, 7))
|
# %%
import os
import pathlib
import chardet
import pandas as pd
import pathlib
from utils import get_projectpaths
(projectroot, rawdatapath, cleandatapath, processeddatapath) = get_projectpaths()
# %%
listoffiles = []
for path, subdirs, files in os.walk(rawdatapath):
[listoffiles.append(str(pathlib.PurePath(path, name).relative_to(rawdatapath))) for name in files]
# %% make sure we're only looking at the txt files and not zips etc
excludedfiles = [filename for filename in listoffiles if filename[-3:] != "txt"]
for i in excludedfiles:
print("We have excluded the following file from analysis (wrong extension)", i)
listoffiles = [filename for filename in listoffiles if filename[-3:] == "txt"]
# %% get encodings
encodingtypes = []
confidence = []
for file in listoffiles:
with open(str(rawdatapath/ file), 'rb') as detect_file_encoding:
detection = chardet.detect(detect_file_encoding.read())
encodingtypes.append(detection['encoding'])
confidence.append(detection['confidence'])
# %% get data formats
dataformats = pd.DataFrame(list(zip(listoffiles, encodingtypes,confidence)),
columns =['filename', 'encoding', 'confidence'])
# %% export and count
dataformats.to_csv(processeddatapath/"inferred_dataset_encodings.csv", index=False)
print(dataformats['encoding'].value_counts()) |
import logging
from typing import Dict, List, Iterable
from allennlp.data.dataset_readers.dataset_utils import to_bioul
from allennlp.common.file_utils import cached_path
from allennlp.common.checks import ConfigurationError
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import Field, TextField, SequenceLabelField, MetadataField
from allennlp.data.instance import Instance
from allennlp.data.token_indexers import SingleIdTokenIndexer, TokenIndexer
from allennlp.data.tokenizers import Token
from allennlp_models.common.ontonotes import Ontonotes, OntonotesSentence
logger = logging.getLogger(__name__)
def _normalize_word(word: str):
if word in ("/.", "/?"):
return word[1:]
else:
return word
@DatasetReader.register("ontonotes_ner")
class OntonotesNamedEntityRecognition(DatasetReader):
"""
This DatasetReader is designed to read in the English OntoNotes v5.0 data
for fine-grained named entity recognition. It returns a dataset of instances with the
following fields:
tokens : `TextField`
The tokens in the sentence.
tags : `SequenceLabelField`
A sequence of BIO tags for the NER classes.
Note that the "/pt/" directory of the Onotonotes dataset representing annotations
on the new and old testaments of the Bible are excluded, because they do not contain
NER annotations.
# Parameters
token_indexers : `Dict[str, TokenIndexer]`, optional
We similarly use this for both the premise and the hypothesis. See :class:`TokenIndexer`.
Default is `{"tokens": SingleIdTokenIndexer()}`.
domain_identifier : `str`, (default = `None`)
A string denoting a sub-domain of the Ontonotes 5.0 dataset to use. If present, only
conll files under paths containing this domain identifier will be processed.
coding_scheme : `str`, (default = `None`).
The coding scheme to use for the NER labels. Valid options are "BIO" or "BIOUL".
# Returns
A `Dataset` of `Instances` for Fine-Grained NER.
"""
def __init__(
self,
token_indexers: Dict[str, TokenIndexer] = None,
domain_identifier: str = None,
coding_scheme: str = "BIO",
**kwargs,
) -> None:
super().__init__(**kwargs)
self._token_indexers = token_indexers or {"tokens": SingleIdTokenIndexer()}
self._domain_identifier = domain_identifier
if domain_identifier == "pt":
raise ConfigurationError(
"The Ontonotes 5.0 dataset does not contain annotations for"
" the old and new testament sections."
)
self._coding_scheme = coding_scheme
def _read(self, file_path: str):
# if `file_path` is a URL, redirect to the cache
file_path = cached_path(file_path)
ontonotes_reader = Ontonotes()
logger.info("Reading Fine-Grained NER instances from dataset files at: %s", file_path)
if self._domain_identifier is not None:
logger.info(
"Filtering to only include file paths containing the %s domain",
self._domain_identifier,
)
for sentence in self._ontonotes_subset(
ontonotes_reader, file_path, self._domain_identifier
):
tokens = [Token(_normalize_word(t)) for t in sentence.words]
yield self.text_to_instance(tokens, sentence.named_entities)
@staticmethod
def _ontonotes_subset(
ontonotes_reader: Ontonotes, file_path: str, domain_identifier: str
) -> Iterable[OntonotesSentence]:
"""
Iterates over the Ontonotes 5.0 dataset using an optional domain identifier.
If the domain identifier is present, only examples which contain the domain
identifier in the file path are yielded.
"""
for conll_file in ontonotes_reader.dataset_path_iterator(file_path):
if (
domain_identifier is None or f"/{domain_identifier}/" in conll_file
) and "/pt/" not in conll_file:
yield from ontonotes_reader.sentence_iterator(conll_file)
def text_to_instance(
self, # type: ignore
tokens: List[Token],
ner_tags: List[str] = None,
) -> Instance:
"""
We take `pre-tokenized` input here, because we don't have a tokenizer in this class.
"""
sequence = TextField(tokens, self._token_indexers)
instance_fields: Dict[str, Field] = {"tokens": sequence}
instance_fields["metadata"] = MetadataField({"words": [x.text for x in tokens]})
# Add "tag label" to instance
if ner_tags is not None:
if self._coding_scheme == "BIOUL":
ner_tags = to_bioul(ner_tags, encoding="BIO")
instance_fields["tags"] = SequenceLabelField(ner_tags, sequence)
return Instance(instance_fields)
|
import numpy as np
import openmdao.api as om
class ComputeSinCos(om.ExplicitComponent):
# computes sin and cos of the input angle
def initialize(self):
self.options.declare('num_nodes', default=1, desc="Number of nodes to compute")
def setup(self):
nn = self.options['num_nodes']
arange = np.arange(0, nn)
self.add_input('angle', shape=(nn,),units='deg')
self.add_output('cos', shape=(nn,),units=None)
self.add_output('sin', shape=(nn,),units=None)
self.declare_partials(['*'], 'angle', rows=arange, cols=arange)
def compute(self, inputs, outputs):
outputs['cos'] = np.cos(inputs['angle'])
outputs['sin'] = np.sin(inputs['angle'])
def compute_partials(self, inputs, partials):
partials['cos', 'angle'] = -np.sin(inputs['angle'])
partials['sin', 'angle'] = np.cos(inputs['angle']) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def add_element():
name = input('Конечный пункт: ')
num = input('Номер поезда: ')
tm = input('Время отправления: ')
trains = {}
trains['name'] = name
trains['num'] = int(num)
trains['tm'] = tm
return trains
def find_train(trains):
num = int(input('Введите номер искомого поезда: '))
for dcts in trains:
if dcts['num'] == num:
print(f'Конечный пункт: {dcts["name"]} \n'
f'Номер поезда: {dcts["num"]} \n'
f'Время отправления: {dcts["tm"]}')
return
print('Поезда с таким номером нет')
if __name__ == '__main__':
flag = True
trains = []
while flag:
print('1. Добавить новый поезд')
print('2. Вывести информацию о поезде')
print('3.Выход из программы')
com = int(input('введите номер команды: '))
if com == 1:
trains.append(add_element())
elif com == 2:
find_train(trains)
elif com == 3:
flag = False
|
import math
n = int(input())
x = int(math.sqrt(n)) + 1
val = 1
while val <= x:
if val == x:
val*=2
print(val) |
import os
import uuid
from datetime import datetime, timedelta
import mock
import pytz
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from utils.widget import quill
from wiki.forms import wikipageform
from wiki.models import wikipage, wikisection
from wiki.models.permissionpage import PermissionPage
from wiki.models.permissionsection import PermissionSection
from wiki.models.wikipage import Keywords, WikiPage
from wiki.models.wikisection import WikiSection
def render_mock(request, template, data, content_type='test'):
return {'request':request, 'template':template, 'data': data, 'content_type':content_type}
def redirect_mock(link):
return link
def reverse_mock(link, kwargs=None):
if kwargs is None:
return link
return link
class req:
def __init__(self, method='GET', post={}, user=None):
self.method = method
self.user = user
self.POST = post
class WikiPageFormTestCase(TestCase):
def setUp(self):
self.firstUser = User(is_superuser=True, username='test1', password='test1', email='[email protected]', first_name='testname1', last_name='testlast2')
self.secondUser = User(is_superuser=False, username='test2', password='test2', email='[email protected]', first_name='testname2', last_name='testlast2')
self.thirdUser = User(is_superuser=False, username='test3', password='test3', email='[email protected]', first_name='testname3', last_name='testlast3')
self.fourthUser = User(is_superuser=False, username='test4', password='test4', email='[email protected]', first_name='testname4', last_name='testlast4')
self.firstUser.save()
self.secondUser.save()
self.thirdUser.save()
self.fourthUser.save()
self.wikiuuid = [uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4()]
self.wikistext = ['{"ops":[{"insert":"123123\\n"}]}', 'text', None]
self.wikisuuid = [uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4(), uuid.uuid4()]
self.wikipath = 'wiki'
self.wikipagelink = 'wiki_page'
self.wikimainpagelink = 'wiki_homepage'
self.softwarename = 'name'
self.formtemplate = 'forms/unimodelform.html'
self.contenttype = 'text/html'
self.createdtime = datetime.now(pytz.utc)
self.wikiPages = []
self.permissions = []
for i in range(3):
self.wikiPages.append(WikiPage(unid=self.wikiuuid[i], createdon=self.createdtime, updatedon=self.createdtime, createdby=self.firstUser, updatedby=self.secondUser, title='testpage'+str(i+1)))
self.wikiPages[i].save()
self.wikiPages[i].createdon=self.createdtime + timedelta(hours=i)
self.wikiPages[i].updatedon=self.createdtime + timedelta(hours=i)
self.wikiPages[i].save()
self.pagepermissions = []
pagep = PermissionPage(createdby=self.firstUser, accesslevel=20, grantedto=self.thirdUser, wikipage=self.wikiPages[2])
pagep.save()
self.pagepermissions.append(pagep)
pagep = PermissionPage(createdby=self.firstUser, accesslevel=30, grantedto=self.fourthUser, wikipage=self.wikiPages[2])
pagep.save()
self.pagepermissions.append(pagep)
self.wikiSections = []
for i in range(3):
self.wikiSections.append(WikiSection(unid=self.wikisuuid[i], createdon=self.createdtime, updatedon=self.createdtime, createdby=self.firstUser, updatedby=self.secondUser, title='testsec'+str(i+1), pageorder=i+1, text=self.wikistext[i], wikipage=self.wikiPages[0]))
self.wikiSections[i].save()
self.wikiSections[i].createdon=self.createdtime + timedelta(hours=i)
self.wikiSections[i].updatedon=self.createdtime + timedelta(hours=i)
perm = PermissionSection(createdby=self.firstUser, accesslevel=20, grantedto=self.secondUser, section=self.wikiSections[i])
perm.save()
self.permissions.append(perm)
perm = PermissionSection(createdby=self.firstUser, accesslevel=10, grantedto=self.thirdUser, section=self.wikiSections[i])
perm.save()
self.permissions.append(perm)
if i==1:
self.wikiSections[1].createdby = None
self.wikiSections[1].updatedby = None
self.wikiSections[i].save()
settings.SOFTWARE_NAME_SHORT = self.softwarename
wikipageform.settings.SOFTWARE_NAME_SHORT = self.softwarename
wikipageform.settings.WIKI_FILES = self.wikipath
os.path.exists = mock.Mock(return_value=True, spec='os.path.exists')
os.makedirs = mock.Mock(return_value=None, spec='os.makedirs')
wikipageform.render = mock.Mock(side_effect=render_mock)
wikipageform.redirect = mock.Mock(side_effect=redirect_mock)
wikipageform.reverse = mock.Mock(side_effect=reverse_mock)
wikipage.reverse = mock.Mock(side_effect=reverse_mock)
def test_wiki_page_form_get_request_super_user(self):
post = {'action':'add'}
method = 'GET'
request = req(method=method, user=self.firstUser)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result['request'], request)
self.assertEqual(result['template'], self.formtemplate)
data = result['data']
self.assertEqual(data['action'], 'add')
self.assertEqual(data['PAGE_TITLE'], 'Post an article: ' + self.softwarename)
self.assertEqual(data['minititle'], 'Post Article')
self.assertEqual(data['submbutton'], 'Post article')
self.assertEqual(data['backurl'], self.wikimainpagelink)
self.assertEqual(data['needquillinput'], True)
self.assertIsInstance(data['form'], wikipageform.WikiPageForm)
self.assertEqual(result['content_type'], self.contenttype)
def test_wiki_page_form_get_request_no_access(self):
method = 'GET'
request = req(method=method, user=self.thirdUser)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_get_request_no_permissions(self):
method = 'GET'
request = req(method=method, user=self.fourthUser)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_post_request_no_action(self):
post = {}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result['request'], request)
self.assertEqual(result['template'], self.formtemplate)
data = result['data']
self.assertEqual(data['action'], 'add')
self.assertEqual(data['PAGE_TITLE'], 'Post an article: ' + self.softwarename)
self.assertEqual(data['minititle'], 'Post Article')
self.assertEqual(data['submbutton'], 'Post article')
self.assertEqual(data['backurl'], self.wikimainpagelink)
self.assertEqual(data['needquillinput'], True)
self.assertIsInstance(data['form'], wikipageform.WikiPageForm)
self.assertEqual(result['content_type'], self.contenttype)
def test_wiki_page_form_post_request_no_action_no_permissions(self):
post = {}
method = 'POST'
request = req(method=method, user=self.thirdUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_add_request_success(self):
post = {'action':'add', 'title':self.wikiPages[0].title}
method = 'POST'
WikiPage.objects.all().delete()
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikipagelink)
self.assertEqual(len(WikiPage.objects.all()), 1)
wiki = WikiPage.objects.all()[0]
self.assertEqual(wiki.title, self.wikiPages[0].title)
self.assertEqual(wiki.createdby, self.firstUser)
self.assertEqual(wiki.updatedby, self.firstUser)
def test_wiki_page_form_add_request_failed_no_access(self):
post = {'action':'add', 'title':self.wikiPages[0].title}
method = 'POST'
request = req(method=method, user=self.thirdUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_add_request_failed_no_permissions(self):
post = {'action':'add', 'title':self.wikiPages[0].title}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_add_request_failed_no_title(self):
post = {'action':'add', 'title':None}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result['request'], request)
self.assertEqual(result['template'], self.formtemplate)
data = result['data']
self.assertEqual(data['action'], 'add')
self.assertEqual(data['PAGE_TITLE'], 'Post an article: ' + self.softwarename)
self.assertEqual(data['minititle'], 'Post Article')
self.assertEqual(data['submbutton'], 'Post article')
self.assertEqual(data['backurl'], self.wikimainpagelink)
self.assertEqual(data['needquillinput'], True)
self.assertIsInstance(data['form'], wikipageform.WikiPageForm)
self.assertTrue(('title' in data['form'].data) or (data['form'].data == {}))
self.assertEqual(result['content_type'], self.contenttype)
def test_wiki_page_form_change_request_success_super_user(self):
post = {'action':'change', 'targetid': self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result['request'], request)
self.assertEqual(result['template'], self.formtemplate)
data = result['data']
self.assertEqual(data['action'], 'changed')
self.assertEqual(data['targetid'], self.wikiPages[0].unid)
self.assertEqual(data['PAGE_TITLE'], 'Post an article: ' + self.softwarename)
self.assertEqual(data['minititle'], 'Change Posted Article')
self.assertEqual(data['submbutton'], 'Change posted article')
self.assertEqual(data['deletebutton'], 'Delete article')
self.assertEqual(data['backurl'], self.wikipagelink)
self.assertEqual(data['needquillinput'], True)
self.assertIsInstance(data['form'], wikipageform.WikiPageForm)
self.assertTrue('title' in data['form'].initial)
self.assertEqual(data['form'].initial['title'], self.wikiPages[0].title)
self.assertEqual(result['content_type'], self.contenttype)
def test_wiki_page_form_change_request_success_permission(self):
post = {'action':'change', 'targetid': self.wikiPages[2].unid}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result['request'], request)
self.assertEqual(result['template'], self.formtemplate)
data = result['data']
self.assertEqual(data['action'], 'changed')
self.assertEqual(data['targetid'], self.wikiPages[2].unid)
self.assertEqual(data['PAGE_TITLE'], 'Post an article: ' + self.softwarename)
self.assertEqual(data['minititle'], 'Change Posted Article')
self.assertEqual(data['submbutton'], 'Change posted article')
self.assertEqual(data['deletebutton'], 'Delete article')
self.assertEqual(data['backurl'], self.wikipagelink)
self.assertEqual(data['needquillinput'], True)
self.assertIsInstance(data['form'], wikipageform.WikiPageForm)
self.assertTrue('title' in data['form'].initial)
self.assertEqual(data['form'].initial['title'], self.wikiPages[2].title)
self.assertEqual(result['content_type'], self.contenttype)
def test_wiki_page_form_change_request_fail_no_access(self):
post = {'action':'change', 'targetid': self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.thirdUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_change_request_fail_no_permissions(self):
post = {'action':'change', 'targetid': self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_change_request_fail_no_page(self):
post = {'action':'change', 'targetid':uuid.uuid4()}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_change_request_fail_no_target_id(self):
post = {'action':'change'}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_changed_request_success_super_user(self):
post = {'action':'changed', 'targetid': self.wikiPages[0].unid, 'title':'new title'}
method = 'POST'
self.wikiPages[0].updatedby = self.secondUser
self.wikiPages[0].save()
wiki = WikiPage.objects.get(unid=self.wikiPages[0].unid)
self.assertEqual(wiki.updatedby, self.secondUser)
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikipagelink)
wiki = WikiPage.objects.get(unid=self.wikiPages[0].unid)
self.assertEqual(wiki.title, 'new title')
self.assertEqual(wiki.createdby, self.firstUser)
self.assertEqual(wiki.updatedby, self.firstUser)
self.assertNotEqual(wiki.updatedon, wiki.createdon)
def test_wiki_page_form_changed_request_success_permissions(self):
post = {'action':'changed', 'targetid': self.wikiPages[2].unid, 'title':'new title'}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikipagelink)
wiki = WikiPage.objects.get(unid=self.wikiPages[2].unid)
self.assertEqual(wiki.title, 'new title')
self.assertEqual(wiki.createdby, self.firstUser)
self.assertEqual(wiki.updatedby, self.fourthUser)
self.assertNotEqual(wiki.updatedon, wiki.createdon)
def test_wiki_page_form_changed_request_failed_no_access(self):
post = {'action':'changed', 'targetid': self.wikiPages[0].unid, 'title':'new title'}
method = 'POST'
request = req(method=method, user=self.thirdUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_changed_request_failed_no_permissions(self):
post = {'action':'changed', 'targetid': self.wikiPages[0].unid, 'title':'new title'}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_changed_request_failed_no_title(self):
post = {'action':'changed', 'targetid': self.wikiPages[0].unid, 'title': None}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result['request'], request)
self.assertEqual(result['template'], self.formtemplate)
data = result['data']
self.assertEqual(data['action'], 'changed')
self.assertEqual(data['targetid'], self.wikiPages[0].unid)
self.assertEqual(data['PAGE_TITLE'], 'Post an article: ' + self.softwarename)
self.assertEqual(data['minititle'], 'Change Posted Article')
self.assertEqual(data['submbutton'], 'Change posted article')
self.assertEqual(data['deletebutton'], 'Delete article')
self.assertEqual(data['backurl'], self.wikipagelink)
self.assertEqual(data['needquillinput'], True)
self.assertIsInstance(data['form'], wikipageform.WikiPageForm)
self.assertTrue('title' in data['form'].initial)
self.assertEqual(data['form'].initial['title'], self.wikiPages[0].title)
self.assertEqual(result['content_type'], self.contenttype)
def test_wiki_page_form_changed_request_fail_no_page(self):
post = {'action':'changed', 'targetid':uuid.uuid4()}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_changed_request_fail_no_target_id(self):
post = {'action':'changed'}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_delete_request_success_super_user(self):
post = {'action':'delete', 'targetid':self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
try:
wiki = WikiPage.objects.get(unid=self.wikiPages[0].unid)
except:
wiki=None
self.assertIsNone(wiki)
def test_wiki_page_form_delete_request_success_permission(self):
post = {'action':'delete', 'targetid':self.wikiPages[2].unid}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
try:
wiki = WikiPage.objects.get(unid=self.wikiPages[2].unid)
except:
wiki=None
self.assertIsNone(wiki)
def test_wiki_page_form_delete_request_fail_wrong_action(self):
post = {'action':'qwertyu', 'targetid':self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_delete_request_fail_no_access(self):
post = {'action':'delete', 'targetid':self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.thirdUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_delete_request_fail_no_permissions(self):
post = {'action':'delete', 'targetid':self.wikiPages[0].unid}
method = 'POST'
request = req(method=method, user=self.fourthUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_delete_request_fail_no_page(self):
post = {'action':'delete', 'targetid':uuid.uuid4()}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_form_delete_request_fail_no_target_id(self):
post = {'action':'delete'}
method = 'POST'
request = req(method=method, user=self.firstUser, post=post)
result = wikipageform.WikiArticleFormParse(request)
self.assertEqual(result, self.wikimainpagelink)
def test_wiki_page_viewable_super_user(self):
self.assertTrue(self.wikiPages[0].viewable(self.firstUser))
def test_wiki_page_viewable_permission_editable(self):
self.assertTrue(self.wikiPages[0].viewable(self.secondUser))
def test_wiki_page_viewable_permission_viewable(self):
self.assertTrue(self.wikiPages[0].viewable(self.thirdUser))
def test_wiki_page_not_viewable_permission(self):
self.assertFalse(self.wikiPages[0].viewable(self.fourthUser))
def test_wiki_page_viewable_common_knowledge(self):
self.wikiPages[0].commonknowledge = True
self.wikiPages[0].save()
self.assertTrue(self.wikiPages[0].viewable(self.fourthUser))
|
import os
import datetime
from utils import get_python_version
python_version = get_python_version()
attacks = ['bim']#, 'jsma', 'cw', 'bim']
labels = [0,1,2,3,4,5,6,7,8,9]
qq = [2,3]
rel_num = [6,8,10, 12]
model_names = ['neural_networks/cifar_original']
#model_names = ['neural_networks/LeNet1', 'neural_networks/LeNet4', 'neural_networks/LeNet5']# 'neural_networks/cifar40_128']
approaches = ['lsa', 'dsa']
for seed in range(1,6):
for model in model_names:
# for app in approaches:
#for l in labels:
#for rn in rel_num:
command = 'python validation_cifar.py -DS cifar10 -M %s -S %d -A lsa' %(model, seed)
os.system(command)
exit()
for r in rn:
for model in model_names:
for label in labels:
for q in qq:
for at in attacks:
command = 'python coverage_runner.py -A cc -M %s -DS cifar10 -C %d \
-Q %d -RN %d -ADV %s' %(model, label,\
q, r, at)
os.system(command)
|
""" Setup for pytrafikverket """
from setuptools import setup
setup(
name="pytrafikverket",
version="0.1.5.8",
description="api for trafikverket in sweden",
url='https://github.com/AnderssonPeter/pytrafikverket',
author="Peter Andersson",
license="MIT",
install_requires=["aiohttp", "async-timeout", "lxml"],
packages=["pytrafikverket"],
zip_safe=True,
entry_point={
"console_scripts": [
"pytrafikverket=pytrafikverket.pytrafikverket:main"
]
}
)
|
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
f = host.file('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
@pytest.mark.parametrize("name", [
("haproxy"),
])
def test_packages(host, name):
pkg = host.package(name)
assert pkg.is_installed
def test_haproxy_port(host):
haproxy = host.addr("127.0.0.1")
haproxy.port(80).is_reachable
def test_haproxy_config(host):
haproxy_config = host.file("/etc/haproxy/haproxy.cfg")
haproxy_config.exists
oct(haproxy_config.mode) == '0644'
haproxy_config.user == 'root'
haproxy_config.group == 'root'
|
from .utils import *
from .music import *
|
#!/usr/bin/env python
"""Lists results directories with a summary of their contents.
Useful for quickly inspecting which directory contains which experiments.
Also shows if any scripts are still running.
For scripts that run many experiments, it shows the number of experiments
finished, expected and unfinished. For example, "13/20 r1" means 13 of the
expected 20 experiments have finished, 1 is unfinished, and the relevant process
appears still to be running ("r") on this machine. The other status codes are
"u" for unfinished but not running, and "?" for hasn't started.
"""
# Chuan-Zheng Lee <[email protected]>
# July 2021
import argparse
import datetime
import itertools
import json
import re
from pathlib import Path
import psutil
from config import RESULTS_DIRECTORY
# copied from run_experiments.py to avoid needing all the main packages
# (this allows this to be run from a symlink in kyanite)
all_matrix_labels = ['clients', 'noise']
ARGUMENT_ABBREVIATIONS = {
'noise': 'σₙ²',
'power': 'P',
'parameter_radius': 'B',
'clients': 'n',
'dataset': 'data',
'momentum_client': 'mom',
'momentum': 'mom',
'lr_client': 'lr',
'repeat': 'rep',
'rounds': 'rds',
'optimizer': 'opt',
'parameter_radius_initial': 'Bin',
}
DATASET_ABBREVIATIONS = {
"epsilon": "eps",
"epsilon-small": "eps-sm",
"cifar10-simple": "c10-sim",
"cifar10-simple-flipcrop": "c10-sim-fc",
"cifar10-resnet20": "c10-r20",
"cifar10-resnet18": "c10-r18",
"cifar10-resnet20-flipcrop": "c10-r20-fc",
"cifar10-resnet18-flipcrop": "c10-r18-fc",
"fashionmnist-simple": "fmn-sim",
"fashionmnist-cnn1": "fmn-cnn1",
"fashionmnist-cnn2": "fmn-cnn2",
}
DEFAULT_ARGUMENTS = {
'rounds': 20,
'batch_size': 64,
'clients': 10,
'lr_client': 0.01,
'momentum_client': 0.0,
'weight_decay_client': 0.0,
'optimizer_client': 'sgd',
'lr_scheduler_client': 'none',
'noise': 1.0,
'power': 1.0,
'parameter_radius': 1.0,
'small': False,
'cpu': False,
'epochs': 1,
'ema_coefficient': 1 / 3,
'power_update_period': 1,
'power_quantile': 1.0,
'power_factor': 0.9,
'parameter_radius_initial': 1.0,
'qrange_update_period': 1,
'qrange_param_quantile': 1.0,
'qrange_client_quantile': 1.0,
'qrange_initial': 1.0,
'rounding_method': 'stochastic',
'zero_bits_strategy': 'read-zero',
'save_models': False,
'send': 'deltas',
'save_squared_error': False,
'parameter_schedule': 'staggered',
'weight_decay': 0.0,
'momentum': 0.0,
'optimizer': 'sgd',
'lr_scheduler': 'none',
'client_sync': True,
}
def process_legacy_arguments(argsfile):
"""Process arguments that were in the old arguments.txt format."""
with open(argsfile) as f:
script = None
started = None
commit = None
for line in f:
if line.startswith("script: "):
script = line[8:].strip()
if line.startswith("started: "):
started = line[9:].strip()
started = datetime.datetime.strptime(started, '%Y-%m-%dT%H:%M:%S.%f')
if line.startswith("commit: "):
commit = line[8:15].strip()
if line.strip() == "== arguments ==":
break
arguments = {}
for line in f:
key, value = line.split(sep=':', maxsplit=1)
key = key.strip()
value = value.strip()
arguments[key] = value
return script, started, commit, None, arguments
def process_arguments(argsfile):
"""Process arguments in the standard arguments.json format."""
with open(argsfile) as f:
args_dict = json.load(f)
script = args_dict.get('script', '???')
started = args_dict.get('started', None)
if started is not None:
started = datetime.datetime.strptime(started, '%Y-%m-%dT%H:%M:%S.%f')
git = args_dict.get('git', {})
commit = git.get('commit', '??? ')[:7]
changed_files = git.get('changed_files', [])
if changed_files and changed_files != ['']:
commit += "*"
else:
commit += " "
process_id = args_dict.get('process_id')
arguments = args_dict.get('args', {})
# This is the new version
if script == 'run.py' and 'experiment' in arguments:
script = arguments.pop('experiment')
return script, started, commit, process_id, arguments
def is_composite_argument(key, value):
if key == 'repeat':
return True
if key in ['clients', 'noise'] and isinstance(value, list):
return True
return False
def format_args_string(arguments, always_show=[], repeat_changed=False):
args_items = sorted(arguments.items(), key=lambda item: not is_composite_argument(*item))
formatted_args = []
for key, value in args_items:
key_in_always_show = key in always_show or shorten_key_name(key) in always_show
if DEFAULT_ARGUMENTS.get(key) == value and not key_in_always_show:
continue
if key == 'repeat' and repeat_changed:
value = f"\033[1;35m{value}"
formatted_args.append(format_argument(key, value))
return " ".join(formatted_args)
def format_argument(key, value):
is_composite = is_composite_argument(key, value)
key = shorten_key_name(key)
value = format_arg_value(value)
if is_composite:
return f"\033[0;34m{key}=\033[1;34m{value}\033[0m"
else:
return f"\033[0;90m{key}=\033[0m{value}"
def shorten_key_name(key):
"""Shortens long keys."""
if key in ARGUMENT_ABBREVIATIONS:
return ARGUMENT_ABBREVIATIONS[key]
words = key.split("_")
if len(words) == 1:
return key
return "".join(word[0] for word in words).upper()
def format_arg_single_value(value):
if isinstance(value, float):
return f"{value:.4g}"
elif value in DATASET_ABBREVIATIONS:
return DATASET_ABBREVIATIONS[value]
return str(value)
def format_arg_value(value):
"""Formats an argument value for display.
Currently, this just simplifies lists of consecutive integers."""
if not isinstance(value, list):
return format_arg_single_value(value)
if len(value) == 1 or not all([isinstance(x, int) for x in value]):
return "[" + ", ".join([format_arg_single_value(x) for x in value]) + "]"
lowest = min(value)
highest = max(value)
if value == list(range(lowest, highest + 1)):
return f"{{{lowest}..{highest}}}"
return str(value)
def has_started(directory):
"""Returns True if the experiments in this directory appear to have
(non-trivially) started.
"""
return len(list(directory.iterdir())) > 1
def has_finished(directory):
"""Returns True if the experiments in this directory appear to have
finished.
"""
if (directory / "result.txt").exists():
return True
if (directory / "evaluation.json").exists():
return True
def parse_start_time(args):
# the default start time depends on whether args.dir was given
if args.recent is None and args.after is None and args.all is False:
if args.dir is None:
args.recent = '1d'
else:
args.all = True
if args.all:
return None
if args.after is not None:
formats = ["%Y", "%Y%m", "%Y%m%d", "%Y%m%d-%H", "%Y%m%d-%H%M", "%Y%m%d-%H%M%S"]
for fmt in formats:
try:
start_time = datetime.datetime.strptime(args.after, fmt)
except ValueError:
continue
else:
return start_time
else:
print(f"Invalid --after argument: {args.after}")
exit(1)
if args.recent is not None:
pattern = r'^(?:(\d+(?:\.\d*)?)d)?(?:(\d+(?:\.\d*)?)h)?$'
m = re.match(pattern, args.recent)
if not m:
print(f"Invalid --recent argument: {args.recent}")
exit(1)
days, hours = m.groups()
period = datetime.timedelta(days=float(days) if days else 0, hours=float(hours) if hours else 0)
return datetime.datetime.now() - period
return None
def is_composite_directory(arguments):
if not arguments:
return False
if 'repeat' in arguments:
return True
return False
def detect_composite_status(directory, arguments):
"""Returns a 3-tuple `(unfinished, finished, expected)` where
- `unfinished` is the number of directories that exist but have not finished
- `finished` is the number of directories that have finished
It is assumed that the directory is composite, i.e. that
`is_composite_directory(directory)` is true.
"""
labels = []
matrix = []
expected = arguments['repeat']
childname_parts = []
for label in all_matrix_labels:
values = arguments.get(label)
if isinstance(values, list):
labels.append(label)
matrix.append(values)
expected *= len(values)
childname_parts.append(label + "-{" + label + "}")
labels.append('iteration')
matrix.append(range(arguments['repeat']))
finished = 0
unfinished = 0
for values in itertools.product(*matrix):
childname = "-".join(f"{label}-{value}" for label, value in zip(labels, values))
if has_finished(directory / childname):
finished += 1
elif (directory / childname).exists():
unfinished += 1
return unfinished, finished, expected
def check_repeats_file(directory, arguments):
if (directory / "repeats").exists():
# override repeat with repeats file
try:
new_value = int(open(directory / "repeats").readline())
except (ValueError, FileNotFoundError):
return False
if arguments['repeat'] != new_value:
arguments['repeat'] = new_value
return True
else:
return False
else:
return False
def show_status_line(directory, if_after=None, always_show=[], filter_args={}):
"""Shows the status and arguments of the directory in a single line.
If `if_after` is provided, it should be a `datetime.datetime` object, and if
the directory indicates that its experiments started after this time, this
does nothing.
Arguments in `always_show` are always shown, even if they match the default.
"""
dirname = directory.name
if (directory / "arguments.json").exists():
info_tuple = process_arguments(directory / "arguments.json")
elif (directory / "arguments.txt").exists():
info_tuple = process_legacy_arguments(directory / "arguments.txt")
else:
if if_after and datetime.datetime.strptime(dirname, "%Y%m%d-%H%M%S") > if_after:
print(f"\033[1;31m{dirname} ???\033[0m")
return
script, started, commit, process_id, arguments = info_tuple
if if_after and started and started < if_after:
return
if not matches_filter(filter_args, script, arguments):
return
repeat_changed = check_repeats_file(directory, arguments)
argsstring = format_args_string(arguments, always_show=always_show, repeat_changed=repeat_changed)
is_running = process_id is not None and psutil.pid_exists(process_id)
stopnow_color = "\033[1;31m" if is_running else "\033[0;31m"
stopnow = f"{stopnow_color}!\033[0m" if (directory / "stop-now").exists() else " "
if is_composite_directory(arguments):
unfinished, finished, expected = detect_composite_status(directory, arguments)
if is_running:
color = "\033[0;32m"
status = f"{finished:>3}/{expected:<3}{stopnow}{color}r{unfinished}"
elif unfinished > 0:
# not running, but at least one is unfinished
color = "\033[1;35m"
status = f"{finished:>3}/{expected:<3}{stopnow}{color}u{unfinished}"
elif finished == expected:
# seems to be done and dusted
color = ""
status = f"{finished:>3}/{expected:<3}{stopnow}{color} "
else:
# seems to be incomplete but no single run is unfinished
color = "\033[1;33m"
status = f"{finished:>3}/{expected:<3}{stopnow}{color}u{unfinished}"
elif is_running:
color = "\033[0;32m"
status = f" {stopnow}{color}r "
elif not has_started(directory):
color = "\033[0;31m"
status = f" {stopnow}{color}? "
elif not has_finished(directory):
color = "\033[0;33m"
status = f" {stopnow}{color}u "
else:
color = "\033[0;34m"
status = f" {stopnow}{color} "
print(f"{color}{dirname:16} {commit} {status:10} {script:<17}\033[0m {argsstring}")
def parse_filter_args(args):
"""Parses --filter arguments from the command line."""
filter_args = {}
for arg in args:
if arg.endswith(".py"):
filter_args['__script__'] = arg
elif "=" in arg:
key, value = arg.split("=", maxsplit=1)
filter_args[key] = value
return filter_args
def matches_filter(filter_args, script, arguments):
"""Returns True if the `script` and `arguments` match the specification in
`filter_args`. If `arguments` doesn't have an argument in the filter, it's
considered to match vacuously, i.e. False is only returned if there is
a specific argument that does not match.
"""
arguments_with_shortened_keys = {shorten_key_name(key): value for key, value in arguments.items()}
for filter_key, filter_value in filter_args.items():
if filter_key == 'script':
if script != filter_args['script']:
return False
elif filter_key in arguments:
if format_arg_single_value(arguments[filter_key]) != filter_value:
return False
elif filter_key in arguments_with_shortened_keys:
if format_arg_single_value(arguments_with_shortened_keys[filter_key]) != filter_value:
return False
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("dir", type=Path, nargs='?', default=None,
help=f"Results directory (default: {RESULTS_DIRECTORY})")
parser.add_argument("-s", "--show", nargs='+', default=[], metavar="ARG",
help="Always show these arguments, even if equal to the default")
parser.add_argument("-f", "--filter", nargs='+', default=[],
help="Only show directories matching this filter. Valid filters: (a) "
"the name of a script, e.g. dynquant.py, (b) single-value argument "
"spec, e.g. rounds=150")
when = parser.add_mutually_exclusive_group()
when.add_argument("-r", "--recent", type=str, default=None, metavar="PERIOD",
help="Only show directories less than a day old, or less than a specified "
"period of time, e.g. 2d for 2 days, 3h for 3 hours, 1d5h for 1 day "
"5 hours. This is the default, with a period of 1 day.")
when.add_argument("-a", "--after", type=str, default=None, metavar="DATETIME",
help="Only show directories after this date and time, specified in the format "
"yyyymmdd-hhmmss, partial specifications (e.g. yyyymmdd-hh) allowed")
when.add_argument("-A", "--all", action="store_true", default=False,
help="List all directories, no matter how old")
args = parser.parse_args()
# keep info on whether --dir was specified for parse_start_time(args) below
resultsdir = args.dir or Path(RESULTS_DIRECTORY)
if not resultsdir.is_dir():
print(f"{resultsdir} is not a directory")
exit(1)
directories = sorted(resultsdir.iterdir())
start_time = parse_start_time(args)
if start_time:
print("\033[1;37mShowing directories after:", start_time.isoformat(), "\033[0m")
filter_args = parse_filter_args(args.filter)
if filter_args:
print("\033[1;37mShowing only directories matching:",
", ".join(f"{key}={value}" for key, value in filter_args.items()), "\033[0m")
for directory in directories:
if not directory.is_dir():
continue
show_status_line(directory, if_after=start_time, always_show=args.show, filter_args=filter_args)
|
import collections
class Solution:
def getHint(self, secret: str, guess: str) -> str:
table = collections.Counter()
bull = cow = 0
for s, g in zip(secret, guess):
if s == g:
bull += 1
else:
if table[s] < 0:
cow += 1
table[s] += 1
if table[g] > 0:
cow += 1
table[g] -= 1
return str(bull) + 'A' + str(cow) + 'B'
|
c = get_config()
c.Exchange.root = '/srv/nbgrader/exchange'
c.Exchange.course_id = "2018s-ocng469"
|
from enum import Enum
class OpArithmetic(Enum):
PLUS = 1
MINUS = 2
TIMES = 3
DIVIDE = 4
MODULE = 5
POWER = 6
class OpLogical(Enum):
GREATER = 1
LESS = 2
EQUALS = 3
NOT_EQUALS = 4
GREATER_EQUALS = 5
LESS_EQUALS = 6
LIKE = 7
NOT_LIKE = 8
class OpRelational(Enum):
AND = 1
OR = 2
NOT = 3
def say_hi():
print('Python Cook Book')
|
from logging import BASIC_FORMAT
import tictactoe as t
import test_helper as helper
import unittest
class TestTicTacToe(unittest.TestCase):
def test_player(self):
for test_case in helper.test_cases:
self.assertEqual(t.player(test_case["board"]),test_case["player"])
def test_terminal(self):
self.assertTrue(t.terminal([['O', 'X', 'O'], ['X', 'X', 'O'], ['X', 'O', 'X']]))
def test_result(self):
board = [['O', 'O', 'X'], ['X', 'O', 'X'], [t.EMPTY, 'X', t.EMPTY]]
tmp = t.result(board,(2,2))
self.assertEqual(tmp,[['O', 'O', 'X'], ['X', 'O', 'X'], [t.EMPTY, 'X', 'O']])
self.assertEqual(board,[['O', 'O', 'X'], ['X', 'O', 'X'], [t.EMPTY, 'X', t.EMPTY]])
def test_minimax(self):
self.assertEqual(t.minimax([['O', 'X', 'O'], ['X', 'X', 'O'], ['X', 'O', t.EMPTY]]),(2,2))
self.assertEqual(t.minimax([['O', 'X', 'O'], ['X', 'X', 'O'], ['X', t.EMPTY, t.EMPTY]]),(2,2))
self.assertEqual(t.minimax([['O', 'O', 'X'], ['X', 'O', 'X'], [t.EMPTY, 'X', t.EMPTY]]),(2,2))
self.assertEqual(t.minimax([
[t.X, t.EMPTY, t.EMPTY],
[t.EMPTY, t.O, t.EMPTY],
[t.EMPTY, t.EMPTY, t.EMPTY],
]),(0,1))
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
"""
Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br)
Centro de Informática (CIn) (http://www.cin.ufpe.br)
Projeto Programação 1
Graduando em Sistemas de Informação
IF968 - Programação 1
Autor: Matheus Ribeiro Brant Nobre (mrbn)
Email: [email protected]
Copyright(c) 2018 Matheus Ribeiro Brant Nobre
"""
"""
Funcionalidade do Script: Esse scirpt contém as funções de busca e apresentação
dos produtos ao usuário. As operaões que chamam as funções abaixo estão
no script principal.
"""
def exibirProdutos(produtos, cardapio):
'''
Percorre a lista que armazena os dados dos produtos e printa na tela
a quantidade, nome e valor do pedido realizado pelo usuário. Essa função é
chamada no comando 10 do script principal.
'''
for tupla in produtos:
nome = tupla[0]
qtd = tupla[1]
valor = cardapio[nome][1]
print("{} {} - R${}".format(qtd, nome, qtd*valor))
def buscaProdutos(cardapio, valor):
'''
Percorre a lista que armazena os dados dos produtos e acrescenta ao final
da lista resultados cada elemento que tenha um valor menor ou igual ao
valor informado pelo usuário, retornado essa lista ao final. Essa função é
chamada no comando 12 do script principal.
'''
resultados = []
for produto in cardapio:
if cardapio[produto][1] <= valor:
resultados.append(produto)
resultados.sort()
return resultados |
#!/usr/bin/env python
# coding=utf8
# File: lab_export.py
from rllab.utils import logger
___all__ = ['lab_export']
class lab_export(object):
"""decorator to export RLlab API"""
def __init__(self, *args):
self._name = args[0]
def __call__(self, func):
"""Calls this decorator"""
func._lab_api_names = self._name
return func
|
# Copyright (c) Youngwan Lee (ETRI) All Rights Reserved.
from .config import add_vovnet_config
from .vovnet import build_vovnet_fpn_backbone, build_vovnet_backbone
from .mobilenet import build_mobilenetv2_fpn_backbone, build_mnv2_backbone |
#!/usr/bin/env python
#
# Make a legend for specific lines.
from pylab import *
t1 = arange(0.0, 2.0, 0.1)
t2 = arange(0.0, 2.0, 0.01)
# note that plot returns a list of lines. The "l1, = plot" usage
# extracts the first element of the list inot l1 using tuple
# unpacking. So l1 is a Line2D instance, not a sequence of lines
l1, = plot(t2, exp(-t2))
l2, l3 = plot(t2, sin(2*pi*t2), '--go', t1, log(1+t1), '.')
l4, = plot(t2, exp(-t2)*sin(2*pi*t2), 'rs-.')
legend( (l2, l4), ('oscillatory', 'damped'), 'upper right', shadow=True)
xlabel('time')
ylabel('volts')
title('Damped oscillation')
#axis([0,2,-1,1])
show()
|
operations_maps = {
'eq': lambda first, second: first == second,
'ne': lambda first, second: first != second,
'gt': lambda first, second: first > second,
'ge': lambda first, second: first >= second,
'lt': lambda first, second: first < second,
'le': lambda first, second: first <= second,
}
def context_strategy(toggle, context):
for condition in toggle['conditions']:
value = context[condition['field']]
expected_value = condition['value']
operation = condition['operation']
if not operations_maps[operation](expected_value, value):
return False
return True
|
"""
AssignResources class for CentralNodeLow.
"""
# PROTECTED REGION ID(CentralNode.additionnal_import) ENABLED START #
# Standard Python imports
import json
import time
# Tango imports
import tango
from tango import DevState, DevFailed
# Additional import
from ska.base.commands import BaseCommand
from tmc.common.tango_client import TangoClient
from tmc.common.tango_server_helper import TangoServerHelper
from . import const
class AssignResources(BaseCommand):
"""
A class for CentralNode's AssignResources() command.
Assigns resources to given subarray. It accepts the subarray id, mccs string which contains subarray_beam_ids, station id and channels blocks
in JSON string format.
"""
def check_allowed(self):
"""
Checks whether this command is allowed to be run in current device state
:return: True if this command is allowed to be run in current device state
:rtype: boolean
:raises: DevFailed if this command is not allowed to be run
in current device state
"""
if self.state_model.op_state in [
DevState.FAULT,
DevState.UNKNOWN,
DevState.DISABLE,
]:
tango.Except.throw_exception(
f"Command AssignResources is not allowed in current state {self.state_model.op_state}.",
"Failed to invoke AssignResources command on CentralNode.",
"CentralNode.AssignResources()",
tango.ErrSeverity.ERR,
)
return True
def do(self, argin):
"""
Method to invoke AssignResources command on Subarray.
:param argin: The string in JSON format. The JSON contains following values:
interface:
DevString. Mandatory.
Version of schema to allocate assign resources.
subarray_id:
DevShort. Mandatory.
Sub-Array to allocate resources to
mccs:
subarray_beam_ids:
DevArray. Mandatory
logical ID of beam
station_ids:
DevArray. Mandatory
list of stations contributing beams to the data set
channel_blocks:
DevArray. Mandatory
list of channels used
Example:
{"interface":"https://schema.skao.int/ska-low-tmc-assignresources/2.0","transaction_id":"txn-....-00001","subarray_id":1,"mccs":{"subarray_beam_ids":[1],"station_ids":[[1,2]],"channel_blocks":[3]},"sdp":{}}
Note: Enter input without spaces as: {"interface":"https://schema.skao.int/ska-low-tmc-assignresources/2.0","transaction_id":"txn-....-00001","subarray_id":1,"mccs":{"subarray_beam_ids":[1],"station_ids":[[1,2]],"channel_blocks":[3]},"sdp":{}}
return:
None
raises:
KeyError if input argument json string contains invalid key
ValueError if input argument json string contains invalid value
AssertionError if Mccs On command is not completed.
"""
device_data = self.target
try:
self.this_server = TangoServerHelper.get_instance()
# Check if Mccs On command is completed
cmd_res = json.loads(device_data.cmd_res_evt_val)
log_msg = "commandresult attribute value in StandByTelescope command", cmd_res
self.logger.debug(log_msg)
if cmd_res["result_code"] != 0:
retry = 0
while retry < 3:
if cmd_res["result_code"] == 0:
break
retry += 1
time.sleep(0.1)
assert cmd_res["result_code"] == 0, "Startup command completed OK"
json_argument = json.loads(argin)
subarray_id = int(json_argument["subarray_id"])
subarray_cmd_data = self._create_subarray_cmd_data(json_argument)
log_msg = f"Assigning resources to subarray :-> {subarray_id}"
self.logger.info(log_msg)
subarray_client = self.create_client(
device_data.subarray_FQDN_dict[subarray_id]
)
self.invoke_assign_resources(subarray_client, subarray_cmd_data)
mccs_string = json.loads(argin)
input_mccs_master = self._create_mccs_cmd_data(mccs_string)
self.mccs_master_ln_fqdn = ""
property_value = self.this_server.read_property("MCCSMasterLeafNodeFQDN")
self.mccs_master_ln_fqdn = self.mccs_master_ln_fqdn.join(property_value)
mccs_master_ln_client = self.create_client(self.mccs_master_ln_fqdn)
self.invoke_assign_resources(mccs_master_ln_client, input_mccs_master)
self.this_server.write_attr("activityMessage", const.STR_ASSIGN_RESOURCES_SUCCESS, False)
self.logger.info(const.STR_ASSIGN_RESOURCES_SUCCESS)
except KeyError as key_error:
self.logger.error(const.ERR_JSON_KEY_NOT_FOUND)
self.this_server.write_attr("activityMessage", f"{const.ERR_JSON_KEY_NOT_FOUND}{key_error}", False)
log_msg = f"{const.ERR_JSON_KEY_NOT_FOUND}{key_error}"
self.logger.exception(key_error)
tango.Except.throw_exception(
const.STR_RESOURCE_ALLOCATION_FAILED,
log_msg,
"CentralNode.AssignResourcesCommand",
tango.ErrSeverity.ERR,
)
except ValueError as val_error:
self.logger.exception(
"Exception in AssignResources command: %s", str(val_error)
)
self.this_server.write_attr("activityMessage", f"Invalid value in input: {val_error}", False)
log_msg = f"{const.STR_ASSIGN_RES_EXEC}{val_error}"
self.logger.exception(val_error)
tango.Except.throw_exception(const.STR_RESOURCE_ALLOCATION_FAILED, log_msg,
"CentralNode.AssignResourcesCommand",
tango.ErrSeverity.ERR)
except AssertionError:
log_msg = "Exception in AssignResources command: " + const.ERR_STARTUP_CMD_INCOMPLETE
self.logger.exception(log_msg)
log_msg = const.STR_ASSIGN_RES_EXEC + const.ERR_STARTUP_CMD_INCOMPLETE
self.logger.exception(log_msg)
self.this_server.write_attr("activityMessage", log_msg, False)
tango.Except.throw_exception(const.ERR_STARTUP_CMD_INCOMPLETE, log_msg,
"CentralNode.AssignResourcesCommand",
tango.ErrSeverity.ERR)
message = const.STR_RETURN_MSG_ASSIGN_RESOURCES_SUCCESS
self.logger.info(message)
return message
def _create_mccs_cmd_data(self, json_argument):
"""
Remove 'sdp' and 'mccs' key from input JSON argument and forward the updated JSON to mccs master leaf node.
:param json_argument: The string in JSON format.
:return: The string in JSON format.
"""
mccs_value = json_argument["mccs"]
json_argument["interface"] = "https://schema.skao.int/ska-low-mccs-assignresources/1.0"
if 'transaction_id' in json_argument:
del json_argument["transaction_id"]
if 'sdp' in json_argument:
del json_argument["sdp"]
if 'mccs' in json_argument:
del json_argument["mccs"]
json_argument.update(mccs_value)
input_to_mccs= json.dumps(json_argument)
return input_to_mccs
def _create_subarray_cmd_data(self, json_argument):
"""
Remove 'subarray id', 'sdp' from json argument and forward the updated JSON to Subarray node.
:param json_argument: The string in JSON format.
:return: The string in JSON format.
"""
# Remove subarray_id key from input json argument and send the json to subarray node
if 'subarray_id' in json_argument:
del json_argument["subarray_id"]
if 'sdp' in json_argument:
del json_argument["sdp"]
input_to_subarray = json.dumps(json_argument)
return input_to_subarray
def create_client(self, fqdn):
"""
Creates TangoClient for given FQDN
:param fqdn: String. FQDN of the Tango device for which client object is to be created.
return: TangoClient object
"""
return TangoClient(fqdn)
def invoke_assign_resources(self, tango_client, input_arg):
"""
Invokes assign Resources command on leaf node with input argument.
:param tango_client: client of corresponding leaf node
:param input_arg: Json string input to invoke command.
:raises: DevFailed if error occurs while invoking command on any of the devices like SubarrayNode, MCCSMasterLeafNode
"""
try:
tango_client.send_command(const.CMD_ASSIGN_RESOURCES, input_arg)
log_msg = "Assign resurces command invoked successfully on {}".format(
tango_client.get_device_fqdn
)
self.logger.debug(log_msg)
self.this_server.write_attr("activityMessage", log_msg, False)
except DevFailed as dev_failed:
log_msg = f"{const.ERR_ASSGN_RESOURCES}{dev_failed}"
self.logger.exception(dev_failed)
tango.Except.throw_exception(
const.STR_CMD_FAILED,
log_msg,
"CentralNode.AssignResourcesCommand",
tango.ErrSeverity.ERR,
)
|
from ast import parse
import copy
import os
import sys
import argparse
from tracemalloc import start
import smartsheet
from pptree import *
def init_client():
token_name = "SMARTSHEET_ACCESS_TOKEN"
token = os.getenv(token_name)
if token == None:
sys.exit(f"{token_name} not set")
client = smartsheet.Smartsheet(token)
client.errors_as_exceptions(True)
return client
def parse_args():
parser = argparse.ArgumentParser(
description="Explore Smartsheet Workspaces")
parser.add_argument('workspace_id')
parser.add_argument('--output', choices=['tree', 'csv'], default='tree')
parser.add_argument('--starting_folder_id', type=int,
help='Displays folders starting with and contained by this folder')
parser.add_argument('--depth', type=int, default=0,
help='Depth from starting point to print (csv output only)')
return parser.parse_args()
def find_folder_in(workspace, folder_id_to_find):
search_domain = copy.copy(workspace.folders)
i = 0
while i < len(search_domain):
folder = search_domain[i]
if folder.id == folder_id_to_find:
return folder
search_domain += folder.folders
i += 1
return None
def print_csv(starting_folder, depth):
starting_folder.depth = 0
list = [starting_folder]
i = 0
while i < len(list):
current = list[i]
if current.depth == depth:
print(f'"{current.name}","{current.id}"')
else:
for f in current.folders:
f.name = f'{current.name}/{f.name}'
f.depth = current.depth + 1
list += current.folders
i += 1
args = parse_args()
client = init_client()
workspace = client.Workspaces.get_workspace(
workspace_id=args.workspace_id, load_all=True, include=["folders"])
if args.starting_folder_id == None:
top = workspace
else:
top = find_folder_in(workspace, args.starting_folder_id)
if top == None:
sys.exit("Folder not found")
if args.output == 'tree':
print_tree(top, childattr="folders")
else:
print_csv(top, args.depth)
|
import unittest
from io import StringIO
import re
import numpy as np
import openmdao.api as om
from openmdao.utils.array_utils import evenly_distrib_idxs
from openmdao.utils.mpi import MPI
class MixedDistrib2(om.ExplicitComponent):
def setup(self):
# Distributed Input
self.add_input('in_dist', shape_by_conn=True, distributed=True)
# Serial Input
self.add_input('in_serial', val=1)
# Distributed Output
self.add_output('out_dist', copy_shape='in_dist', distributed=True)
# Serial Output
self.add_output('out_serial', copy_shape='in_serial')
def compute(self, inputs, outputs):
x = inputs['in_dist']
y = inputs['in_serial']
# "Computationally Intensive" operation that we wish to parallelize.
f_x = x**2 - 2.0*x + 4.0
# These operations are repeated on all procs.
f_y = y ** 0.5
g_y = y**2 + 3.0*y - 5.0
# Compute square root of our portion of the distributed input.
g_x = x ** 0.5
# Distributed output
outputs['out_dist'] = f_x + f_y
# Serial output
# We need to gather the summed values to compute the total sum over all procs.
local_sum = np.array(np.sum(g_x))
total_sum = local_sum.copy()
MPI.COMM_WORLD.Allreduce(local_sum, total_sum, op=MPI.SUM)
outputs['out_serial'] = g_y * total_sum
def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode):
x = inputs['in_dist']
y = inputs['in_serial']
g_y = y**2 + 3.0*y - 5.0
# These operations are repeated on all procs.
g_y = y**2 + 3.0*y - 5.0
# Compute square root of our portion of the distributed input.
g_x = x ** 0.5
# Serial output
# We need to gather the summed values to compute the total sum over all procs.
local_sum = np.array(np.sum(g_x))
total_sum = local_sum.copy()
MPI.COMM_WORLD.Allreduce(local_sum, total_sum, op=MPI.SUM)
# total_sum
num_x = len(x)
d_g_y__d_y = 2*y + 3.
d_g_x__d_x = 0.5*x**-0.5
d_out_serial__d_y = d_g_y__d_y # scalar
d_out_serial__d_x = g_y*d_g_x__d_x.reshape((1,num_x))
if mode == 'fwd':
if 'out_serial' in d_outputs:
if 'in_dist' in d_inputs:
d_outputs['out_serial'] += d_out_serial__d_x.dot(d_inputs['in_dist'])
if 'in_serial' in d_inputs:
d_outputs['out_serial'] += d_out_serial__d_y.dot(d_inputs['in_serial'])
elif mode == 'rev':
if 'out_serial' in d_outputs:
if 'in_dist' in d_inputs:
d_inputs['in_dist'] += d_out_serial__d_x.T.dot(d_outputs['out_serial'])
if 'in_serial' in d_inputs:
d_inputs['in_serial'] += total_sum*d_out_serial__d_y.T.dot(d_outputs['out_serial'])
@unittest.skipUnless(MPI, "MPI is required.")
class CheckPartialsRev(unittest.TestCase):
N_PROCS = 2
def test_cp_rev_mode(self):
'''
-----------------------------------------------------
The erroneous output contained these values:
Raw Forward Derivative (Jfor)
[[62.5 62.5 62.5]]
Raw Reverse Derivative (Jrev)
[[31.25 31.25 31.25]]
Raw FD Derivative (Jfd)
[[62.49998444 62.49998444 62.49998444]]
...
Raw Forward Derivative (Jfor)
[[62.5 62.5 62.5 62.5]]
Raw Reverse Derivative (Jrev)
[[31.25 31.25 31.25 31.25]]
Raw FD Derivative (Jfd)
[[62.49998444 62.49998444 62.49998444 62.49998444]]
-----------------------------------------------------
The corrected output contains these values:
Raw Forward Derivative (Jfor)
[[62.5 62.5 62.5]]
Raw Reverse Derivative (Jrev)
[[62.5 62.5 62.5]]
Raw FD Derivative (Jfd)
[[62.49998444 62.49998444 62.49998444]]
...
Raw Forward Derivative (Jfor)
[[62.5 62.5 62.5 62.5]]
Raw Reverse Derivative (Jrev)
[[62.5 62.5 62.5 62.5]]
Raw FD Derivative (Jfd)
[[62.49998444 62.49998444 62.49998444 62.49998444]]
-----------------------------------------------------
'''
size = 7
comm = MPI.COMM_WORLD
rank = comm.rank
sizes, offsets = evenly_distrib_idxs(comm.size, size)
prob = om.Problem()
model = prob.model
# Create a distributed source for the distributed input.
ivc = om.IndepVarComp()
ivc.add_output('x_dist', np.zeros(sizes[rank]), distributed=True)
ivc.add_output('x_serial', val=1)
model.add_subsystem("indep", ivc)
model.add_subsystem("D1", MixedDistrib2())
model.add_subsystem('con_cmp1', om.ExecComp('con1 = y**2'), promotes=['con1', 'y'])
model.connect('indep.x_dist', 'D1.in_dist')
model.connect('indep.x_serial', ['D1.in_serial','y'])
prob.driver = om.ScipyOptimizeDriver()
prob.driver.options['optimizer'] = 'SLSQP'
model.add_design_var('indep.x_serial', lower=5, upper=10)
model.add_constraint('con1', upper=90)
model.add_objective('D1.out_serial')
prob.setup(force_alloc_complex=True)
# Set initial values of distributed variable.
x_dist_init = np.ones(sizes[rank])
prob.set_val('indep.x_dist', x_dist_init)
# Set initial values of serial variable.
prob.set_val('indep.x_serial', 10)
prob.run_model()
stream = StringIO()
prob.check_partials(out_stream=stream)
out_str = stream.getvalue()
msg = "Problem.check_partials() output contains a reverse partial derivative divided by comm size."
self.assertNotRegex(out_str, ".*31.25 31.25 31.25.*", msg)
|
"""Test functions for Aracnid Logger functionality.
"""
import os
import pytest
from aracnid_logger import Logger, SlackLogger
def test_module_main():
"""Tests that Aracnid Logger was imported successfully.
"""
config_dir = os.path.dirname(__file__)
logger = Logger('__main__', config_dir=config_dir)
assert logger.logger.name == 'root'
def test_module_sub():
"""Tests that Aracnid Logger was imported successfully.
"""
config_dir = os.path.dirname(__file__)
logger = Logger(__name__, config_dir=config_dir)
assert logger.logger.name == __name__
def test_setting_config_file_by_arg(monkeypatch):
"""Tests setting the config file by passing the argument.
"""
monkeypatch.setenv('LOGGING_CONFIG_FILE', 'logging_config_test.json')
config_dir = os.path.dirname(__file__)
logger = Logger(
'__main__',
config_filename='logging_config_test.json',
config_dir=config_dir)
assert logger.logging_filename == 'logging_config_test.json'
def test_setting_config_file_by_env(monkeypatch):
"""Tests setting the config file by environment variable.
"""
monkeypatch.setenv('LOGGING_CONFIG_FILE', 'logging_config_test.json')
config_dir = os.path.dirname(__file__)
logger = Logger('__main__', config_dir=config_dir)
assert logger.logging_filename == 'logging_config_test.json'
def test_setting_config_file_by_default(monkeypatch):
"""Test that Aracnid Logger sets a default config filename,
if environmental variable is missing.
"""
monkeypatch.delenv('LOGGING_CONFIG_FILE', raising=False)
config_dir = os.path.dirname(__file__)
logger = Logger('__main__', config_dir=config_dir)
assert logger.logging_filename == 'logging_config.json'
def test_setting_config_dir_by_arg(monkeypatch):
"""Tests setting the config dir by passing the argument.
"""
monkeypatch.delenv('LOGGING_CONFIG_DIR', raising=False)
config_dir = os.path.dirname(__file__)
logger = Logger(
'__main__',
config_filename='logging_config_test.json',
config_dir=config_dir)
assert logger.logging_filename == 'logging_config_test.json'
def test_setting_config_dir_by_env(monkeypatch):
"""Tests setting the config dir by environment variable.
"""
config_dir = os.path.dirname(__file__)
monkeypatch.setenv('LOGGING_CONFIG_DIR', config_dir)
logger = Logger(
'__main__',
config_filename='logging_config_test.json')
assert logger.logging_dir == config_dir
def test_missing_config_file(monkeypatch):
"""Tests that Aracnid Logger was imported successfully.
"""
monkeypatch.setenv('LOGGING_CONFIG_FILE', 'logging_config_missing.json')
config_dir = os.path.dirname(__file__)
with pytest.raises(FileNotFoundError):
_ = Logger('__main__', config_dir=config_dir)
def test_setting_formatter_by_arg(monkeypatch):
"""Tests setting the formatter by passing the argument.
"""
monkeypatch.delenv('LOGGING_FORMATTER', raising=False)
config_dir = os.path.dirname(__file__)
logger = Logger(
'__main__',
config_dir=config_dir,
formatter='deployed')
assert logger.formatter == 'deployed'
def test_setting_formatter_by_env(monkeypatch):
"""Tests setting the formatter by environment variable.
"""
monkeypatch.setenv('LOGGING_FORMATTER', 'deployed')
config_dir = os.path.dirname(__file__)
logger = Logger(
'__main__',
config_dir=config_dir)
assert logger.formatter == 'deployed'
def test_setting_formatter_by_default(monkeypatch):
"""Tests setting the formatter by default.
"""
monkeypatch.delenv('LOGGING_FORMATTER', raising=False)
config_dir = os.path.dirname(__file__)
logger = Logger(
'__main__',
config_dir=config_dir)
assert logger.formatter == 'default'
def test_config_slack_handler(monkeypatch):
"""Tests setting the slack handler configuration.
"""
monkeypatch.setenv('LOGGING_CONFIG_FILE', 'logging_config_slack.json')
config_dir = os.path.dirname(__file__)
logger = SlackLogger('__main__', config_dir=config_dir)
# assert False
assert len(logger.logger.handlers) == 2
def test_config_slack_handler_default_error(monkeypatch):
"""Tests setting the slack handler channel to 'default' raised error.
"""
monkeypatch.setenv('LOGGING_CONFIG_FILE', 'logging_config_slack_default.json')
config_dir = os.path.dirname(__file__)
with pytest.raises(ValueError):
_ = SlackLogger('__main__', config_dir=config_dir)
|
#!/usr/bin/env python
"""Functional testing framework for command line applications"""
import difflib
import itertools
import optparse
import os
import re
import signal
import subprocess
import sys
import shutil
import time
import tempfile
try:
import configparser
except ImportError:
import ConfigParser as configparser
__all__ = ['main', 'test']
def findtests(paths):
"""Yield tests in paths in sorted order"""
for p in paths:
if os.path.isdir(p):
for root, dirs, files in os.walk(p):
if os.path.basename(root).startswith('.'):
continue
for f in sorted(files):
if not f.startswith('.') and f.endswith('.t'):
yield os.path.normpath(os.path.join(root, f))
else:
yield os.path.normpath(p)
def regex(pattern, s):
"""Match a regular expression or return False if invalid.
>>> [bool(regex(r, 'foobar')) for r in ('foo.*', '***')]
[True, False]
"""
try:
return re.match(pattern + r'\Z', s)
except re.error:
return False
def glob(el, l):
r"""Match a glob-like pattern.
The only supported special characters are * and ?. Escaping is
supported.
>>> bool(glob(r'\* \\ \? fo?b*', '* \\ ? foobar'))
True
"""
i, n = 0, len(el)
res = ''
while i < n:
c = el[i]
i += 1
if c == '\\' and el[i] in '*?\\':
res += el[i - 1:i + 1]
i += 1
elif c == '*':
res += '.*'
elif c == '?':
res += '.'
else:
res += re.escape(c)
return regex(res, l)
annotations = {'glob': glob, 're': regex}
def match(el, l):
"""Match patterns based on annotations"""
for k in annotations:
ann = ' (%s)\n' % k
if el.endswith(ann) and annotations[k](el[:-len(ann)], l[:-1]):
return True
return False
class SequenceMatcher(difflib.SequenceMatcher, object):
"""Like difflib.SequenceMatcher, but matches globs and regexes"""
def find_longest_match(self, alo, ahi, blo, bhi):
"""Find longest matching block in a[alo:ahi] and b[blo:bhi]"""
# SequenceMatcher uses find_longest_match() to slowly whittle down
# the differences between a and b until it has each matching block.
# Because of this, we can end up doing the same matches many times.
matches = []
for n, (el, line) in enumerate(zip(self.a[alo:ahi], self.b[blo:bhi])):
if el != line and match(el, line):
# This fools the superclass's method into thinking that the
# regex/glob in a is identical to b by replacing a's line (the
# expected output) with b's line (the actual output).
self.a[alo + n] = line
matches.append((n, el))
ret = super(SequenceMatcher, self).find_longest_match(alo, ahi,
blo, bhi)
# Restore the lines replaced above. Otherwise, the diff output
# would seem to imply that the tests never had any regexes/globs.
for n, el in matches:
self.a[alo + n] = el
return ret
def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
tofiledate='', n=3, lineterm='\n', matcher=SequenceMatcher):
"""Compare two sequences of lines; generate the delta as a unified diff.
This is like difflib.unified_diff(), but allows custom matchers.
"""
started = False
for group in matcher(None, a, b).get_grouped_opcodes(n):
if not started:
fromdate = fromfiledate and '\t%s' % fromfiledate or ''
todate = fromfiledate and '\t%s' % tofiledate or ''
yield '--- %s%s%s' % (fromfile, fromdate, lineterm)
yield '+++ %s%s%s' % (tofile, todate, lineterm)
started = True
i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
yield "@@ -%d,%d +%d,%d @@%s" % (i1 + 1, i2 - i1, j1 + 1, j2 - j1,
lineterm)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
for line in a[i1:i2]:
yield ' ' + line
continue
if tag == 'replace' or tag == 'delete':
for line in a[i1:i2]:
yield '-' + line
if tag == 'replace' or tag == 'insert':
for line in b[j1:j2]:
yield '+' + line
needescape = re.compile(r'[\x00-\x09\x0b-\x1f\x7f-\xff]').search
escapesub = re.compile(r'[\x00-\x09\x0b-\x1f\\\x7f-\xff]').sub
escapemap = dict((chr(i), r'\x%02x' % i) for i in range(256))
escapemap.update({'\\': '\\\\', '\r': r'\r', '\t': r'\t'})
def escape(s):
"""Like the string-escape codec, but doesn't escape quotes"""
return escapesub(lambda m: escapemap[m.group(0)], s[:-1]) + ' (esc)\n'
def makeresetsigpipe():
"""Make a function to reset SIGPIPE to SIG_DFL (for use in subprocesses).
Doing subprocess.Popen(..., preexec_fn=makeresetsigpipe()) will prevent
Python's SIGPIPE handler (SIG_IGN) from being inherited by the
child process.
"""
if sys.platform == 'win32' or getattr(signal, 'SIGPIPE', None) is None:
return None
return lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def test(path, shell, indent=2):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
diff is a generator that yields the diff between the two lists.
If a test exits with return code 80, the actual output is set to
None and diff is set to [].
"""
indent = ' ' * indent
cmdline = '%s$ ' % indent
conline = '%s> ' % indent
f = open(path)
abspath = os.path.abspath(path)
env = os.environ.copy()
env['TESTDIR'] = os.path.dirname(abspath)
env['TESTFILE'] = os.path.basename(abspath)
p = subprocess.Popen([shell, '-'], bufsize=-1, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, env=env,
preexec_fn=makeresetsigpipe(),
close_fds=os.name == 'posix')
salt = 'CRAM%s' % time.time()
after = {}
refout, postout = [], []
i = pos = prepos = -1
stdin = []
for i, line in enumerate(f):
refout.append(line)
if line.startswith(cmdline):
after.setdefault(pos, []).append(line)
prepos = pos
pos = i
stdin.append('echo "\n%s %s $?"\n' % (salt, i))
stdin.append(line[len(cmdline):])
elif line.startswith(conline):
after.setdefault(prepos, []).append(line)
stdin.append(line[len(conline):])
elif not line.startswith(indent):
after.setdefault(pos, []).append(line)
stdin.append('echo "\n%s %s $?"\n' % (salt, i + 1))
output = p.communicate(input=''.join(stdin))[0]
if p.returncode == 80:
return (refout, None, [])
# Add a trailing newline to the input script if it's missing.
if refout and not refout[-1].endswith('\n'):
refout[-1] += '\n'
# We use str.split instead of splitlines to get consistent
# behavior between Python 2 and 3. In 3, we use unicode strings,
# which has more line breaks than \n and \r.
pos = -1
ret = 0
for i, line in enumerate(output[:-1].split('\n')):
line += '\n'
if line.startswith(salt):
presalt = postout.pop()
if presalt != '%s\n' % indent:
postout.append(presalt[:-1] + ' (no-eol)\n')
ret = int(line.split()[2])
if ret != 0:
postout.append('%s[%s]\n' % (indent, ret))
postout += after.pop(pos, [])
pos = int(line.split()[1])
else:
if needescape(line):
line = escape(line)
postout.append(indent + line)
postout += after.pop(pos, [])
diffpath = os.path.basename(abspath)
diff = unified_diff(refout, postout, diffpath, diffpath + '.err')
for firstline in diff:
return refout, postout, itertools.chain([firstline], diff)
return refout, postout, []
def prompt(question, answers, auto=None):
"""Write a prompt to stdout and ask for answer in stdin.
answers should be a string, with each character a single
answer. An uppercase letter is considered the default answer.
If an invalid answer is given, this asks again until it gets a
valid one.
If auto is set, the question is answered automatically with the
specified value.
"""
default = [c for c in answers if c.isupper()]
while True:
sys.stdout.write('%s [%s] ' % (question, answers))
sys.stdout.flush()
if auto is not None:
sys.stdout.write(auto + '\n')
sys.stdout.flush()
return auto
answer = sys.stdin.readline().strip().lower()
if not answer and default:
return default[0]
elif answer and answer in answers.lower():
return answer
def log(msg=None, verbosemsg=None, verbose=False):
"""Write msg to standard out and flush.
If verbose is True, write verbosemsg instead.
"""
if verbose:
msg = verbosemsg
if msg:
sys.stdout.write(msg)
sys.stdout.flush()
def patch(cmd, diff, path):
"""Run echo [lines from diff] | cmd -p0"""
p = subprocess.Popen([cmd, '-p0'], bufsize=-1, stdin=subprocess.PIPE,
universal_newlines=True,
preexec_fn=makeresetsigpipe(),
cwd=path,
close_fds=os.name == 'posix')
p.communicate(''.join(diff))
return p.returncode == 0
def run(paths, tmpdir, shell, quiet=False, verbose=False, patchcmd=None,
answer=None, indent=2):
"""Run tests in paths in tmpdir.
If quiet is True, diffs aren't printed. If verbose is True,
filenames and status information are printed.
If patchcmd is set, a prompt is written to stdout asking if
changed output should be merged back into the original test. The
answer is read from stdin. If 'y', the test is patched using patch
based on the changed output.
"""
cwd = os.getcwd()
seen = set()
basenames = set()
skipped = failed = 0
for i, path in enumerate(findtests(paths)):
abspath = os.path.abspath(path)
if abspath in seen:
continue
seen.add(abspath)
log(None, '%s: ' % path, verbose)
if not os.stat(abspath).st_size:
skipped += 1
log('s', 'empty\n', verbose)
else:
basename = os.path.basename(path)
if basename in basenames:
basename = '%s-%s' % (basename, i)
else:
basenames.add(basename)
testdir = os.path.join(tmpdir, basename)
os.mkdir(testdir)
try:
os.chdir(testdir)
refout, postout, diff = test(abspath, shell, indent)
finally:
os.chdir(cwd)
errpath = abspath + '.err'
if postout is None:
skipped += 1
log('s', 'skipped\n', verbose)
elif not diff:
log('.', 'passed\n', verbose)
if os.path.exists(errpath):
os.remove(errpath)
else:
failed += 1
log('!', 'failed\n', verbose)
if not quiet:
log('\n', None, verbose)
errfile = open(errpath, 'w')
try:
for line in postout:
errfile.write(line)
finally:
errfile.close()
if not quiet:
if patchcmd:
diff = list(diff)
for line in diff:
log(line)
if (patchcmd and
prompt('Accept this change?', 'yN', answer) == 'y'):
if patch(patchcmd, diff, os.path.dirname(abspath)):
log(None, '%s: merged output\n' % path, verbose)
os.remove(errpath)
else:
log('%s: merge failed\n' % path)
log('\n', None, verbose)
log('# Ran %s tests, %s skipped, %s failed.\n'
% (len(seen), skipped, failed))
return bool(failed)
def which(cmd):
"""Return the patch to cmd or None if not found"""
for p in os.environ['PATH'].split(os.pathsep):
path = os.path.join(p, cmd)
if os.path.isfile(path) and os.access(path, os.X_OK):
return os.path.abspath(path)
return None
def expandpath(path):
"""Expands ~ and environment variables in path"""
return os.path.expanduser(os.path.expandvars(path))
class OptionParser(optparse.OptionParser):
"""Like optparse.OptionParser, but supports setting values through
CRAM= and .cramrc."""
def __init__(self, *args, **kwargs):
self._config_opts = {}
optparse.OptionParser.__init__(self, *args, **kwargs)
def add_option(self, *args, **kwargs):
option = optparse.OptionParser.add_option(self, *args, **kwargs)
if option.dest and option.dest != 'version':
key = option.dest.replace('_', '-')
self._config_opts[key] = option.action == 'store_true'
return option
def parse_args(self, args=None, values=None):
config = configparser.RawConfigParser()
config.read(expandpath(os.environ.get('CRAMRC', '.cramrc')))
defaults = {}
for key, isbool in self._config_opts.items():
try:
if isbool:
try:
value = config.getboolean('cram', key)
except ValueError:
value = config.get('cram', key)
self.error('--%s: invalid boolean value: %r'
% (key, value))
else:
value = config.get('cram', key)
except (configparser.NoSectionError, configparser.NoOptionError):
pass
else:
defaults[key] = value
self.set_defaults(**defaults)
eargs = os.environ.get('CRAM', '').strip()
if eargs:
import shlex
args = args or []
args += shlex.split(eargs)
try:
return optparse.OptionParser.parse_args(self, args, values)
except optparse.OptionValueError:
self.error(str(sys.exc_info()[1]))
def main(args):
"""Main entry point.
args should not contain the script name.
"""
p = OptionParser(usage='cram [OPTIONS] TESTS...', prog='cram')
p.add_option('-V', '--version', action='store_true',
help='show version information and exit')
p.add_option('-q', '--quiet', action='store_true',
help="don't print diffs")
p.add_option('-v', '--verbose', action='store_true',
help='show filenames and test status')
p.add_option('-i', '--interactive', action='store_true',
help='interactively merge changed test output')
p.add_option('-y', '--yes', action='store_true',
help='answer yes to all questions')
p.add_option('-n', '--no', action='store_true',
help='answer no to all questions')
p.add_option('-E', '--preserve-env', action='store_true',
help="don't reset common environment variables")
p.add_option('--keep-tmpdir', action='store_true',
help='keep temporary directories')
p.add_option('--shell', action='store', default='/bin/sh', metavar='PATH',
help='shell to use for running tests')
p.add_option('--indent', action='store', default=2, metavar='NUM',
type='int', help='number of spaces to use for indentation')
opts, paths = p.parse_args(args)
if opts.version:
sys.stdout.write("""Cram CLI testing framework (version 0.6)
Copyright (C) 2010-2011 Brodie Rao <[email protected]> and others
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
""")
return
conflicts = [('-y', opts.yes, '-n', opts.no),
('-q', opts.quiet, '-i', opts.interactive)]
for s1, o1, s2, o2 in conflicts:
if o1 and o2:
sys.stderr.write('options %s and %s are mutually exclusive\n'
% (s1, s2))
return 2
patchcmd = None
if opts.interactive:
patchcmd = which('patch')
if not patchcmd:
sys.stderr.write('patch(1) required for -i\n')
return 2
if not paths:
sys.stdout.write(p.get_usage())
return 2
badpaths = [path for path in paths if not os.path.exists(path)]
if badpaths:
sys.stderr.write('no such file: %s\n' % badpaths[0])
return 2
tmpdir = os.environ['CRAMTMP'] = tempfile.mkdtemp('', 'cramtests-')
proctmp = os.path.join(tmpdir, 'tmp')
os.mkdir(proctmp)
for s in ('TMPDIR', 'TEMP', 'TMP'):
os.environ[s] = proctmp
if not opts.preserve_env:
for s in ('LANG', 'LC_ALL', 'LANGUAGE'):
os.environ[s] = 'C'
os.environ['TZ'] = 'GMT'
os.environ['CDPATH'] = ''
os.environ['COLUMNS'] = '80'
os.environ['GREP_OPTIONS'] = ''
if opts.yes:
answer = 'y'
elif opts.no:
answer = 'n'
else:
answer = None
try:
return run(paths, tmpdir, opts.shell, opts.quiet, opts.verbose,
patchcmd, answer, opts.indent)
finally:
if opts.keep_tmpdir:
log('# Kept temporary directory: %s\n' % tmpdir)
else:
shutil.rmtree(tmpdir)
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except KeyboardInterrupt:
pass
|
import abc
from collections import OrderedDict
from typing import Iterable,MutableMapping
from torch import nn as nn
from rlkit.core.batch_rl_algorithm import BatchRLAlgorithm
from rlkit.core.batch_rl_algorithm_modenv import BatchRLAlgorithmModEnv
from rlkit.core.offline_rl_algorithm import BatchOfflineRLAlgorithm
from rlkit.core.online_rl_algorithm import OnlineRLAlgorithm
from rlkit.core.trainer import Trainer
from rlkit.torch.core import np_to_pytorch_batch
OrderedDictType = MutableMapping
class TorchOnlineRLAlgorithm(OnlineRLAlgorithm):
def to(self, device):
for net in self.trainer.networks:
net.to(device)
def training_mode(self, mode):
for net in self.trainer.networks:
net.train(mode)
class TorchBatchRLAlgorithm(BatchRLAlgorithm):
def to(self, device):
for net in self.trainer.networks:
net.to(device)
def training_mode(self, mode):
for net in self.trainer.networks:
net.train(mode)
class TorchBatchRLAlgorithmModEnv(BatchRLAlgorithmModEnv):
def to(self, device):
for net in self.trainer.networks:
net.to(device)
def training_mode(self, mode):
for net in self.trainer.networks:
net.train(mode)
class TorchOfflineBatchRLAlgorithm(BatchOfflineRLAlgorithm):
def to(self, device):
for net in self.trainer.networks:
net.to(device)
def training_mode(self, mode):
for net in self.trainer.networks:
net.train(mode)
class TorchTrainer(Trainer, metaclass=abc.ABCMeta):
def __init__(self):
self._num_train_steps = 0
def train(self, np_batch):
self._num_train_steps += 1
batch = np_to_pytorch_batch(np_batch)
self.train_from_torch(batch)
def get_diagnostics(self):
return OrderedDict([
('num train calls', self._num_train_steps),
])
@abc.abstractmethod
def train_from_torch(self, batch):
pass
@property
@abc.abstractmethod
def networks(self) -> Iterable[nn.Module]:
pass
class JointTrainer(Trainer):
"""
Combine multiple trainers.
Usage:
```
trainer1 = ...
trainer2 = ...
trainers = OrderedDict([
('sac', sac_trainer),
('vae', vae_trainer),
])
joint_trainer = JointTrainer
algorithm = RLAlgorithm(trainer=joint_trainer, ...)
algorithm.train()
```
And then in the logs, the output will be of the fomr:
```
trainer/sac/...
trainer/vae/...
```
"""
def __init__(self, trainers: OrderedDictType[str, TorchTrainer]):
super().__init__()
if len(trainers) == 0:
raise ValueError("Need at least one trainer")
self._trainers = trainers
def train(self, np_batch):
for trainer in self._trainers.values():
trainer.train(np_batch)
@property
def networks(self):
for trainer in self._trainers.values():
for net in trainer.networks:
yield net
def end_epoch(self, epoch):
for trainer in self._trainers.values():
trainer.end_epoch(epoch)
def get_snapshot(self):
snapshot = {}
for trainer_name, trainer in self._trainers.items():
for k, v in trainer.get_snapshot().items():
if trainer_name:
new_k = '{}/{}'.format(trainer_name, k)
snapshot[new_k] = v
else:
snapshot[k] = v
return snapshot
def get_diagnostics(self):
stats = {}
for trainer_name, trainer in self._trainers.items():
for k, v in trainer.get_diagnostics().items():
if trainer_name:
new_k = '{}/{}'.format(trainer_name, k)
stats[new_k] = v
else:
stats[k] = v
return stats
|
import os
from dotenv import load_dotenv, find_dotenv
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse
import spacy
import uvicorn
from app.models import AzureSearchDocumentsRequest, AzureSearchDocumentsResponse
load_dotenv(find_dotenv())
prefix = os.environ.get("CLUSTER_ROUTE_PREFIX")
if not prefix:
prefix = ""
prefix = prefix.rstrip("/")
app = FastAPI(
title="{{cookiecutter.project_name}}",
version="1.0",
description="{{cookiecutter.project_short_description}}",
openapi_prefix=prefix
)
nlp = spacy.load('en_core_web_sm')
def extract_from_text(text: str):
"""Extract Spacy Named Entities from raw text"""
entities = []
for ent in nlp(text).ents:
match = {
"text": ent.text,
"label": ent.label_,
"start": ent.start_char,
"end": ent.end_char,
}
entities.append(match)
return entities
@app.get('/', include_in_schema=False)
def docs_redirect():
return RedirectResponse(f'{prefix}/docs')
@app.post(
"/spacy_entities",
response_model=AzureSearchDocumentsResponse,
tags=["NER", "Azure Search"],
)
async def extract_for_azure_search(body: AzureSearchDocumentsRequest):
"""Extract Named Entities from a batch of Azure Search Document Records.
This route can be used directly as a Cognitive Skill in Azure Search
For Documentation on integration with Azure Search, see here:
https://docs.microsoft.com/en-us/azure/search/cognitive-search-custom-skill-interface"""
res = []
for val in body.values:
ents = set([e["text"] for e in extract_from_text(val.data.text)])
ents = sorted(list(ents), key=lambda s: s.lower())
res.append(
{
"recordId": val.recordId,
"data": {
"entities": ents
}
}
)
return {
"values": res
}
|
from litex.soc.cores.cpu.ibex.core import Ibex
|
import heapq
import time
import uuid
import asyncio
class Timer:
def __init__(self):
self.timerList = list()
self.d = dict()
# ratio:间隔,runSize:次数
def addTimer(self, func, args: list, ratio=1, runSize=-1):
if ratio == 0:
raise
while (uid := uuid.uuid4()) in self.d:
pass
thisTime = time.time()
self.d[uid] = [thisTime + ratio, func, ratio, runSize, [uid] + args]
heapq.heappush(self.timerList, self.d[uid])
def delTimer(self, id):
for i in range(0, len(self.timerList)):
if self.timerList[i][4] == id:
del self.timerList[i]
del self.d[id]
return True
return False
def getTimeOut(self):
thisTime = time.time()
re = []
while len(self.timerList) > 0 and self.timerList[0][0] < thisTime:
timer = heapq.heappop(self.timerList)
re.append([timer[1], timer[4]])
if timer[3] != -1:
timer[3] -= 1
if timer[3] != 0:
timer[0] += timer[2]
heapq.heappush(self.timerList, timer)
else:
del self.d[timer[4]]
return re
async def timerLoop(self):
loop = asyncio.get_event_loop()
while True:
thisTime = time.time()
wakeList = self.getTimeOut()
for i in wakeList:
asyncio.run_coroutine_threadsafe(i[0](*i[1]), loop)
await asyncio.sleep(0.01 - (time.time() - thisTime))
|
import numpy as np
import csv
# import matplotlib.pyplot as plt
def get_gt_infos(cfg, dataset):
'''
:param dataset: dataset object
:param cfg: object containing model config information
:return: gt_infos--containing gt boxes that have labels corresponding to the classes of interest, as well as the
labels themselves
'''
gt_infos = []
dataset_infos = []
dataset_name = cfg.DATA_CONFIG.DATASET
if dataset_name == 'CadcDataset':
dataset_infos = dataset.cadc_infos
elif dataset_name == 'KittiDataset':
dataset_infos = dataset.kitti_infos
elif dataset_name == 'WaymoDataset':
dataset_infos = dataset.infos
# print("dataset_infos: {}".format(dataset_infos))
for info in dataset_infos:
box3d_lidar = np.array(info['annos']['gt_boxes_lidar'])
labels = np.array(info['annos']['name'])
# print("info['annos']: ".format(info['annos']))
interested = []
for i in range(len(labels)):
label = labels[i]
if label in cfg.CLASS_NAMES:
interested.append(i)
interested = np.array(interested)
# print("len(box3d_lidar): {}".format(len(box3d_lidar)))
# print("len(labels): {}".format(len(labels)))
# print("len(interested): {}".format(len(interested)))
# print("type(interested): {}".format(type(interested)))
# TODO: handle the case where len(interested) == 0
if (len(interested) == 0):
gt_info = {
'boxes': [],
'labels': [],
}
else:
# box3d_lidar[:,2] -= box3d_lidar[:,5] / 2
gt_info = {
'boxes': box3d_lidar[interested],
'labels': info['annos']['name'][interested],
}
gt_infos.append(gt_info)
return gt_infos
def list_selection(input_list, selections):
new_list = []
for ind in selections:
new_list.append(input_list[ind])
return new_list
# def write_to_csv(file_name, field_name, data_1, data_2, data_3, data_4):
# with open(file_name, 'w', newline='') as csvfile:
# writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=field_name)
# name1 = field_name[0]
# name2 = field_name[1]
# name3 = field_name[2]
# name4 = field_name[3]
# writer.writeheader()
# for i in range(len(data_1)):
# writer.writerow({name1: data_1[i], name2: data_2[i], name3: data_3[i], name4: data_4[i]})
def write_to_csv(file_name, field_name, data_list):
with open(file_name, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=field_name)
writer.writeheader()
for i in range(len(data_list[0])):
data_dict = {}
for cnt, name in enumerate(field_name):
data_dict[name] = data_list[cnt][i]
writer.writerow(data_dict)
def write_attr_to_csv(file_name, grad, box_vertices):
with open(file_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
if len(grad.shape)==3 and grad.shape[2]==64:
pos_grad = np.sum((grad > 0) * grad, axis=2)
neg_grad = np.sum((grad > 0) * grad, axis=2)
for row in pos_grad:
writer.writerow(row)
for vert in box_vertices:
writer.writerow(vert)
for row in neg_grad:
writer.writerow(row)
else:
for row in grad:
writer.writerow(row)
for vert in box_vertices:
writer.writerow(vert)
if __name__ == '__main__':
pass
|
from .color import Color
import random
import time
class Animation:
def on_listen(self, provider):
provider.clear_all()
groups = int(provider.run_params.num_leds / 3)
while provider.run_params.curr_state == "ON_LISTEN":
for i in range(0, 3):
for g in range(0, groups):
if provider.run_params.curr_state != "ON_LISTEN":
break
color = self.remap_color(provider.run_params.animation_color.listen, provider.run_params.max_brightness)
provider.set_color(g * 3 + i, color)
provider.refresh()
self.delay_on_state(80, "ON_LISTEN", provider)
provider.clear_all()
self.delay_on_state(80, "ON_LISTEN", provider)
provider.clear_all()
def delay_on_state(self, ms, state, provider):
for i in range(0, ms):
if provider.run_params.curr_state != state:
break
time.sleep(0.001)
def remap_color(self, color, brightness):
r = int(color.r * brightness / 255);
g = int(color.g * brightness / 255);
b = int(color.b * brightness / 255);
return Color(r, g, b);
def on_speak(self, provider):
curr_bri = 0;
provider.clear_all()
step = int(provider.run_params.max_brightness / 20)
while provider.run_params.curr_state == "ON_SPEAK":
for curr_bri in range(0, provider.run_params.max_brightness, step):
for j in range(0, provider.run_params.num_leds):
if provider.run_params.curr_state != "ON_SPEAK":
break
provider.set_color(j, self.remap_color(provider.run_params.animation_color.speak, curr_bri))
provider.refresh()
self.delay_on_state(20, "ON_SPEAK", provider)
curr_bri = provider.run_params.max_brightness
for curr_bri in range(provider.run_params.max_brightness, 0, -step):
for j in range(0, provider.run_params.num_leds):
if provider.run_params.curr_state != "ON_SPEAK":
break
provider.set_color(j, self.remap_color(provider.run_params.animation_color.speak, curr_bri))
provider.refresh()
self.delay_on_state(20, "ON_SPEAK", provider)
provider.clear_all()
provider.refresh()
self.delay_on_state(200, "ON_SPEAK", provider)
provider.clear_all()
def on_idle(self, provider):
curr_bri = 0;
provider.clear_all()
step = int(provider.run_params.max_brightness / 20)
while provider.run_params.curr_state == "ON_IDLE":
self.delay_on_state(2000, "ON_IDLE", provider)
provider.clear_all()
led = random.randint(0, provider.run_params.num_leds - 1)
for curr_bri in range(0, provider.run_params.max_brightness, step):
if provider.run_params.curr_state != "ON_IDLE":
break
provider.set_color(led, self.remap_color(provider.run_params.animation_color.idle, curr_bri))
provider.refresh()
self.delay_on_state(100, "ON_IDLE", provider)
curr_bri = provider.run_params.max_brightness
for curr_bri in range(provider.run_params.max_brightness, 0, -step):
if provider.run_params.curr_state != "ON_IDLE":
break
provider.set_color(led, self.remap_color(provider.run_params.animation_color.idle, curr_bri))
provider.refresh()
self.delay_on_state(100, "ON_IDLE", provider)
provider.set_color(led, Color(0, 0, 0))
provider.refresh()
self.delay_on_state(3000, "ON_IDLE", provider)
provider.clear_all()
|
import json
import re
import os
import time
import pygame
from . import logic
from random import randrange
from settings import *
class Menu:
def __init__(self, game):
"""
Class which represents the menu.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
self.game = game
self.runDisplay = True
self.pointerRect = pygame.Rect(0, 0, 20, 20)
self.offset = -100
self.storekeeperImg = pygame.transform.scale(STOREKEEPER_IMG, (70, 70))
def drawPointer(self):
"""
Method that draws the pointer on the display.
"""
self.game.display.blit(self.storekeeperImg, (self.pointerRect.x - 200,
self.pointerRect.y - 30))
def blitScreen(self):
"""
Method that updates the screen, resets the keys and blits the display on
the window.
"""
self.game.window.blit(self.game.display, (0, 0))
pygame.display.update()
self.game.resetKeys()
class MainMenu(Menu):
def __init__(self, game):
Menu.__init__(self, game)
"""
Class which represents the main menu, inheriting from the Menu class.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
self.state = "Start"
self.logoMenuX, self.logoMenuY = midWidth, midHeight - 220
self.startMenuX, self.startMenuY = midWidth, midHeight - 40
self.moduleMenuX, self.moduleMenuY = midWidth, midHeight + 30
self.instructionsMenuX, self.instructionsMenuY = midWidth, midHeight + 100
self.rankingMenuX, self.rankingMenuY = midWidth, midHeight + 170
self.creditsMenuX, self.creditsMenuY = midWidth, midHeight + 240
self.quitMenuX, self.quitMenuY = midWidth, midHeight + 310
self.pointerRect.midtop = (self.startMenuX + self.offset, self.startMenuY)
def displayMenu(self):
"""
Method that displays the menu. It prints 7 buttons thanks to the drawText() method.
It also draws the pointer and blits the screen every single frame.
"""
self.runDisplay = True
self.resetPointer()
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('SOKOBAN', 130, self.logoMenuX, self.logoMenuY,
WHITE, self.game.fontTitle)
self.game.drawText('Start Game', 70, self.startMenuX, self.startMenuY,
WHITE, self.game.fontName)
self.game.drawText('Load Game', 70, self.moduleMenuX, self.moduleMenuY,
WHITE, self.game.fontName)
self.game.drawText('Instructions', 70, self.instructionsMenuX, self.instructionsMenuY,
WHITE, self.game.fontName)
self.game.drawText('Ranking', 70, self.rankingMenuX, self.rankingMenuY,
WHITE, self.game.fontName)
self.game.drawText('Credits', 70, self.creditsMenuX, self.creditsMenuY,
WHITE, self.game.fontName)
self.game.drawText('Quit', 70, self.quitMenuX, self.quitMenuY,
WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.startMenuX + self.offset, self.startMenuY)
self.state = 'Start'
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an
end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
if self.state == 'Start':
self.pointerRect.midtop = (self.moduleMenuX + self.offset,
self.moduleMenuY)
self.state = 'Level'
elif self.state == 'Level':
self.pointerRect.midtop = (self.instructionsMenuX + self.offset,
self.instructionsMenuY)
self.state = 'Instructions'
elif self.state == 'Instructions':
self.pointerRect.midtop = (self.rankingMenuX + self.offset,
self.rankingMenuY)
self.state = 'Ranking'
elif self.state == 'Ranking':
self.pointerRect.midtop = (self.creditsMenuX + self.offset,
self.creditsMenuY)
self.state = 'Credits'
elif self.state == 'Credits':
self.pointerRect.midtop = (self.quitMenuX + self.offset,
self.quitMenuY)
self.state = 'Quit'
elif self.state == 'Quit':
self.pointerRect.midtop = (self.startMenuX + self.offset,
self.startMenuY)
self.state = 'Start'
elif self.game.UP_KEY or self.game.W_KEY:
if self.state == 'Start':
self.pointerRect.midtop = (self.quitMenuX + self.offset,
self.quitMenuY)
self.state = 'Quit'
elif self.state == 'Quit':
self.pointerRect.midtop = (self.creditsMenuX + self.offset,
self.creditsMenuY)
self.state = 'Credits'
elif self.state == 'Credits':
self.pointerRect.midtop = (self.rankingMenuX + self.offset,
self.rankingMenuY)
self.state = 'Ranking'
elif self.state == 'Ranking':
self.pointerRect.midtop = (self.instructionsMenuX + self.offset,
self.instructionsMenuY)
self.state = 'Instructions'
elif self.state == 'Instructions':
self.pointerRect.midtop = (self.moduleMenuX + self.offset,
self.moduleMenuY)
self.state = 'Level'
elif self.state == 'Level':
self.pointerRect.midtop = (self.startMenuX + self.offset,
self.startMenuY)
self.state = 'Start'
def checkInput(self):
"""
Method that handles changing the currently displayed menu depending on
whether player has given its nickname.
"""
self.movePointer()
if self.game.START_KEY:
if self.state == 'Start' and len(self.game.playerName) == 0:
self.game.previousMenu = 'Start'
self.game.currentMenu = self.game.inputMenu
elif self.state == 'Start' and len(self.game.playerName) > 0:
self.game.START_KEY = False
self.game.currentMenu = self.game.moduleMenu
elif self.state == 'Level' and len(self.game.playerName) == 0:
self.game.previousMenu = 'Level'
self.game.currentMenu = self.game.inputMenu
elif self.state == 'Level':
self.game.START_KEY = False
self.game.currentMenu = self.game.loadSaveMenu
elif self.state == 'Instructions':
self.game.currentMenu = self.game.instructionsMenu
elif self.state == 'Ranking':
self.game.currentMenu = self.game.rankMenu
elif self.state == 'Credits':
self.game.currentMenu = self.game.creditsMenu
elif self.state == 'Quit':
self.game.running = False
self.runDisplay = False
class ModuleMenu(Menu):
def __init__(self, game):
"""
Class which represents the module menu, inheriting from the Menu class.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.firstModuleX, self.firstModuleY = midWidth, midHeight
self.secondModuleX, self.secondModuleY = midWidth, midHeight + 100
self.thirdModuleX, self.thirdModuleY = midWidth, midHeight + 200
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'One'
def displayMenu(self):
"""
Method that displays the menu. It prints 4 buttons thanks to the drawText() method.
It also draws the pointer and blits the screen every single frame.
"""
self.runDisplay = True
self.resetPointer()
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('Choose module: ', 120, midWidth, midHeight - 200,
WHITE, self.game.fontName)
self.game.drawText('Module 1', 80, self.firstModuleX, self.firstModuleY,
WHITE, self.game.fontName)
self.game.drawText('Module 2', 80, self.secondModuleX, self.secondModuleY,
WHITE, self.game.fontName)
self.game.drawText('Module 3', 80, self.thirdModuleX, self.thirdModuleY,
WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu. Supports
three module selection logic.
"""
self.movePointer()
if self.game.BACK_KEY or self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
self.runDisplay = False
if self.game.START_KEY:
if self.state == 'One':
self.game.currentMenu = self.game.diffMenu
elif self.state == 'Two':
self.runDisplay = False
self.game.logicState = True
while self.game.gameLevel <= 20 and self.game.START_KEY:
self.game.currentLevel = self.game.gameLevel
boardName = str(self.game.currentLevel) + '.txt'
logic.startTheGame(self.game.window, boardName, self.game,
self.game.gamePoints, MODULE_II)
self.game.logicState = True
elif self.state == 'Three':
self.game.currentMenu = self.game.widthHeightMenu
self.runDisplay = False
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an
end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
if self.state == 'One':
self.pointerRect.midtop = (self.secondModuleX + self.offset,
self.secondModuleY)
self.state = 'Two'
elif self.state == 'Two':
self.pointerRect.midtop = (self.thirdModuleX + self.offset,
self.thirdModuleY)
self.state = 'Three'
elif self.state == 'Three':
self.pointerRect.midtop = (self.firstModuleX + self.offset,
self.firstModuleY)
self.state = 'One'
elif self.game.UP_KEY or self.game.W_KEY:
if self.state == 'One':
self.pointerRect.midtop = (self.thirdModuleX + self.offset,
self.thirdModuleY)
self.state = 'Three'
elif self.state == 'Two':
self.pointerRect.midtop = (self.firstModuleX + self.offset,
self.firstModuleY)
self.state = 'One'
elif self.state == 'Three':
self.pointerRect.midtop = (self.secondModuleX + self.offset,
self.secondModuleY)
self.state = 'Two'
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'One'
class CreditsMenu(Menu):
def __init__(self, game):
"""
Class which represents the credits menu, inheriting from the Menu class.
Shows the info about the game developers.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.creditsTitleX, self.creditsTitleY = midWidth, midHeight - 280
self.firstAuthorX, self.firstAuthorY = midWidth, midHeight - 150
self.secondAuthorX, self.secondAuthorY = midWidth, midHeight - 70
self.partOneX, self.partOneY = midWidth, midHeight + 60
self.partTwoX, self.partTwoY = midWidth, midHeight + 140
self.partThreeX, self.partThreeY = midWidth, midHeight + 220
self.copyrightX, self.copyrightY = WIDTH - 175, HEIGHT - 15
def displayMenu(self):
"""
Method that displays the menu. It prints 7 buttons thanks to the
drawText() method. It also blits the screen every single frame.
"""
self.runDisplay = True
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('THE GAME HAS BEEN WRITTEN BY', 85, self.creditsTitleX,
self.creditsTitleY, WHITE, self.game.fontName)
self.game.drawText('PIOTR BATOR', 70, self.firstAuthorX, self.firstAuthorY,
WHITE, self.game.fontName)
self.game.drawText('GABRIEL BRZOSKWINIA', 70, self.secondAuthorX,
self.secondAuthorY, WHITE, self.game.fontName)
self.game.drawText('AS A PART OF', 60, self.partOneX, self.partOneY,
WHITE, self.game.fontName)
self.game.drawText('THE MOTOROLA SCIENCE CUP', 60, self.partTwoX,
self.partTwoY, RED, self.game.fontName)
self.game.drawText('COMPETITION TASKS', 60, self.partThreeX,
self.partThreeY, WHITE, self.game.fontName)
self.game.drawText('2021 © ALL RIGHTS RESERVED', 30, self.copyrightX,
self.copyrightY, WHITE, self.game.fontName)
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
if self.game.BACK_KEY:
self.game.currentMenu = self.game.mainMenu
if self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
if self.game.START_KEY:
self.game.currentMenu = self.game.mainMenu
self.runDisplay = False
class InstructionsMenu(Menu):
def __init__(self, game):
"""
Class which represents the instructions menu, inheriting from the Menu class.
It is an interface that presents the rules of the game and controls to the player.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.instructionsTextX, self.instructionsTextY = midWidth, midHeight - 280
self.image = pygame.image.load('./src/img/controls.png')
self.image = pygame.transform.scale(self.image, (500, 350))
def displayMenu(self):
"""
Method that displays the menu. It prints 3 buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.display.blit(self.image, (self.instructionsTextX - 250,
self.instructionsTextY + 150))
self.game.drawText('USE', 55, self.instructionsTextX - 450,
self.instructionsTextY, WHITE, self.game.fontName)
self.game.drawText('WSAD', 55, self.instructionsTextX - 340,
self.instructionsTextY, RED, self.game.fontName)
self.game.drawText('IN ORDER TO MOVE YOUR STOREKEEPER', 55,
self.instructionsTextX + 150, self.instructionsTextY, WHITE, self.game.fontName)
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
if self.game.BACK_KEY:
self.game.currentMenu = self.game.mainMenu
if self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
if self.game.START_KEY:
self.game.currentMenu = self.game.legendMenu
self.runDisplay = False
class LegendMenu(Menu):
def __init__(self, game):
"""
Class which represents the legend menu, inheriting from the Menu class.
The rules of the game are displayed here.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.legendTextX, self.legendTextY = midWidth, midHeight - 280
def displayMenu(self):
"""
Method that displays the menu. It prints 12 buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('RULES', 100, self.legendTextX, self.legendTextY,
WHITE, self.game.fontName)
self.game.drawText('THE GOAL OF THIS GAME IS TO MOVE', 45,
self.legendTextX, self.legendTextY + 150, WHITE, self.game.fontName)
self.game.drawText('AND CORRECTLY POSITION THE', 45, self.legendTextX - 180,
self.legendTextY + 220, WHITE, self.game.fontName)
self.game.drawText('BOXES', 45, self.legendTextX + 150,
self.legendTextY + 220, RED, self.game.fontName)
self.game.drawText('IN A WAREHOUSE.', 45, self.legendTextX + 365,
self.legendTextY + 220, WHITE, self.game.fontName)
self.game.drawText('YOU WILL PLAY AS THE', 45, self.legendTextX - 300,
self.legendTextY + 290, WHITE, self.game.fontName)
self.game.drawText('WAREHOUSE KEEPER', 45, self.legendTextX + 90,
self.legendTextY + 290, RED, self.game.fontName)
self.game.drawText('AND TRY TO COPE', 45, self.legendTextX + 430,
self.legendTextY + 290, WHITE, self.game.fontName)
self.game.drawText('WITH THE CHALLENGE, FACING', 45, self.legendTextX - 300,
self.legendTextY + 360, WHITE, self.game.fontName)
self.game.drawText('60 MAPS', 45, self.legendTextX + 50, self.legendTextY + 360,
RED, self.game.fontName)
self.game.drawText('OF VARYING DIFFICULTY.', 45, self.legendTextX + 350,
self.legendTextY + 360, WHITE, self.game.fontName)
self.game.drawText('WE WISH YOU GOOD LUCK!', 45, self.legendTextX,
self.legendTextY + 500, WHITE, self.game.fontName)
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
if self.game.BACK_KEY:
self.game.currentMenu = self.game.mainMenu
if self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
if self.game.START_KEY:
self.game.currentMenu = self.game.mainMenu
self.runDisplay = False
class DiffMenu(Menu):
def __init__(self, game):
"""
Class which represents the diffMenu, inheriting from the Menu class.
Player can choose game difficulty here.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.diffTitleX, self.diffTitleY = midWidth, midHeight - 200
self.easyX, self.easyY = midWidth, midHeight
self.mediumX, self.mediumY = midWidth, midHeight + 100
self.hardX, self.hardY = midWidth, midHeight + 200
self.pointerRect.midtop = (self.easyX + self.offset, self.easyY)
self.state = 'Easy'
self.moved = 'No'
def displayMenu(self):
"""
Method that displays the menu. It prints 4 buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
if self.moved == 'No':
self.resetPointer()
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('SELECT YOUR DIFFICULTY', 85, self.diffTitleX, self.diffTitleY, WHITE, self.game.fontName)
self.game.drawText('EASY', 80, self.easyX, self.easyY, WHITE, self.game.fontName)
self.game.drawText('MEDIUM', 80, self.mediumX, self.mediumY, WHITE, self.game.fontName)
self.game.drawText('HARD', 80, self.hardX, self.hardY, WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
self.movePointer()
if self.game.BACK_KEY:
self.game.currentMenu = self.game.mainMenu
self.moved = 'No'
if self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
self.moved = 'No'
if self.game.START_KEY:
self.game.currentMenu = self.game.mainMenu
self.moved = 'No'
self.runDisplay = False
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an end event handler.
Depending on the chosen difficulty, the player draws a map from three fields.
"""
if self.game.START_KEY:
self.moved = 'No'
if self.state == 'Easy':
self.runDisplay = False
self.game.logicState = True
self.game.currentLevel = randrange(1, 20)
boardName = str(self.game.currentLevel) + '.txt'
logic.startTheGame(self.game.window, boardName, self.game,
self.game.gamePoints, MODULE_I)
elif self.state == 'Medium':
self.runDisplay = False
self.game.logicState = True
self.game.currentLevel = randrange(21, 40)
boardName = str(self.game.currentLevel) + '.txt'
logic.startTheGame(self.game.window, boardName, self.game,
self.game.gamePoints, MODULE_I)
elif self.state == 'Hard':
self.runDisplay = False
self.game.logicState = True
self.game.currentLevel = randrange(41, 60)
boardName = str(self.game.currentLevel) + '.txt'
logic.startTheGame(self.game.window, boardName, self.game,
self.game.gamePoints, MODULE_I)
if self.game.DOWN_KEY or self.game.S_KEY:
self.moved = 'Yes'
if self.state == 'Easy':
self.pointerRect.midtop = (self.mediumX + self.offset, self.mediumY)
self.state = 'Medium'
elif self.state == 'Medium':
self.pointerRect.midtop = (self.hardX + self.offset, self.hardY)
self.state = 'Hard'
elif self.state == 'Hard':
self.pointerRect.midtop = (self.easyX + self.offset, self.easyY)
self.state = 'Easy'
elif self.game.UP_KEY or self.game.W_KEY:
self.moved = 'Yes'
if self.state == 'Easy':
self.pointerRect.midtop = (self.hardX + self.offset, self.hardY)
self.state = 'Hard'
elif self.state == 'Medium':
self.pointerRect.midtop = (self.easyX + self.offset, self.easyY)
self.state = 'Easy'
elif self.state == 'Hard':
self.pointerRect.midtop = (self.mediumX + self.offset, self.mediumY)
self.state = 'Medium'
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.easyX + self.offset, self.easyY)
self.state = 'Easy'
class InputName(Menu):
def __init__(self, game):
"""
This is a class that handles user input. It gives its name, which is
necessary for many functions in the game to work.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.inputNameX, self.inputNameY = midWidth, midHeight - 280
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
if len(self.game.playerName) > 0 and self.game.START_KEY:
self.runDisplay = False
self.game.START_KEY = False
self.game.running = True
if self.game.previousMenu == 'Start':
self.game.currentMenu = self.game.moduleMenu
elif self.game.previousMenu == 'Level':
self.game.currentMenu = self.game.loadSaveMenu
self.game.previousMenu = ''
elif self.game.ESC_PRESSED or self.game.BACK_KEY:
self.runDisplay = False
self.game.playerName = ''
self.game.running = True
self.game.currentMenu = self.game.mainMenu
def inputName(self):
"""
Function for handling player writing his nickname.
"""
self.game.running = False
event = pygame.event.poll()
keys = pygame.key.get_pressed()
if event.type == pygame.KEYDOWN:
key = pygame.key.name(event.key)
if len(key) == 1:
if (keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT]) and len(self.game.playerName) < 15:
self.game.playerName += key.upper()
elif len(self.game.playerName) < 15:
self.game.playerName += key
elif key == 'backspace':
self.game.playerName = self.game.playerName[:len(self.game.playerName) - 1]
elif key == 'return':
self.game.START_KEY = True
elif key == 'escape':
self.game.ESC_PRESSED = True
elif event.type == pygame.QUIT:
self.runDisplay = False
self.game.running = False
self.game.drawText(self.game.playerName, 60, self.inputNameX, self.inputNameY + 350, RED,
self.game.fontName)
self.game.drawText('Chars used: ' + str(len(self.game.playerName)), 30,
self.inputNameX, self.inputNameY + 600, WHITE, self.game.fontName)
def displayMenu(self):
"""
Method that displays the menu. It prints 2 buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
while self.runDisplay:
self.game.display.fill(BLACK)
self.game.drawText('TYPE IN YOUR NICKNAME [15]', 95, self.inputNameX, self.inputNameY + 50, WHITE,
self.game.fontName)
self.game.drawText('AND PRESS ENTER TO CONFIRM', 70, self.inputNameX, self.inputNameY + 150, WHITE,
self.game.fontName)
self.inputName()
self.checkInput()
self.blitScreen()
class RankMenu(Menu):
def __init__(self, game):
"""
Class which represents the rank menu, inheriting from the Menu class.
The results are read from the file and a ranking of the players is being created.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.headerX = midWidth
self.headerY = midHeight - 200
self.itemY = midHeight - 100
def displayMenu(self):
"""
Method that displays the menu. It prints buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
while self.runDisplay:
self.game.checkEvents()
if self.game.START_KEY or self.game.BACK_KEY or self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
self.runDisplay = False
self.game.display.fill(BLACK)
self.game.drawText('RANKING', 90, self.headerX, self.headerY, WHITE, self.game.fontName)
def getScore(table):
return table.get('userScore')
with open('scoreFile.txt', 'r') as scoreFile:
table = [json.loads(line) for line in scoreFile]
counter = 1
if len(table) == 0:
self.game.drawText('EMPTY RANKING', 100, self.headerX, self.itemY + 100, RED, self.game.fontName)
else:
table.sort(key=getScore, reverse=True)
for row in table:
name = table[counter - 1]['userNameVar']
points = table[counter - 1]['userScore']
self.game.drawText('NAME', 60, self.headerX - 300, self.headerY + 100, WHITE, self.game.fontName)
self.game.drawText('POINTS', 60, self.headerX + 300, self.headerY + 100, WHITE, self.game.fontName)
if counter <= 5:
self.game.drawText(str(counter) + '. ' + str(name), 50, self.headerX - 300, self.itemY + (counter * 60), WHITE, self.game.fontName)
self.game.drawText(str(points), 50, self.headerX + 300, self.itemY + (counter * 60), RED, self.game.fontName)
counter += 1
self.blitScreen()
scoreFile.close()
class SaveGameMenu(Menu):
def __init__(self, game):
"""
Sub menu for game map and score saving to shelf file format.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.firstModuleX, self.firstModuleY = midWidth, midHeight
self.secondModuleX, self.secondModuleY = midWidth, midHeight + 100
self.thirdModuleX, self.thirdModuleY = midWidth, midHeight + 200
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'Yes'
def displayMenu(self):
"""
Method that displays the menu. It prints buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
self.resetPointer()
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
if self.game.flagVar == MODULE_I:
self.game.drawText('DO YOU WANT TO QUIT ?', 65, midWidth, midHeight - 300,
WHITE, self.game.fontName)
else:
self.game.drawText('DO YOU WANT TO QUIT AND SAVE YOUR SCORE?', 65, midWidth, midHeight - 300,
WHITE, self.game.fontName)
self.game.drawText('YES', 60, self.firstModuleX, self.firstModuleY,
WHITE, self.game.fontName)
self.game.drawText('NO', 60, self.secondModuleX, self.secondModuleY,
WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
self.movePointer()
if self.game.START_KEY:
if self.state == 'Yes':
self.runDisplay = False
self.game.START_KEY = False
self.game.currentMenu = self.game.mainMenu
if self.game.currentPlayerState['flag'] in [MODULE_II, MODULE_III, RESTORE]:
currLvl = self.game.currentLevel
logic.saveGame(self.game.currentPlayerState['width'],
self.game.currentPlayerState['height'],
self.game.currentPlayerState['sprites'],
self.game.currentPlayerState['time'],
self.game.playerName, currLvl, self.game.gamePoints,
self.game.currentPlayerState['flag'])
if self.game.gameLevel > 1:
self.game.gameLevel = 1
self.game.gamePoints = 0
if self.state == 'No':
self.runDisplay = False
self.game.currentMenu = self.game.mainMenu
if self.game.ESC_PRESSED:
self.runDisplay = False
self.game.logicState = True
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
if self.state == 'Yes':
self.pointerRect.midtop = (self.secondModuleX + self.offset, self.secondModuleY)
self.state = 'No'
elif self.state == 'No':
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'Yes'
elif self.game.UP_KEY or self.game.W_KEY:
if self.state == 'Yes':
self.pointerRect.midtop = (self.secondModuleX + self.offset, self.secondModuleY)
self.state = 'No'
elif self.state == 'No':
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'Yes'
def resetPointer(self):
"""
Utility method for reset pointer to default position after action.
"""
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'Yes'
class WidthHeightMenu(Menu):
def __init__(self, game):
"""
Sub menu for passing the width and height to 3rd module map-creator.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.textInfoX, self.textInfoY = midWidth, midHeight - 250
self.widthX, self.widthY = midWidth, midHeight - 50
self.heightX, self.heightY = midWidth, midHeight + 100
self.nameX, self.nameY = midWidth - 300, midHeight + 220
self.passedWidth = ''
self.passedHeight = ''
self.passiveColor = GRAY
self.activeColor = LIGHTSKYBLUE
self.inputWidthRect = pygame.Rect(self.widthX + 100, self.widthY - 50, 100, 100)
self.inputHeightRect = pygame.Rect(self.heightX + 100, self.heightY - 50, 100, 100)
self.inputNameRect = pygame.Rect(self.nameX + 100, self.nameY - 40, 450, 80)
self.buttonWActive, self.buttonHActive, self.buttonNActive = False, False, False
self.numberKeys = [pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4,
pygame.K_5, pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9]
self.colorW = self.passiveColor
self.colorH = self.passiveColor
self.colorN = self.passiveColor
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
if self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
self.game.running = True
self.runDisplay = False
if self.game.START_KEY:
if 8 <= int(self.passedWidth) <= 30 and 8 <= int(self.passedHeight) <= 20 and 0 < len(self.game.passedMapName) <= 15:
self.runDisplay = False
self.game.running = True
self.game.logicState = True
logic.createMap(self.game.window, int(self.passedWidth),
int(self.passedHeight), self.game)
self.passedWidth = ''
self.passedHeight = ''
def inputHandle(self):
"""
Method for handling input new created map width and height.
"""
self.game.running = False
event = pygame.event.poll()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.inputWidthRect.collidepoint(event.pos):
self.buttonWActive = True
self.colorW = self.activeColor
elif not self.inputWidthRect.collidepoint(event.pos):
self.buttonWActive = False
self.colorW = self.passiveColor
if self.inputHeightRect.collidepoint(event.pos):
self.buttonHActive = True
self.colorH = self.activeColor
elif not self.inputHeightRect.collidepoint(event.pos):
self.buttonHActive = False
self.colorH = self.passiveColor
if self.inputNameRect.collidepoint(event.pos):
self.buttonNActive = True
self.colorN = self.activeColor
elif not self.inputNameRect.collidepoint(event.pos):
self.buttonNActive = False
self.colorN = self.passiveColor
if event.type == pygame.KEYDOWN:
key = pygame.key.name(event.key)
if self.buttonWActive:
if key == 'backspace':
self.passedWidth = self.passedWidth[:-1]
elif key == 'return':
if len(self.passedHeight) > 0 and len(self.passedWidth) > 0:
self.game.START_KEY = True
else:
if event.key in self.numberKeys and len(self.passedWidth) < 2:
self.passedWidth += event.unicode
elif self.buttonHActive:
if key == 'backspace':
self.passedHeight = self.passedHeight[:-1]
elif key == 'return':
if len(self.passedHeight) > 0 and len(self.passedWidth) > 0:
self.game.START_KEY = True
else:
if event.key in self.numberKeys and len(self.passedHeight) < 2:
self.passedHeight += event.unicode
elif self.buttonNActive:
if key == 'backspace':
self.game.passedMapName = self.game.passedMapName[:-1]
elif key == 'return':
self.game.START_KEY = True
else:
if len(self.game.passedMapName) < 15:
self.game.passedMapName += event.unicode
elif key == 'return':
if len(self.passedHeight) > 0 and len(self.passedWidth) > 0:
self.game.START_KEY = True
elif key == 'escape':
self.game.ESC_PRESSED = True
elif event.type == pygame.QUIT:
self.runDisplay = False
self.game.running = False
pygame.draw.rect(self.game.display, self.colorW, self.inputWidthRect, 2)
pygame.draw.rect(self.game.display, self.colorH, self.inputHeightRect, 2)
pygame.draw.rect(self.game.display, self.colorN, self.inputNameRect, 2)
self.game.drawText(self.passedWidth, 50, self.widthX + 150, self.widthY,
WHITE, self.game.fontName)
self.game.drawText(self.passedHeight, 50, self.heightX + 150, self.heightY,
WHITE, self.game.fontName)
self.game.drawText(self.game.passedMapName, 40, self.nameX + 325, self.nameY,
WHITE, self.game.fontName)
def displayMenu(self):
"""
Method that displays the menu. It prints buttons thanks to the drawText() method.
It also blits the screen every single frame.
"""
self.runDisplay = True
while self.runDisplay:
self.game.display.fill(BLACK)
self.game.drawText('ENTER YOUR MAP DIMENSIONS', 65, self.textInfoX,
self.textInfoY, WHITE, self.game.fontName)
self.game.drawText('MIN: 8 x 8 MAX: 30 x 20 [press enter]', 35, self.textInfoX, self.textInfoY + 50,
RED, self.game.fontName)
self.game.drawText('WIDTH: ', 60, self.widthX, self.widthY, WHITE,
self.game.fontName)
self.game.drawText('HEIGHT: ', 60, self.heightX, self.heightY,
WHITE, self.game.fontName)
self.game.drawText('NAME: ', 60, self.nameX, self.nameY,
WHITE, self.game.fontName)
self.inputHandle()
self.checkInput()
self.blitScreen()
def unableToSaveMonit(self):
"""
Utility method for displaying short monit about information why map cant
be saved.
"""
self.game.display.fill(BLACK)
self.game.drawText('Created map must have at least one of each game object.',
45, midWidth, midHeight - 45, WHITE, self.game.fontName)
self.game.drawText('[Storekeeper, Box, Destination, Floor, Wall]',
45, midWidth, midHeight + 45, WHITE, self.game.fontName)
self.blitScreen()
time.sleep(2)
def boxesDestinationInvalidMonit(self):
"""
Utility method for displaying short monit about incorrect amounts of
destinations and boxes
"""
self.game.display.fill(BLACK)
self.game.drawText('Created map must have equal or more amount',
45, midWidth, midHeight - 45, WHITE, self.game.fontName)
self.game.drawText('of the Boxes than the Destinations amount.',
45, midWidth, midHeight + 45, WHITE, self.game.fontName)
self.blitScreen()
time.sleep(2)
def tooManyBoardsMonit(self):
"""
Utility method for displaying short monit if amount of player's own boards,
exceed MAX_BOARD value.
"""
self.game.display.fill(BLACK)
self.game.drawText(f'You already have {MAX_BOARDS} maps. This is limit.',
45, midWidth, midHeight - 45, WHITE, self.game.fontName)
self.game.drawText('Remove old one to save new.',
45, midWidth, midHeight + 45, WHITE, self.game.fontName)
self.blitScreen()
time.sleep(2)
class LoadMapMenu(Menu):
def __init__(self, game):
Menu.__init__(self, game)
"""
Sub menu for Module III that allows player to choose his own map.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
self.textInfoX, self.textInfoY = midWidth - 25, midHeight - 280
self.itemMapX, self.itemMapY = midWidth, midHeight - 200
self.deleteRect = pygame.Rect(midWidth + 450, midHeight + 320, 140, 50)
self.offset = -100
self.pointerRect = pygame.Rect(0, 0, 20, 20)
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + 10)
self.counter = 0
self.storekeeperImg = pygame.transform.scale(STOREKEEPER_IMG, (40, 40))
self.chosenMap = ''
self.mapArray = []
self.amount = 0
def displayMenu(self):
"""
Method that displays the menu. It also draws the pointer and blits the
screen every single frame.
"""
self.runDisplay = True
self.resetPointer()
maps = os.listdir(OWN_BOARDS_DIR)
self.cleanMaps(maps)
if len(self.mapArray) > 0:
self.chosenMap = self.mapArray[0]
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('CHOOSE MAP', 65, self.textInfoX, self.textInfoY,
WHITE, self.game.fontName)
for row in range(len(self.mapArray)):
if row < 12:
board = self.prepareMapName(self.mapArray[row])
self.game.drawText(str(board), 28, self.itemMapX, self.itemMapY + (row * 45),
WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
else:
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('YOU HAVE NOT CREATED A MAP YET', 65, midWidth, midHeight,
WHITE, self.game.fontName)
self.blitScreen()
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + 10)
self.chosenMap = ''
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
self.counter += 1
if self.counter > len(self.mapArray) - 1 or self.counter > 11:
self.counter = 0
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + (self.counter * 45))
self.chosenMap = self.mapArray[self.counter]
elif self.game.UP_KEY or self.game.W_KEY:
self.counter -= 1
if self.counter < 0:
self.counter = len(self.mapArray) - 1
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + self.counter * 45)
self.chosenMap = self.mapArray[self.counter]
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
self.movePointer()
if self.game.ESC_PRESSED or self.game.BACK_KEY:
self.runDisplay = False
self.game.currentMenu = self.game.mainMenu
self.counter = 0
self.mapArray.clear()
if self.game.START_KEY and len(self.mapArray) <= 0:
self.runDisplay = False
self.game.currentMenu = self.game.loadSaveMenu
self.mapArray.clear()
elif self.game.START_KEY and len(self.mapArray) > 0:
self.runDisplay = False
self.game.logicState = True
self.counter = 0
self.mapArray.clear()
logic.startTheGame(self.game.window, self.chosenMap, self.game,
self.game.gamePoints, MODULE_III)
def prepareMapName(self, fileName):
"""
Utility function for preparing name of saved game.
:param fileName:
Name of file which contains map.
:type fileName: str, required
:return:
Returns nice looking saved game file name.
:rtype: str
"""
mapName = fileName[:fileName.find('_')]
date = fileName[len(mapName) + 1:]
hours = date[:8]
hours = hours.replace('_', ':')
day = date[9: 19]
day = day.replace('_', '/')
result = ''.join((mapName.ljust(20, ' '), hours, ' ', day))
return result
def cleanMaps(self, maps):
"""
Utility function for select only current playing player.
:param maps:
Name of maps to search in.
:type maps: list, required
"""
for file in maps:
if re.search(rf'(.*)(_){self.game.playerName}\b(.*)', file):
self.mapArray.append(file)
class DeleteMapMenu(Menu):
def __init__(self, game):
Menu.__init__(self, game)
"""
Sub menu for Module III that allows player to delete his own map.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
self.textInfoX, self.textInfoY = midWidth, midHeight - 280
self.itemMapX, self.itemMapY = midWidth, midHeight - 180
self.offset = -100
self.pointerRect = pygame.Rect(0, 0, 20, 20)
self.storekeeperImg = pygame.transform.scale(STOREKEEPER_IMG, (40, 40))
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + 10)
self.counter = 0
self.mapArray = []
self.chosenMap = ''
def displayMenu(self):
"""
Method that displays the menu. It prints 7 buttons thanks to the drawText() method.
It also draws the pointer and blits the screen every single frame.
"""
self.runDisplay = True
self.resetPointer()
for map in os.listdir(OWN_BOARDS_DIR):
if map.find(self.game.playerName) > -1:
self.mapArray.append(map)
if len(self.mapArray) > 0:
self.chosenMap = self.mapArray[0]
while self.runDisplay:
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('DELETE YOUR MAP', 65, self.textInfoX, self.textInfoY,
WHITE, self.game.fontName)
for row in range(len(self.mapArray)):
if row < 12:
board = self.prepareSaveName(self.mapArray[row])
self.game.drawText(str(board), 28, self.itemMapX, self.itemMapY + (row * 45),
WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
else:
while self.runDisplay:
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('YOU HAVE NOT CREATED A MAP YET', 65, midWidth, midHeight,
WHITE, self.game.fontName)
self.blitScreen()
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + 10)
self.chosenMap = ''
def prepareSaveName(self, filename):
"""
Utility function for preparing player save game for nice format.
:param filename:
Name of the file which contains save.
:type filename: str, required
:return:
Nice looking save game name.
:rtype: str
"""
playerName = filename[:filename.find('_')]
hours = filename[len(playerName) + 1:]
hour = hours[:8]
date = hours[9:19]
hour = hour.replace('_', ':')
date = date.replace('_', '/')
result = ''.join((playerName, ' ', hour, ' ', date))
return result
def removeMap(self, mapID):
"""
Function for module III which allows player to delete his own map.
:param mapID:
ID of created map.
:type mapID: int, required
"""
if os.path.isfile('./src/boards/own/' + str(mapID)):
os.remove('./src/boards/own/' + mapID)
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
self.counter += 1
if self.counter > len(self.mapArray) - 1 or self.counter > 11:
self.counter = 0
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + (self.counter * 45))
self.chosenMap = self.mapArray[self.counter]
elif self.game.UP_KEY or self.game.W_KEY:
self.counter -= 1
if self.counter < 0:
self.counter = len(self.mapArray) - 1
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + self.counter * 45)
self.chosenMap = self.mapArray[self.counter]
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
self.movePointer()
if self.game.ESC_PRESSED:
self.runDisplay = False
self.counter = 0
self.game.currentMenu = self.game.mainMenu
self.mapArray.clear()
if self.game.START_KEY and len(self.mapArray) > 0:
self.runDisplay = False
self.removeMap(self.chosenMap)
self.counter = 0
self.successfullMonit()
self.game.currentMenu = self.game.mainMenu
self.mapArray.clear()
elif self.game.START_KEY and len(self.mapArray) <= 0:
self.runDisplay = False
self.game.currentMenu = self.game.loadSaveMenu
def successfullMonit(self):
"""
Short once second communicat which display after successfull map delete.
"""
self.game.display.fill(BLACK)
self.game.drawText('Map successfully deleted!', 65, midWidth, midHeight,
WHITE, self.game.fontName)
self.blitScreen()
time.sleep(1)
class LoadSaveMenu(Menu):
def __init__(self, game):
"""
Class which represents the module menu, inheriting from the Menu class.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.firstModuleX, self.firstModuleY = midWidth, midHeight
self.secondModuleX, self.secondModuleY = midWidth, midHeight + 100
self.thirdModuleX, self.thirdModuleY = midWidth, midHeight + 200
self.fourthModuleX, self.fourthModuleY = midWidth, midHeight + 300
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'One'
self.moved = 'No'
def displayMenu(self):
"""
Method that displays the menu. It prints 4 buttons thanks to the drawText() method.
It also draws the pointer and blits the screen every single frame.
"""
self.runDisplay = True
if self.moved == 'No':
self.resetPointer()
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('Load game/map from:', 120, midWidth, midHeight - 200, WHITE, self.game.fontName)
self.game.drawText('Module 2', 80, self.firstModuleX, self.firstModuleY, WHITE, self.game.fontName)
self.game.drawText('Own maps', 80, self.secondModuleX, self.secondModuleY, WHITE, self.game.fontName)
self.game.drawText('Own saves', 80, self.thirdModuleX, self.thirdModuleY, WHITE, self.game.fontName)
self.game.drawText('Del Map', 80, self.fourthModuleX, self.fourthModuleY, WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
def checkInput(self):
"""
Method that handles changing the currently displayed menu. Supports three module selection logic.
"""
self.movePointer()
if self.game.BACK_KEY or self.game.ESC_PRESSED:
self.game.currentMenu = self.game.mainMenu
self.moved = 'No'
if self.game.START_KEY:
self.moved = 'No'
if self.state == 'One':
self.game.currentMenu = self.game.resumeSavedGameMenu
self.game.previousMenu = self.state
elif self.state == 'Two':
self.game.currentMenu = self.game.loadMapMenu
elif self.state == 'Three':
self.game.currentMenu = self.game.resumeSavedGameMenu
self.game.previousMenu = self.state
elif self.state == 'Four':
self.game.currentMenu = self.game.deleteMapMenu
self.runDisplay = False
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'One'
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
self.moved = 'Yes'
if self.state == 'One':
self.pointerRect.midtop = (self.secondModuleX + self.offset, self.secondModuleY)
self.state = 'Two'
elif self.state == 'Two':
self.pointerRect.midtop = (self.thirdModuleX + self.offset, self.thirdModuleY)
self.state = 'Three'
elif self.state == 'Three':
self.pointerRect.midtop = (self.fourthModuleX + self.offset, self.fourthModuleY)
self.state = 'Four'
elif self.state == 'Four':
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'One'
elif self.game.UP_KEY or self.game.W_KEY:
self.moved = 'Yes'
if self.state == 'One':
self.pointerRect.midtop = (self.fourthModuleX + self.offset, self.fourthModuleY)
self.state = 'Four'
elif self.state == 'Two':
self.pointerRect.midtop = (self.firstModuleX + self.offset, self.firstModuleY)
self.state = 'One'
elif self.state == 'Three':
self.pointerRect.midtop = (self.secondModuleX + self.offset, self.secondModuleY)
self.state = 'Two'
elif self.state == 'Four':
self.pointerRect.midtop = (self.thirdModuleX + self.offset, self.thirdModuleY)
self.state = 'Three'
class ResumeSavedGameMenu(Menu):
def __init__(self, game):
"""
Sub menu for Module III that allows player to choose his own map.
:param game:
Game class that allows connection between game logic and menu.
:type game: game.Game, required
"""
Menu.__init__(self, game)
self.textInfoX, self.textInfoY = midWidth, midHeight - 280
self.itemMapX, self.itemMapY = midWidth, midHeight - 180
self.deleteRect = pygame.Rect(midWidth + 450, midHeight + 320, 140, 50)
self.offset = -100
self.pointerRect = pygame.Rect(0, 0, 20, 20)
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + 10)
self.counter = 0
self.storekeeperImg = pygame.transform.scale(STOREKEEPER_IMG, (40, 40))
self.mapArray = []
self.chosenMap = ''
def displayMenu(self):
"""
Method that displays the menu. It prints 7 buttons thanks to the drawText() method.
It also draws the pointer and blits the screen every single frame.
"""
self.runDisplay = True
maps = os.listdir(SAVES_DIR)
amount = 0
self.cleanMaps(maps, self.game.previousMenu)
self.game.previousMenu = ''
self.resetPointer()
if len(self.mapArray) > 0:
self.chosenMap = self.mapArray[0]
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('CHOOSE MAP', 65, self.textInfoX, self.textInfoY,
WHITE, self.game.fontName)
for row in range(len(self.mapArray)):
if row < 12:
board = self.prepareSaveName(self.mapArray[row])
self.game.drawText(str(board), 28, self.itemMapX, self.itemMapY + (row * 45),
WHITE, self.game.fontName)
self.drawPointer()
self.blitScreen()
else:
while self.runDisplay:
self.game.resetKeys()
self.game.checkEvents()
self.checkInput()
self.game.display.fill(BLACK)
self.game.drawText('YOU HAVE NOT CREATED ANY SAVES', 65, midWidth, midHeight,
WHITE, self.game.fontName)
self.blitScreen()
def resetPointer(self):
"""
Utility function for reset pointer position after selected action.
"""
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + 10)
self.chosenMap = ''
def prepareSaveName(self, filename):
"""
Utility function for preparing player save game for nice format.
:param filename:
Name of the file which contains save.
:type filename: str, required
:return:
Nice looking save game name.
:rtype: str
"""
playerName = filename[:filename.find('_')]
hours = filename[len(playerName) + 1:]
hour = hours[:8]
date = hours[9:19]
hour = hour.replace('_', ':')
date = date.replace('_', '/')
result = ''.join((playerName, ' ', hour, ' ', date))
return result
def movePointer(self):
"""
Method that includes pointer's movement logic. Moreover, it includes an end event handler.
"""
if self.game.DOWN_KEY or self.game.S_KEY:
self.counter += 1
if self.counter > len(self.mapArray) - 1 or self.counter > 11:
self.counter = 0
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + (self.counter * 45))
self.chosenMap = self.mapArray[self.counter]
elif self.game.UP_KEY or self.game.W_KEY:
self.counter -= 1
if self.counter < 0:
self.counter = len(self.mapArray) - 1
self.pointerRect.midtop = (self.itemMapX + self.offset, self.itemMapY + self.counter * 45)
self.chosenMap = self.mapArray[self.counter]
def checkInput(self):
"""
Method that handles changing the currently displayed menu.
"""
self.movePointer()
if self.game.ESC_PRESSED:
self.runDisplay = False
self.mapArray.clear()
self.game.currentMenu = self.game.mainMenu
if self.game.START_KEY and len(self.mapArray) > 0:
self.runDisplay = False
self.game.logicState = True
self.game.restoreDetails = logic.loadSave(self.chosenMap[:len(self.chosenMap) - 4])
self.mapArray.clear()
if self.game.restoreDetails['flag'] == MODULE_II:
self.game.gameLevel = self.game.restoreDetails['lvlName']
logic.startTheGame(self.game.window, self.chosenMap,
self.game, self.game.gamePoints, RESTORE)
if self.game.gameLevel > self.game.restoreDetails['lvlName']:
while self.game.gameLevel <= 20 and self.game.START_KEY:
self.game.currentLevel = self.game.gameLevel
boardName = str(self.game.currentLevel) + '.txt'
logic.startTheGame(self.game.window, boardName, self.game,
self.game.gamePoints, MODULE_II)
self.game.logicState = True
elif self.game.restoreDetails['flag'] == MODULE_III:
logic.startTheGame(self.game.window, self.chosenMap,
self.game, self.game.gamePoints, RESTORE)
self.game.restoreDetails.clear()
elif self.game.START_KEY and len(self.mapArray) <= 0:
self.runDisplay = False
self.game.currentMenu = self.game.loadSaveMenu
self.mapArray.clear()
def prepareSaveName(self, filename):
"""
Utility function for preparing player save game for nice format.
:param filename:
Name of the file which contains save.
:type filename: str, required
:return:
Nice looking save game name.
:rtype: str
"""
playerName = filename[:filename.find('_')]
hours = filename[len(playerName) + 1:]
hour = hours[:8]
date = hours[9:19]
hour = hour.replace('_', ':')
date = date.replace('_', '/')
result = ''.join((playerName, ' ', hour, ' ', date))
return result
def cleanMaps(self, maps, previousState):
"""
Method for choosing map based on before selected menu.
:param maps:
List of game saves in folder SAVES_DIR.
:type maps: list, required
:param previousState:
Flag that allows to discriminate module II and III saved games.
:type previousState: str, required
"""
for file in maps:
if file.find('.bak') > -1 and \
re.search(rf'\b{self.game.playerName}(_)(.*)\b', file):
if re.search(rf'\b(.*)(_){previousState}\b', file):
self.mapArray.append(file)
|
"""
List Exercise 1
Implementieren Sie die Funktion list_from_range(), um damit eine Liste mit allen Elementen von 'min' bis
und mit 'max' zu erstellen. Verwenden Sie List.append() und benutzen Sie die nachfolgenden Tests zur Kontrolle.
"""
def list_from_range(min, max):
my_list = []
for element in range(min, max + 1):
my_list.append(element)
return my_list
# Tests
print(list_from_range(-1, 4)) # -> [-1, 0, 1, 2, 3, 4]
print(list_from_range(1, -4)) # -> []
|
# -*- encoding: utf-8 -*-
import logging
from celery import task
from checkout.models import ObjectPaymentPlanInstalment
logger = logging.getLogger(__name__)
@task()
def process_payments():
logger.info('process_payments')
ObjectPaymentPlanInstalment.objects.process_payments()
@task()
def refresh_card_expiry_dates():
logger.info('refresh_card_expiry_dates')
ObjectPaymentPlan.objects.refresh_card_expiry_dates()
|
# coding: utf-8
import gym
from gym import wrappers
import random
import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
from collections import deque
import numpy as np
env = gym.make('CartPole-v1')
# hyper parameters
EPISODES = 50 # number of episodes
EPS_START = 0.9 # e-greedy threshold start value
EPS_END = 0.05 # e-greedy threshold end value
EPS_DECAY = 200 # e-greedy threshold decay
GAMMA = 0.8 # Q-learning discount factor
LR = 0.001 # NN optimizer learning rate
HIDDEN_LAYER = 256 # NN hidden layer size
BATCH_SIZE = 64 # Q-learning batch size
class DQNAgent:
def __init__(self):
self.model = nn.Sequential(
nn.Linear(4, HIDDEN_LAYER),
nn.ReLU(),
nn.Linear(HIDDEN_LAYER, 2)
)
self.memory = deque(maxlen=10000)
self.optimizer = optim.Adam(self.model.parameters(), LR)
self.steps_done = 0
def act(self, state):
eps_threshold = EPS_END + (EPS_START - EPS_END) * math.exp(-1. * self.steps_done / EPS_DECAY)
self.steps_done += 1
if random.random() > eps_threshold:
return self.model(state).data.max(1)[1].view(1, 1)
else:
return torch.LongTensor([[random.randrange(2)]])
def memorize(self, state, action, reward, next_state):
self.memory.append((state,
action,
torch.FloatTensor([reward]),
torch.FloatTensor([next_state])))
def learn(self):
"""Experience Replay"""
if len(self.memory) < BATCH_SIZE:
return
batch = random.sample(self.memory, BATCH_SIZE)
states, actions, rewards, next_states = zip(*batch)
states = torch.cat(states)
actions = torch.cat(actions)
rewards = torch.cat(rewards)
next_states = torch.cat(next_states)
current_q = self.model(states).gather(1, actions)
max_next_q = self.model(next_states).detach().max(1)[0]
expected_q = rewards + (GAMMA * max_next_q)
loss = F.mse_loss(current_q.squeeze(), expected_q)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
agent = DQNAgent()
env = gym.make('CartPole-v0')
episode_durations = []
for e in range(1, EPISODES+1):
state = env.reset()
steps = 0
while True:
env.render()
state = torch.FloatTensor([state])
action = agent.act(state)
next_state, reward, done, _ = env.step(action.item())
# negative reward when attempt ends
if done:
reward = -1
agent.memorize(state, action, reward, next_state)
agent.learn()
state = next_state
steps += 1
if done:
print("{2} Episode {0} finished after {1} steps"
.format(e, steps, '\033[92m' if steps >= 195 else '\033[99m'))
episode_durations.append(steps)
break
|
import dropbox
from dropbox import DropboxOAuth2FlowNoRedirect
from papergit.config import config
class Dropbox:
"""
The base dropbox class to access.
"""
def __init__(self):
self.dbx = None
def initialize(self):
assert config.initialized
self.dbx = dropbox.Dropbox(self.get_auth_token())
def get_old_auth_token(self):
# Check if the OAuth Flow has been performed before and thus doesn't
# need to be done again. If yes, return the auth_token
token = getattr(config.dropbox, 'api_token')
return None if token == '' else token
def get_auth_token(self):
old_token = self.get_old_auth_token()
if old_token is None:
# This means that we don't have the authentication token, so run the
# entire workflow again to get the auth token.
return self.get_new_auth_token()
# If not none, just return the old Auth Token
return old_token
def get_new_auth_token(self):
# Run the dropbox OAuth Flow to get the user's OAuth Token.
auth_flow = DropboxOAuth2FlowNoRedirect(config.dropbox.app_key,
config.dropbox.app_secret)
authorize_url = auth_flow.start()
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
try:
oauth_result = auth_flow.finish(auth_code)
except Exception as e:
print('Error: %s' % (e,))
return
config.write_to_user_config('dropbox', 'api_token',
oauth_result.access_token)
return oauth_result.access_token
def initialize():
dbox = Dropbox()
dbox.initialize()
config.dbox = dbox
|
from dbca_utils.utils import env
import dj_database_url
import os
from pathlib import Path
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = str(Path(__file__).resolve().parents[1])
PROJECT_DIR = str(Path(__file__).resolve().parents[0])
# Add PROJECT_DIR to the system path.
sys.path.insert(0, PROJECT_DIR)
# Settings defined in environment variables.
DEBUG = env('DEBUG', False)
SECRET_KEY = env('SECRET_KEY', 'PlaceholderSecretKey')
CSRF_COOKIE_SECURE = env('CSRF_COOKIE_SECURE', False)
SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE', False)
if not DEBUG:
ALLOWED_HOSTS = env('ALLOWED_DOMAINS', '').split(',')
else:
ALLOWED_HOSTS = ['*']
INTERNAL_IPS = ['127.0.0.1', '::1']
ROOT_URLCONF = 'ibms_project.urls'
WSGI_APPLICATION = 'ibms_project.wsgi.application'
INSTALLED_APPS = (
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django_extensions',
'crispy_forms',
'crispy_bootstrap5',
'webtemplate_dbca',
'ibms',
'sfm',
)
MIDDLEWARE = [
'ibms_project.middleware.HealthCheckMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'dbca_utils.middleware.SSOLoginMiddleware',
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': (os.path.join(BASE_DIR, 'ibms_project', 'templates'),),
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.template.context_processors.request',
'django.template.context_processors.csrf',
'django.contrib.messages.context_processors.messages',
'ibms_project.context_processors.standard'
],
},
}
]
SITE_TITLE = 'Integrated Business Management System'
SITE_ACRONYM = 'IBMS'
APPLICATION_VERSION_NO = '2.7.0'
ADMINS = ('[email protected]',)
MANAGERS = (
('Natasha Omelchuk', '[email protected]', '9219 9099'),
('Graham Holmes', '[email protected]', '9881 9212'),
('Neil Clancy', '[email protected]', '9219 9926'),
)
SITE_ID = 1
ANONYMOUS_USER_ID = 1
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
IBM_CODE_UPDATER_URI = env('IBM_CODE_UPDATER_URI', '')
IBM_SERVICE_PRIORITY_URI = env('IBM_SERVICE_PRIORITY_URI', '')
IBM_RELOAD_URI = env('IBM_RELOAD_URI', '')
IBM_DATA_AMEND_URI = env('IBM_DATA_AMEND_URI', '')
DATA_UPLOAD_MAX_NUMBER_FIELDS = None # Required to allow end-of-month GLPivot bulk deletes.
CSV_FILE_LIMIT = env('CSV_FILE_LIMIT', 100000000)
# Database configuration
DATABASES = {
# Defined in DATABASE_URL env variable.
'default': dj_database_url.config(),
}
# Static files (CSS, JavaScript, Images)
# Ensure that the media directory exists:
if not os.path.exists(os.path.join(BASE_DIR, 'media')):
os.mkdir(os.path.join(BASE_DIR, 'media'))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(PROJECT_DIR, 'static'), )
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
WHITENOISE_ROOT = STATIC_ROOT
# Internationalisation.
USE_I18N = False
USE_TZ = True
TIME_ZONE = 'Australia/Perth'
LANGUAGE_CODE = 'en-us'
DATE_INPUT_FORMATS = (
'%d/%m/%y',
'%d/%m/%Y',
'%d-%m-%y',
'%d-%m-%Y',
'%d %b %Y',
'%d %b, %Y',
'%d %B %Y',
'%d %B, %Y')
DATETIME_INPUT_FORMATS = (
'%d/%m/%y %H:%M',
'%d/%m/%Y %H:%M',
'%d-%m-%y %H:%M',
'%d-%m-%Y %H:%M',)
# Email settings.
EMAIL_HOST = env('EMAIL_HOST', 'email.host')
EMAIL_PORT = env('EMAIL_PORT', 25)
# Logging settings - log to stdout/stderr
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'console': {'format': '%(asctime)s %(name)-12s %(message)s'},
'verbose': {'format': '%(asctime)s %(levelname)-8s %(message)s'},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'console'
},
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
},
'django.request': {
'handlers': ['console'],
'level': 'WARNING',
'propagate': False,
},
'ibms': {
'handlers': ['console'],
'level': 'INFO'
},
}
}
# django-crispy-forms config
CRISPY_ALLOWED_TEMPLATE_PACKS = 'bootstrap5'
CRISPY_TEMPLATE_PACK = 'bootstrap5'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
# import matplotlib
# matplotlib.use('Agg')
# import matplotlib.pyplot as plt
import copy
import os
import pickle
import itertools
import numpy as np
import pandas as pd
from tqdm import tqdm
from scipy.stats import mode
from torchvision import datasets, transforms, models
import torch
from torch import nn
from utils.train_utils import get_model, get_data
from utils.options import args_parser
from models.Update import LocalUpdateMTL
from models.test import test_img, test_img_local, test_img_local_all, test_img_avg_all, test_img_ensemble_all
import pdb
if __name__ == '__main__':
# parse args
args = args_parser()
args.device = torch.device('cuda:{}'.format(args.gpu) if torch.cuda.is_available() and args.gpu != -1 else 'cpu')
base_dir = './save/{}/{}_iid{}_num{}_C{}_le{}/shard{}/{}/'.format(
args.dataset, args.model, args.iid, args.num_users, args.frac, args.local_ep, args.shard_per_user, args.results_save)
base_save_dir = os.path.join(base_dir, 'mtl')
if not os.path.exists(base_save_dir):
os.makedirs(base_save_dir, exist_ok=True)
dataset_train, dataset_test, dict_users_train, dict_users_test = get_data(args)
dict_save_path = os.path.join(base_dir, 'dict_users.pkl')
with open(dict_save_path, 'rb') as handle:
dict_users_train, dict_users_test = pickle.load(handle)
# build model
net_glob = get_model(args)
net_glob.train()
print(net_glob)
net_glob.train()
total_num_layers = len(net_glob.weight_keys)
w_glob_keys = net_glob.weight_keys[total_num_layers - args.num_layers_keep:]
w_glob_keys = list(itertools.chain.from_iterable(w_glob_keys))
num_param_glob = 0
num_param_local = 0
for key in net_glob.state_dict().keys():
num_param_local += net_glob.state_dict()[key].numel()
if key in w_glob_keys:
num_param_glob += net_glob.state_dict()[key].numel()
percentage_param = 100 * float(num_param_glob) / num_param_local
print('# Params: {} (local), {} (global); Percentage {:.2f} ({}/{})'.format(
num_param_local, num_param_glob, percentage_param, num_param_glob, num_param_local))
# generate list of local models for each user
net_local_list = []
for user_ix in range(args.num_users):
net_local_list.append(copy.deepcopy(net_glob))
criterion = nn.CrossEntropyLoss()
# training
results_save_path = os.path.join(base_save_dir, 'results.csv')
loss_train = []
net_best = None
best_acc = np.ones(args.num_users) * -1
best_net_list = copy.deepcopy(net_local_list)
lr = args.lr
results = []
m = max(int(args.frac * args.num_users), 1)
I = torch.ones((m, m))
i = torch.ones((m, 1))
omega = I - 1 / m * i.mm(i.T)
omega = omega ** 2
omega = omega.cuda()
W = [net_local_list[0].state_dict()[key].flatten() for key in w_glob_keys]
W = torch.cat(W)
d = len(W)
del W
for iter in range(args.epochs):
w_glob = {}
loss_locals = []
m = max(int(args.frac * args.num_users), 1)
idxs_users = np.random.choice(range(args.num_users), m, replace=False)
W = torch.zeros((d, m)).cuda()
for idx, user in enumerate(idxs_users):
W_local = [net_local_list[user].state_dict()[key].flatten() for key in w_glob_keys]
W_local = torch.cat(W_local)
W[:, idx] = W_local
for idx, user in enumerate(idxs_users):
local = LocalUpdateMTL(args=args, dataset=dataset_train, idxs=dict_users_train[user])
net_local = net_local_list[user]
w_local, loss = local.train(net=net_local.to(args.device), lr=lr,
omega=omega, W_glob=W.clone(), idx=idx, w_glob_keys=w_glob_keys)
loss_locals.append(copy.deepcopy(loss))
loss_avg = sum(loss_locals) / len(loss_locals)
loss_train.append(loss_avg)
# eval
acc_test_local, loss_test_local = test_img_local_all(net_local_list, args, dataset_test, dict_users_test, return_all=True)
for user in range(args.num_users):
if acc_test_local[user] > best_acc[user]:
best_acc[user] = acc_test_local[user]
best_net_list[user] = copy.deepcopy(net_local_list[user])
model_save_path = os.path.join(base_save_dir, 'model_user{}.pt'.format(user))
torch.save(best_net_list[user].state_dict(), model_save_path)
acc_test_local, loss_test_local = test_img_local_all(best_net_list, args, dataset_test, dict_users_test)
acc_test_avg, loss_test_avg = test_img_avg_all(net_glob, best_net_list, args, dataset_test)
print('Round {:3d}, Avg Loss {:.3f}, Loss (local): {:.3f}, Acc (local): {:.2f}, Loss (avg): {:.3}, Acc (avg): {:.2f}'.format(
iter, loss_avg, loss_test_local, acc_test_local, loss_test_avg, acc_test_avg))
results.append(np.array([iter, acc_test_local, acc_test_avg, best_acc.mean(), None, None]))
final_results = np.array(results)
final_results = pd.DataFrame(final_results, columns=['epoch', 'acc_test_local', 'acc_test_avg', 'best_acc_local', 'acc_test_ens_avg', 'acc_test_ens_maj'])
final_results.to_csv(results_save_path, index=False)
acc_test_ens_avg, loss_test, acc_test_ens_maj = test_img_ensemble_all(best_net_list, args, dataset_test)
print('Best model, acc (local): {}, acc (ens,avg): {}, acc (ens,maj): {}'.format(best_acc, acc_test_ens_avg, acc_test_ens_maj))
results.append(np.array(['Final', None, None, best_acc.mean(), acc_test_ens_avg, acc_test_ens_maj]))
final_results = np.array(results)
final_results = pd.DataFrame(final_results,
columns=['epoch', 'acc_test_local', 'acc_test_avg', 'best_acc_local', 'acc_test_ens_avg', 'acc_test_ens_maj'])
final_results.to_csv(results_save_path, index=False) |
from typing import Dict, List
import pytest
import torch
from torch.optim import AdamW
from bert_summarizer.config.bertsum import BertSumAbsConfig
from bert_summarizer.models.bertsum import BertSumAbs
from bert_summarizer.trainers.lr_lambda import (
TransformerScheduler,
get_transformer_schedule_with_warmup,
)
class TestTransformerScheduler:
@pytest.fixture
def lr_lambda(self) -> TransformerScheduler:
return TransformerScheduler(10000)
def test_attribute(self, lr_lambda: TransformerScheduler) -> None:
assert lr_lambda.num_warmup_steps == 10000
@pytest.mark.parametrize(
"current_step, expected", [(1, 1e-6), (10000, 1e-2), (1000000, 1e-3)]
)
def test_call(
self, lr_lambda: TransformerScheduler, current_step: int, expected: float
) -> None:
assert lr_lambda(current_step) == expected
class TestGetScheduler:
@pytest.fixture
def model(self) -> BertSumAbs:
return BertSumAbs(BertSumAbsConfig())
@pytest.fixture
def optimizer(self, model: BertSumAbs) -> AdamW:
params: List[Dict[str, torch.Tensor]] = [dict(params=[]), dict(params=[])]
for i, p in enumerate(model.parameters()):
params[i % 2]["params"].append(p)
return AdamW(params)
@pytest.mark.parametrize(
"num_warmup_steps, expected",
[(10000, [10000, 10000]), ([10000, 20000], [10000, 20000])],
)
def test_get_transformer_schedule_with_warmup(
self, optimizer: AdamW, num_warmup_steps: int, expected: List[int]
) -> None:
lr_scheduler = get_transformer_schedule_with_warmup(optimizer, num_warmup_steps)
assert len(lr_scheduler.lr_lambdas) == len(expected)
for lr_lambda, n in zip(lr_scheduler.lr_lambdas, expected):
assert lr_lambda.num_warmup_steps == n
|
# Faça um programa que leia um numero inteiro qualquer e mostre na tela a sua tabuada
taboada = int(input('\nDigite o número da taboada: '))
n1 = taboada * 1
n2 = taboada * 2
n3 = taboada * 3
n4 = taboada * 4
n5 = taboada * 5
n6 = taboada * 6
n7 = taboada * 7
n8 = taboada * 8
n9 = taboada * 9
n10 = taboada * 10
print('\nA taboada do {} é\n'.format(taboada))
print('-------------')
print('{} x 1 = {}'.format(taboada, n1))
print('{} x 2 = {}'.format(taboada, n2))
print('{} x 3 = {}'.format(taboada, n3))
print('{} x 4 = {}'.format(taboada, n4))
print('{} x 5 = {}'.format(taboada, n5))
print('{} x 6 = {}'.format(taboada, n6))
print('{} x 7 = {}'.format(taboada, n7))
print('{} x 8 = {}'.format(taboada, n8))
print('{} x 9 = {}'.format(taboada, n9))
print('{} x 10 = {}'.format(taboada, n10))
print('-------------')
|
import asyncio
import hashlib
import logging
import time
import os
from aiohttp import WSMsgType
from aiohttp.web import (
WebSocketResponse,
json_response,
FileResponse,
Response,
)
logger = logging.getLogger('ira')
TEMPLATE_ROOT = os.path.join(
os.path.dirname(__file__),
'templates',
)
FRONTENT_HTML = os.path.join(
TEMPLATE_ROOT,
'frontend.html',
)
STATIC_ROOT = os.path.join(
os.path.dirname(__file__),
'static',
)
class IraServer:
def __init__(self, app):
self.app = app
self._loop = None
self._executor = None
self.connections = {}
self.pending_futures = {}
self._pending_browser_connections = []
self.app.on_shutdown.append(self.stop)
# setup aiohttp routes
logger.debug('setup aiohttp routing')
self.app.router.add_route(
'*', '/ira/static/{path:.*}', self.handle_static_file_request)
self.app.router.add_route(
'*', '/ira/token.json', self.handle_token_request)
self.app.router.add_route(
'POST', '/ira/{token}/rpc.json', self.handle_rpc_requests)
self.app.router.add_route(
'*', '/ira/', self.handle_frontend_request)
self.app.router.add_route(
'*', '/ira', self.handle_frontend_request)
def set_loop(self, loop):
self._loop = loop
def set_executor(self, executor):
self._executor = executor
@property
def loop(self):
return self._loop
@property
def executor(self):
return self._executor
async def stop(self, *args, **kwargs):
logger.debug('stop')
for token, websocket in self.connections.copy().items():
try:
await websocket.close()
except Exception:
pass
# asyncio helper ##########################################################
def run_coroutine_sync(self, coroutine, wait=True):
future = asyncio.run_coroutine_threadsafe(coroutine, loop=self.loop)
if wait:
return future.result()
return future
def run_function_async(self, function, *args, **kwargs):
def _function():
return function(*args, **kwargs)
return self.loop.run_in_executor(self.executor, _function)
# handle frontend #########################################################
async def generate_token(self):
def _generate_token():
return hashlib.md5(str(time.monotonic_ns()).encode()).hexdigest()
return await self.run_function_async(_generate_token)
async def handle_static_file_request(self, request):
def find_static_file():
rel_path = request.match_info['path']
abs_path = os.path.join(STATIC_ROOT, rel_path)
file_exists = os.path.exists(abs_path)
return file_exists, abs_path
file_exists, path = await self.run_function_async(
find_static_file,
)
if not file_exists:
return Response(
status=404,
text='404: Not found',
)
return FileResponse(path)
async def handle_frontend_websocket(self, request):
token = await self.generate_token()
websocket = WebSocketResponse()
await websocket.prepare(request)
self.connections[token] = websocket
if self._pending_browser_connections:
future = self._pending_browser_connections.pop(0)
future.set_result(True)
# main loop
try:
async for message in websocket:
if message.type == WSMsgType.TEXT:
if(token not in self.pending_futures or
self.pending_futures[token].done() or
self.pending_futures[token].cancelled()):
continue
self.pending_futures[token].set_result(message.data)
elif message.type in (WSMsgType.CLOSED, WSMsgType.ERROR):
break
except asyncio.CancelledError:
pass
except ConnectionResetError:
pass
finally:
self.connections.pop(token)
await websocket.close()
return websocket
async def handle_frontend_request(self, request):
# websocket
if(request.method == 'GET' and
request.headers.get('upgrade', '').lower() == 'websocket'):
return await self.handle_frontend_websocket(request)
response = FileResponse(FRONTENT_HTML)
return response
# rpc #####################################################################
async def handle_token_request(self, request):
data = {
'exit_code': 0,
'token': '',
}
for token, connection in self.connections.items():
data['token'] = token
return json_response(data)
data['exit_code'] = 1
return json_response(data)
async def handle_rpc_requests(self, request):
data = {
'exit_code': 1,
}
token = request.match_info['token']
if token not in self.connections:
data['exit_code'] = 1
else:
post_data = await request.post()
self.pending_futures[token] = asyncio.Future()
try:
await self.connections[token].send_str(post_data['data'])
except ConnectionResetError:
return json_response(data)
try:
await asyncio.wait_for(
self.pending_futures[token],
timeout=10,
)
json_data = self.pending_futures[token].result()
return Response(body=json_data)
finally:
self.pending_futures.pop(token)
return json_response(data)
# pytest helper ###########################################################
def await_browser_connected(self):
future = asyncio.Future(loop=self.loop)
if self.connections:
future.set_result(True)
else:
self._pending_browser_connections.append(future)
return future
|
from __future__ import division
import numpy as np
import pdb
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def final_l2(path1, path2):
row1 = path1[-1]
row2 = path2[-1]
return np.linalg.norm((row2.x.item() - row1.x, row2.y.item() - row1.y))
def average_l2(path1, path2, n_predictions):
assert len(path1) >= n_predictions
assert len(path2) >= n_predictions
path1 = path1[-n_predictions:]
path2 = path2[-n_predictions:]
path1_np_x = np.zeros([1,n_predictions])
path1_np_y = np.zeros([1,n_predictions])
path2_np_x = np.zeros([1,n_predictions])
path2_np_y = np.zeros([1,n_predictions])
j = 0
for r1, r2 in zip(path1, path2):
path1_np_x[0,j] = r1.x
path1_np_y[0,j] = r1.y
path2_np_x[0,j] = r2.x
path2_np_y[0,j] = r2.y
j += 1
return np.sum(np.sqrt((path1_np_x-path2_np_x)**2+(path1_np_y-path2_np_y)**2)) / n_predictions
#np.sum(np.sqrt(np.sum((r1.x - r2.x.item())**2,(r1.y - r2.y.item())**2),dim=1)))/1
#return sum(np.linalg.norm((r1.x - r2.x.item(), r1.y - r2.y.item()))
# for r1, r2 in zip(path1, path2)) / n_predictions
def cross_track(gt, pred, n_predictions):
""" Extend prediction to le length of ground truth, and find the l2 distance between the
last points."""
assert len(gt) >= n_predictions
assert len(pred) >= n_predictions
gt = gt[-n_predictions:]
pred = pred[-n_predictions:]
gt_np = np.zeros([n_predictions,2])
pred_np = np.zeros([n_predictions,2])
j = 0
for r1, r2 in zip(gt, pred):
gt_np[j,0] = r1.x
gt_np[j,1] = r1.y
pred_np[j,0] = r2.x
pred_np[j,1] = r2.y
j += 1
pred_speed = np.power(np.sum(np.power(pred_np[1:]-pred_np[:-1],2),1),0.5)
gt_speed = np.power(np.sum(np.power(gt_np[1:]-gt_np[:-1],2),1),0.5)
pred_speed_cum = pred_speed.cumsum()
gt_speed_cum = gt_speed.cumsum()
diff = abs(pred_speed_cum[-1] - gt_speed_cum[-1])
if(pred_speed_cum[-1] < gt_speed_cum[-1]): #if ground-truth is longer than prediction, prediction should be extrapolated
scale = diff/(pred_speed_cum[n_predictions-2]-pred_speed_cum[n_predictions-3]+0.01) + 1
mapped_p = scale*pred_np[n_predictions-1] + (1-scale)*pred_np[n_predictions-2]
else:
for i in range(n_predictions-1): # minus one, because we have speed profile
if(pred_speed_cum[n_predictions-2-i]<gt_speed_cum[-1]):
diff = gt_speed_cum[-1] - pred_speed_cum[n_predictions-2-i]
scale = diff/(pred_speed_cum[n_predictions-2-i+1]-pred_speed_cum[n_predictions-2-i]+0.01)#+1
mapped_p = scale*pred_np[n_predictions-1-i+1] + (1-scale)*pred_np[n_predictions-1-i]
break
if(gt_speed_cum[-1]<=pred_speed_cum[0]): #gt is smaller than all of them
diff = gt_speed_cum[-1] - pred_speed_cum[0]
scale = diff/(pred_speed_cum[0]+0.01)+1
mapped_p = scale*pred_np[1] + (1-scale)*pred_np[0]
try:
return np.power(np.sum(np.power(gt_np[-1] - mapped_p,2),0),0.5)
except:
pdb.set_trace()
|
class ButtonMapper:
"""
Used to build a dictonary of button roles to the raw buttons for the controller
This is performing well and exiting its thread properly
"""
def __init__(self):
"""
Contains a list of all possible buttons that could be mapped
to check against the user mapping.
"""
self.pos_roles = [
"Button_A",
"Button_B",
"Button_X",
"Button_Y",
"Button_Z",
"Trigger_R",
"Trigger_L",
"Button_DPad_Up",
"Button_DPad_Down",
"Button_DPad_Left",
"Button_DPad_Right",
]
self.roles = []
self.correct = False
self.event = None
def wait_event(self):
"""
Waits for a signal that the gui.py has sent a controller event
then resets the signal and returns to the waiting function.
"""
while not self.cal_event.isSet():
self.cal_event.wait()
self.cal_event.clear()
def build_btns(self, profile, mapping, canvas, cal_event, end_btnmap):
"""
Scans the mapping and the list of all possible buttons to make
a list of buttons that need to be bound in the dictionary
Prompts the user to press each button and then confirm.
If the user presses B or any button that is not assigned properly
will restart the loop. Upon confirmation updates the dictionary
and quits.
"""
self.cal_event = cal_event
self.canvas = canvas
for role in self.pos_roles:
if role in mapping.values():
self.roles.append(role)
clean_map = {}
self.canvas.itemconfig("prompt", text="No buttons bound, Press Button_Start")
self.wait_event()
self.add_button(self.event[0], "Button_Start", clean_map)
while not self.correct:
tmp_map = clean_map.copy()
for role in self.roles:
self.canvas.itemconfig("prompt", text=f"Press {role}")
self.wait_event()
self.add_button(self.event[0], role, tmp_map)
self.canvas.itemconfig("prompt", text="Confirm with A, retry with B")
while True:
self.wait_event()
if self.event[0] not in tmp_map:
break
if "Button_A" in tmp_map[self.event[0]][1][0][0]:
self.correct = True
profile.update(tmp_map)
break
if "Button_B" in tmp_map[self.event[0]][1][0][0]:
break
print(profile)
end_btnmap()
self.close()
def add_button(self, btn, role, map):
"""
Helper function to add roles to the dictonary. The elif/else
are only necesarry if the user is pressing the same button for multiple
roles.
"""
if btn not in map:
map[btn] = {1: [[role]]}
elif 1 not in map[btn]:
map[btn][1] = [[role]]
else:
map[btn][1].append([role])
def put_event(self, event):
"""
Helper function that allows the gui.py to send a raw controller
event
"""
if self.event:
self.event = None
self.event = event
self.confirm = True
def close(self):
"""
Reset variables to default and remove the prompting text from the screen
"""
self.roles.clear()
self.event = None
self.confirm = False
self.canvas.delete("prompt")
|
# This script will use a list of strains in order to generate the model files for the strains.
# All files generated will be put into the "out" directory in the main application.
# Why? Generating the needed data outside of minecraft means less delay when loading the mod.
# I could do it all in the mod itself, but why do it that way, when python is better ;)
import json
import os
#! LIST OF STRAINS
# Master list of strains, change this to change names/values of generated files
strains = [
"yard_trimmings",
"chem_fruit",
"trainwreck",
"miners_delight",
"green_golem",
"og_hunter",
"dolphin_daydream",
"sour_budda",
"blue_widow",
"holy_grain",
"scout_master",
"rickys_special"
]
# Change out_dir to where you want the files to go. Include the last slash.
# out_dir = "out/"
out_dir = "src/main/resources/"
dir_item_models = out_dir + "assets/hempcraft/models/item/"
dir_blockstates = out_dir + "assets/hempcraft/blockstates/"
dir_loottables = out_dir + "data/hempcraft/loot_tables/"
dir_recipe = out_dir + "data/hempcraft/recipes/"
dir_advancements = out_dir + "/data/hempcraft/advancements/"
# Creates a Directory if non exists
def createDir(path):
if not os.path.exists(path):
os.makedirs(path)
print("Created Directory: " + path)
# Writes JSON to a file of specific directory.
def writeJSON(dir, type, name, data):
createDir(dir + type)
with open(dir + type + "/" + name + ".json", 'w') as f:
json.dump(data, f)
print("Generated: " + dir + type + ":" + name)
f.close
# Generates the loot table based off of JSON
def generateLootTable(name):
return {
"type": "minecraft:block",
"pools": [
{
"rolls": 1.0,
"bonus_rolls": 0.0,
"entries": [
{
"type": "minecraft:alternatives",
"children": [
{
"type": "minecraft:item",
"conditions": [
{
"condition": "minecraft:block_state_property",
"block": "hempcraft:plant/" + name,
"properties": {
"age": "7"
}
}
],
"name": "hempcraft:bud/" + name
},
{
"type": "minecraft:item",
"name": "hempcraft:seed/" + name
},
{
"type": "minecraft:item",
"name": "hempcraft:hemp_leaf"
}
]
}
]
},
{
"rolls": 1.0,
"bonus_rolls": 0.0,
"entries": [
{
"type": "minecraft:item",
"functions": [
{
"function": "minecraft:apply_bonus",
"enchantment": "minecraft:fortune",
"formula": "minecraft:binomial_with_bonus_count",
"parameters": {
"extra": 3,
"probability": 0.5714286
}
}
],
"name": "hempcraft:seed/" + name
},
{
"type": "minecraft:item",
"functions": [
{
"function": "minecraft:apply_bonus",
"enchantment": "minecraft:fortune",
"formula": "minecraft:binomial_with_bonus_count",
"parameters": {
"extra": 3,
"probability": 0.5714286
}
}
],
"name": "hempcraft:hemp_leaf"
}
],
"conditions": [
{
"condition": "minecraft:block_state_property",
"block": "hempcraft:plant/" + name,
"properties": {
"age": "7"
}
}
]
}
],
"functions": [
{
"function": "minecraft:explosion_decay"
}
]
}
def generateRecipe(name, type):
wrapper = type
if type == "joint":
wrapper = "joint_paper"
elif type == "cone":
wrapper = "empty_cone"
elif type == "blunt":
wrapper = "empty_blunt"
return {
"type": "minecraft:crafting_shaped",
"pattern":
[
"W",
"P"
],
"key":
{
"P": { "item": "hempcraft:" + wrapper },
"W": { "item": "hempcraft:bud/" + name }
},
"result":
{
"item": "hempcraft:" + type + "/" + name,
"count": 1
}
}
def generateAdvancements(name, type):
return {
"criteria": {
"requirement": {
"trigger": "minecraft:inventory_changed",
"conditions": {
"items": [
{
"items": [
"hempcraft:bud/" + name
]
}
]
}
}
},
"rewards": {
"recipes": [
"hempcraft:" + type + "/" + name
]
}
}
# Model Objects for items
item_seeds = { "parent" : "hempcraft:item/seed" }
item_buds = { "parent": "hempcraft:item/bud" }
item_joints = { "parent": "hempcraft:item/joint" }
item_cones = { "parent": "hempcraft:item/cone" }
item_blunts = { "parent": "hempcraft:item/blunt" }
# BlockStates for Plant (JSON)
blockstate_plant = {
"variants": {
"age=0": {
"model": "hempcraft:block/plant_0"
},
"age=1": {
"model": "hempcraft:block/plant_1"
},
"age=2": {
"model": "hempcraft:block/plant_2"
},
"age=3": {
"model": "hempcraft:block/plant_3"
},
"age=4": {
"model": "hempcraft:block/plant_4"
},
"age=5": {
"model": "hempcraft:block/plant_5"
},
"age=6": {
"model": "hempcraft:block/plant_6"
},
"age=7": {
"model": "hempcraft:block/plant_7"
}
}
}
print("Writing Files")
# The actual generation
# Goes through each strain, and uses the functions to write JSON files to their appropriate directories.
for x in strains:
writeJSON(dir_item_models, "seed", x, item_seeds)
writeJSON(dir_item_models, "bud", x, item_buds)
writeJSON(dir_item_models, "joint", x, item_joints)
writeJSON(dir_item_models, "cone", x, item_cones)
writeJSON(dir_item_models, "blunt", x, item_blunts)
writeJSON(dir_blockstates, "plant", x, blockstate_plant)
writeJSON(dir_loottables + "blocks/", "plant", x, generateLootTable(x))
writeJSON(dir_recipe, "joint", x, generateRecipe(x, "joint"))
writeJSON(dir_recipe, "cone", x, generateRecipe(x, "cone"))
writeJSON(dir_recipe, "blunt", x, generateRecipe(x, "blunt"))
writeJSON(dir_advancements, "joint", x, generateAdvancements(x, "joint"))
writeJSON(dir_advancements, "cone", x, generateAdvancements(x, "cone"))
writeJSON(dir_advancements, "blunt", x, generateAdvancements(x, "blunt"))
|
from .falcon import FalconAPI, StreamManagementThread
from .worker import WorkerThread
from .queue import falcon_events
from .config import config
from .backends import Backends
from .falcon_data import FalconCache
if __name__ == "__main__":
# Central to the fig architecture is a message queue (falcon_events). GCPWorkerThread/s read the queue and process
# each event. The events are put on queue by StreamingThread. StreamingThread is restarted by StreamManagementThread
config.validate()
falcon_cache = FalconCache(FalconAPI())
backends = Backends()
StreamManagementThread(output_queue=falcon_events).start()
for i in range(int(config.get('main', 'worker_threads'))):
WorkerThread(name='worker-' + str(i),
input_queue=falcon_events,
falcon_cache=falcon_cache,
backends=backends,
daemon=True).start()
|
# coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import subprocess
import unittest
from pants.base.scm_project_tree import ScmProjectTree
from pants.scm.git import Git
from pants_test.base.pants_ignore_test_base import PantsIgnoreTestBase
class ScmPantsIgnoreTest(unittest.TestCase, PantsIgnoreTestBase):
"""
Common test cases are defined in PantsIgnoreTestBase.
Special test cases can be defined here.
"""
def mk_project_tree(self, build_root, ignore_patterns=None):
return ScmProjectTree(build_root, Git(worktree=build_root), 'HEAD', ignore_patterns)
def setUp(self):
super(ScmPantsIgnoreTest, self).setUp()
self.prepare()
subprocess.check_call(['git', 'init'])
subprocess.check_call(['git', 'config', 'user.email', '[email protected]'])
subprocess.check_call(['git', 'config', 'user.name', 'Your Name'])
subprocess.check_call(['git', 'add', '.'])
subprocess.check_call(['git', 'commit', '-m' 'initial commit'])
def tearDown(self):
super(ScmPantsIgnoreTest, self).tearDown()
self.cleanup()
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# this module wraps kubectl
import nuvolaris.testutil as tu
import nuvolaris.template as tpl
import subprocess
import json
import logging
import yaml
output = ""
error = ""
returncode = -1
dry_run = False
mocker = tu.MockKube()
# execute kubectl commands
# default namespace is nuvolaris, you can change with keyword arg namespace
# default output is text
# if you specify jsonpath it will filter and parse the json output
# returns exceptions if errors
def kubectl(*args, namespace="nuvolaris", input=None, jsonpath=None):
# support for mocked requests
mres = mocker.invoke(*args)
if mres:
mocker.save(input)
return mres
cmd = ["kubectl", "-n", namespace]
cmd += list(args)
if jsonpath:
cmd += ["-o", "jsonpath-as-json=%s" % jsonpath]
# if is a string, convert input in bytes
try: input = input.encode('utf-8')
except: pass
# executing
logging.debug(cmd)
res = subprocess.run(cmd, capture_output=True, input=input)
global returncode, output, error
returncode = res.returncode
output = res.stdout.decode()
error = res.stderr.decode()
if res.returncode == 0:
if jsonpath:
try:
parsed = json.loads(output)
logging.debug("result: %s", json.dumps(parsed, indent=2))
return parsed
except Exception as e:
logging.info(output)
logging.info(e)
return e
else:
return output
logging.info(f"Error: kubectl f{cmd} input='{input}' output='{output}' error='{error}'")
raise Exception(error)
# create a configmap from keyword arguments
def configMap(name, **kwargs):
"""
>>> import nuvolaris.kube as kube, nuvolaris.testutil as tu
>>> tu.grep(kube.configMap("hello", value="world"), "kind:|name:|value:", sort=True)
kind: ConfigMap
name: hello
value: world
>>> tu.grep(kube.configMap("hello", **{"file.js":"function", "file.py": "def"}), "file.", sort=True)
file.js: function
file.py: def
"""
out = yaml.safe_load("""apiVersion: v1
kind: ConfigMap
metadata:
name: %s
data: {}
"""% name)
for key, value in kwargs.items():
out['data'][key] = value
return yaml.dump(out)
# delete an object
def delete(obj, namespace="nuvolaris"):
# tested with apply
if not isinstance(obj, str):
obj = json.dumps(obj)
return kubectl("delete", "-f", "-", namespace=namespace, input=obj)
# shortcut
def ctl(arg, jsonpath='{@}', flatten=False):
import flatdict, json
data = kubectl(*arg.split(), jsonpath=jsonpath)
if flatten:
return dict(flatdict.FlatterDict(data, delimiter="."))
return data
# apply an object
def apply(obj, namespace="nuvolaris"):
if not isinstance(obj, str):
obj = json.dumps(obj)
return kubectl("apply", "-f", "-", namespace=namespace, input=obj)
# apply an object
def applyTemplate(name, data, namespace="nuvolaris"):
obj = tpl.expand_template(name, data)
return kubectl("apply", "-f", "-", namespace=namespace, input=obj)
# delete an object
def deleteTemplate(name, data, namespace="nuvolaris"):
obj = tpl.expand_template(name, data)
return kubectl("delete", "-f", "-", namespace=namespace, input=obj)
def get(name):
try:
return json.loads(kubectl("get", name, "-ojson"))
except:
return None
def wait(name, condition, timeout="600s"):
return kubectl("wait", name, f"--for={condition}", f"--timeout={timeout}")
# patch an object
def patch(name, data, namespace="nuvolaris", tpe="merge"):
if not type(data) == str:
data = json.dumps(data)
res = kubectl("patch", name, "--type", tpe, "-p", data)
return res |
"""
Handling a Bank Account
"""
class Account: # parent class
def __init__(self, title=None, balance=0):
self.title = title
self.balance = balance
# withdrawal method subtracts the amount from the balance
def withdrawal(self, amount):
self.balance = self.balance - amount
# deposit method adds the amount to the balance
def deposit(self, amount):
self.balance = self.balance + amount
# this method just returns the value of balance
def getBalance(self):
return self.balance
class SavingsAccount(Account):
def __init__(self, title=None, balance=0, interestRate=0):
super().__init__(title, balance)
self.interestRate = interestRate
# computes interest amount using the interest rate
def interestAmount(self):
return (self.balance * self.interestRate / 100)
obj1 = SavingsAccount("Steve", 5000, 10)
print("Initial Balance:", obj1.getBalance())
obj1.withdrawal(1000)
print("Balance after withdrawal:", obj1.getBalance())
obj1.deposit(500)
print("Balance after deposit:", obj1.getBalance())
print("Interest on current balance:", obj1.interestAmount())
|
import os
import string
from typing import Any, Union
def random_string(
length: int = 64, characters: str = string.ascii_letters + string.digits
) -> str:
result_str = "".join(random_choice(characters) for i in range(length))
return result_str
def random_int() -> int:
"""
Select a random integer (64bit)
"""
return bytes_to_int(os.urandom(8))
def random_range(min: int, max: int) -> int:
"""
Select a random integer between two numbers
"""
return (random_int() % ((max + 1) - min)) + min
def bytes_to_int(bytes: bytes) -> int:
"""
Helper function, convert set of bytes to an integer
"""
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
def random_choice(options: Union[list, str]) -> Any:
"""
Select an item from a list of values
"""
r = random_range(0, len(options) - 1)
return options[r]
|
from pathlib import Path
import json
import pandas as pd
from sklearn.utils import Bunch
STRATEGY_FILE = "benchmark_strategies.json"
PHENOTYPE_INFO = {
"ds000228":
{"columns": ["Age", "Gender"],
"replace": {'Age': 'age', 'Gender': 'gender'}},
"ds000030":
{"columns": ["age", "gender"]},
}
def fetch_fmriprep_derivative(dataset_name, participant_tsv_path, path_fmriprep_derivative,
specifier, subject=None, space="MNI152NLin2009cAsym", aroma=False):
"""Fetch fmriprep derivative and return nilearn.dataset.fetch* like output.
Load functional image, confounds, and participants.tsv only.
Parameters
----------
dataset_name : str
Dataset name.
participant_tsv_path : pathlib.Path
A pathlib path point to the BIDS participants file.
path_fmriprep_derivative : pathlib.Path
A pathlib path point to the BIDS participants file.
specifier : string
Text in a fmriprep file name, in between sub-<subject>_ses-<session>_
and `space-<template>`.
subject : string, default None
subject id. If none, return all results.
space : string, default "MNI152NLin2009cAsym"
Template flow tempate name in fmriprep output.
aroma : boolean, default False
Use ICA-AROMA processed data or not.
Returns
-------
sklearn.utils.Bunch
nilearn.dataset.fetch* like output.
"""
# participants tsv from the main dataset
if not participant_tsv_path.is_file():
raise FileNotFoundError(
f"Cannot find {participant_tsv_path}")
if participant_tsv_path.name != "participants.tsv":
raise FileNotFoundError(
f"File {participant_tsv_path} is not a BIDS participant file.")
participant_tsv = pd.read_csv(participant_tsv_path,
index_col=["participant_id"],
sep="\t")
# images and confound files
if subject is None:
subject_dirs = path_fmriprep_derivative.glob("sub-*/")
else:
subject_dirs = path_fmriprep_derivative.glob(f"sub-{subject}/")
func_img_path, confounds_tsv_path, include_subjects = [], [], []
for subject_dir in subject_dirs:
subject = subject_dir.name
desc = "smoothAROMAnonaggr" if aroma else "preproc"
space = "MNI152NLin6Asym" if aroma else space
cur_func = (subject_dir / "func" /
f"{subject}_{specifier}_space-{space}_desc-{desc}_bold.nii.gz")
cur_confound = (subject_dir / "func" /
f"{subject}_{specifier}_desc-confounds_timeseries.tsv")
if cur_func.is_file() and cur_confound.is_file():
func_img_path.append(str(cur_func))
confounds_tsv_path.append(str(cur_confound))
include_subjects.append(subject)
return Bunch(
dataset_name=dataset_name,
func=func_img_path,
confounds=confounds_tsv_path,
phenotypic=participant_tsv.loc[include_subjects, :]
)
def get_prepro_strategy(strategy_name=None):
"""Select a sinlge preprocessing strategy and associated parametes."""
strategy_file = Path(__file__).parent / STRATEGY_FILE
with open(strategy_file, "r") as file:
benchmark_strategies = json.load(file)
if isinstance(strategy_name, str) and strategy_name not in benchmark_strategies:
raise NotImplementedError(
f"Strategy '{strategy_name}' is not implemented. Select from the"
f"following: {[*benchmark_strategies]}"
)
if strategy_name is None:
print("Process all strategies.")
return benchmark_strategies
(f"Process strategy '{strategy_name}'.")
return {strategy_name: benchmark_strategies[strategy_name]}
def generate_movement_summary(dataset_name, data, output):
"""Generate and save movement stats and phenotype for openneuro datasets.
Parameters
----------
dataset_name : str
Dataset name.
data : sklearn.utils.Bunch
Dataset retreived through fmriprep_denoise.fetch_fmriprep_derivative
output : str
Output directory.
"""
movement = _phenotype_movement(data)
movement = movement.sort_index()
movement.to_csv( output / f"dataset-{dataset_name}_desc-movement_phenotype.tsv", sep='\t')
print("Generate movement stats.")
def _phenotype_movement(data):
"""Retreive movement stats and phenotype for openneuro datasets."""
# get motion QC related metrics from confound files
group_mean_fd = pd.DataFrame()
group_mean_fd.index = group_mean_fd.index.set_names("participant_id")
for confounds in data.confounds:
subject_id = confounds.split("/")[-1].split("_")[0]
confounds = pd.read_csv(confounds, sep="\t")
mean_fd = confounds["framewise_displacement"].mean()
group_mean_fd.loc[subject_id, "mean_framewise_displacement"] = mean_fd
# load gender and age as confounds for the developmental dataset
participants = data.phenotypic.copy()
covar = participants.loc[:, PHENOTYPE_INFO[data.dataset_name]['columns']]
fix_col_name = PHENOTYPE_INFO[data.dataset_name].get("replace", False)
if isinstance(fix_col_name, dict):
covar = covar.rename(columns=fix_col_name)
covar.loc[covar['gender'] == 'F', 'gender'] = 1
covar.loc[covar['gender'] == 'M', 'gender'] = 0
covar['gender'] = covar['gender'].astype('float')
return pd.concat((group_mean_fd, covar), axis=1)
|
#! /usr/bin/env python3
from json import loads
from biowardrobe_migration.tests.outputs import chipseq_se
from biowardrobe_migration.utils.files import norm_path, get_broken_outputs
correct, broken = get_broken_outputs(loads(chipseq_se))
print("CORERCT:", correct)
print("BROKEN:", broken)
|
r"""
Store input key strokes if we did read more than was required.
The input classes `Vt100Input` and `Win32Input` read the input text in chunks
of a few kilobytes. This means that if we read input from stdin, it could be
that we read a couple of lines (with newlines in between) at once.
This creates a problem: potentially, we read too much from stdin. Sometimes
people paste several lines at once because they paste input in a REPL and
expect each input() call to process one line. Or they rely on type ahead
because the application can't keep up with the processing.
However, we need to read input in bigger chunks. We need this mostly to support
pasting of larger chunks of text. We don't want everything to become
unresponsive because we:
- read one character;
- parse one character;
- call the key binding, which does a string operation with one character;
- and render the user interface.
Doing text operations on single characters is very inefficient in Python, so we
prefer to work on bigger chunks of text. This is why we have to read the input
in bigger chunks.
Further, line buffering is also not an option, because it doesn't work well in
the architecture. We use lower level Posix APIs, that work better with the
event loop and so on. In fact, there is also nothing that defines that only \n
can accept the input, you could create a key binding for any key to accept the
input.
To support type ahead, this module will store all the key strokes that were
read too early, so that they can be feed into to the next `prompt()` call or to
the next quo `Application`.
"""
from collections import defaultdict
from typing import Dict, List
from quo.keys.key_binding import KeyPress
from .core import Input
__all__ = [
"store_typeahead",
"get_typeahead",
"clear_typeahead",
]
_buffer: Dict[str, List[KeyPress]] = defaultdict(list)
def store_typeahead(input_obj: Input, key_presses: List[KeyPress]) -> None:
"""
Insert typeahead key presses for the given input.
"""
global _buffer
key = input_obj.typeahead_hash()
_buffer[key].extend(key_presses)
def get_typeahead(input_obj: Input) -> List[KeyPress]:
"""
Retrieve typeahead and reset the buffer for this input.
"""
global _buffer
key = input_obj.typeahead_hash()
result = _buffer[key]
_buffer[key] = []
return result
def clear_typeahead(input_obj: Input) -> None:
"""
Clear typeahead buffer.
"""
global _buffer
key = input_obj.typeahead_hash()
_buffer[key] = []
|
"""This is an example of interface module."""
from abc import ABC, abstractmethod
class Interface(ABC):
"""Interface example."""
@abstractmethod
def add(self, a, b):
pass
@abstractmethod
def add_positional(self, a, b, c, d):
pass
# @abstractmethod
# def add_default(self, a=1, b=2, c=3):
# pass
# @abstractmethod
# def add_default_2(self, a=1, b=2, c=3, d=4, e=5, f=6):
# pass
# @abstractmethod
# def add_default_3(self, a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8):
# pass
# @abstractmethod
# def add_list(self, *args):
# pass
# @abstractmethod
# def add_dict(self, **kargs):
# pass
# @abstractmethod
# def add_positionald_and_default(self, a, b, c=3, d=4):
# pass
# @abstractmethod
# def add_positionald_and_list(self, a, b, *args):
# pass
# @abstractmethod
# def add_positional_and_dict(self, a, b, **kargs):
# pass
# @abstractmethod
# def add_default_and_list(self, a=1, b=2, *args):
# pass
# @abstractmethod
# def add_default_and_dict(self, a=1, b=2, **kargs):
# pass
# @abstractmethod
# def add_list_and_dict(self, *args, **kargs):
# pass
# @abstractmethod
# def add_positional_default_and_list(self, a, b=2, *args):
# pass
# @abstractmethod
# def add_positional_default_and_dict(self, a, b=2, **kargs):
# pass
# @abstractmethod
# def add_positional_list_and_dict(self, a, b, *args, **kargs):
# pass
# @abstractmethod
# def add_default_list_and_dict(self, a=1, b=2, *args, **kargs):
# pass
# @abstractmethod
# def add_positional_default_list_and_dict(self, a, b=2, *args, **kargs):
# pass
|
import pytest
from flake8_import_conventions.errors import generate_message
@pytest.mark.parametrize(
"number,package_number,alias,expected",
[
(
1,
"altair",
"alt",
"IC001 altair should be imported as `import altair as alt`",
),
(
2,
"numpy",
"np",
"IC002 numpy should be imported as `import numpy as np`",
),
(
3,
"pandas",
"pd",
"IC003 pandas should be imported as `import pandas as pd`",
),
(
4,
"seaborn",
"sns",
"IC004 seaborn should be imported as `import seaborn as sns`",
),
],
)
def test_generate_message(number, package_number, alias, expected):
assert generate_message(number, package_number, alias) == expected
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.