ngram
listlengths
0
82k
[ "set, and returns the loss. Args: model: The model to", "test set, and returns the loss. Args: model: The model", "of the test set. Returns: The loss on the test", "<gh_stars>0 def default_evaluator(model, X_test, y_test): \"\"\"A simple evaluator that takes", "y_test): \"\"\"A simple evaluator that takes in a model, and", "X_test: The features matrix of the test set. y_test: The", "The loss on the test set. \"\"\" return model.evaluate(X_test, y_test,", "matrix of the test set. y_test: The one-hot labels matrix", "Args: model: The model to evaluate. X_test: The features matrix", "The features matrix of the test set. y_test: The one-hot", "a model, and a test set, and returns the loss.", "the test set. y_test: The one-hot labels matrix of the", "\"\"\"A simple evaluator that takes in a model, and a", "in a model, and a test set, and returns the", "evaluator that takes in a model, and a test set,", "matrix of the test set. Returns: The loss on the", "set. Returns: The loss on the test set. \"\"\" return", "evaluate. X_test: The features matrix of the test set. y_test:", "y_test: The one-hot labels matrix of the test set. Returns:", "def default_evaluator(model, X_test, y_test): \"\"\"A simple evaluator that takes in", "simple evaluator that takes in a model, and a test", "and a test set, and returns the loss. Args: model:", "set. y_test: The one-hot labels matrix of the test set.", "Returns: The loss on the test set. \"\"\" return model.evaluate(X_test,", "X_test, y_test): \"\"\"A simple evaluator that takes in a model,", "a test set, and returns the loss. Args: model: The", "loss on the test set. \"\"\" return model.evaluate(X_test, y_test, verbose=0)[0]", "model to evaluate. X_test: The features matrix of the test", "takes in a model, and a test set, and returns", "labels matrix of the test set. Returns: The loss on", "to evaluate. X_test: The features matrix of the test set.", "test set. Returns: The loss on the test set. \"\"\"", "model, and a test set, and returns the loss. Args:", "The one-hot labels matrix of the test set. Returns: The", "the test set. Returns: The loss on the test set.", "features matrix of the test set. y_test: The one-hot labels", "one-hot labels matrix of the test set. Returns: The loss", "and returns the loss. Args: model: The model to evaluate.", "loss. Args: model: The model to evaluate. X_test: The features", "The model to evaluate. X_test: The features matrix of the", "of the test set. y_test: The one-hot labels matrix of", "default_evaluator(model, X_test, y_test): \"\"\"A simple evaluator that takes in a", "test set. y_test: The one-hot labels matrix of the test", "model: The model to evaluate. X_test: The features matrix of", "returns the loss. Args: model: The model to evaluate. X_test:", "the loss. Args: model: The model to evaluate. X_test: The", "that takes in a model, and a test set, and" ]
[ "class Yolov3(object): def __init__(self): self.num=0 self.input_size=[8,16,32] def __iter__(self): return self", "= random.choice(self.input_size) self.num=self.num+1 if self.num<3: return a else: raise StopIteration", "self.num=self.num+1 if self.num<3: return a else: raise StopIteration yolo=Yolov3() for", "self.input_size=[8,16,32] def __iter__(self): return self def __next__(self): a = random.choice(self.input_size)", "self.num<3: return a else: raise StopIteration yolo=Yolov3() for data in", "random.choice(self.input_size) self.num=self.num+1 if self.num<3: return a else: raise StopIteration yolo=Yolov3()", "def __iter__(self): return self def __next__(self): a = random.choice(self.input_size) self.num=self.num+1", "random class Yolov3(object): def __init__(self): self.num=0 self.input_size=[8,16,32] def __iter__(self): return", "self.num=0 self.input_size=[8,16,32] def __iter__(self): return self def __next__(self): a =", "__next__(self): a = random.choice(self.input_size) self.num=self.num+1 if self.num<3: return a else:", "a else: raise StopIteration yolo=Yolov3() for data in yolo: print(data)", "def __next__(self): a = random.choice(self.input_size) self.num=self.num+1 if self.num<3: return a", "def __init__(self): self.num=0 self.input_size=[8,16,32] def __iter__(self): return self def __next__(self):", "__init__(self): self.num=0 self.input_size=[8,16,32] def __iter__(self): return self def __next__(self): a", "return self def __next__(self): a = random.choice(self.input_size) self.num=self.num+1 if self.num<3:", "Yolov3(object): def __init__(self): self.num=0 self.input_size=[8,16,32] def __iter__(self): return self def", "a = random.choice(self.input_size) self.num=self.num+1 if self.num<3: return a else: raise", "__iter__(self): return self def __next__(self): a = random.choice(self.input_size) self.num=self.num+1 if", "self def __next__(self): a = random.choice(self.input_size) self.num=self.num+1 if self.num<3: return", "return a else: raise StopIteration yolo=Yolov3() for data in yolo:", "import random class Yolov3(object): def __init__(self): self.num=0 self.input_size=[8,16,32] def __iter__(self):", "if self.num<3: return a else: raise StopIteration yolo=Yolov3() for data" ]
[ "np.sign(x) * np.log(1 + mu * np.abs(x)) / np.log(1 +", "hp from scipy.signal import lfilter import soundfile as sf def", "amp_to_db(x): return 20 * np.log10(np.maximum(1e-5, x)) def db_to_amp(x): return np.power(10.0,", "amp_mel = db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft,", "* (2**bits - 1) / 2 return x.clip(0, 2**bits -", "+ 2**15 coarse = unsigned // 256 fine = unsigned", "from_labels: y = label_2_float(y, math.log2(mu)) mu = mu - 1", "1) * -hp.min_level_db) + hp.min_level_db def amp_to_db(x): return 20 *", "# librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x): unsigned", "np import librosa from utils import hparams as hp from", "return coarse * 256 + fine - 2**15 def encode_16bits(x):", "librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x): unsigned =", "sense if from_labels: y = label_2_float(y, math.log2(mu)) mu = mu", "S = amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def stft(y): return librosa.stft( y=y,", "256 return coarse, fine def combine_signal(coarse, fine): return coarse *", "makes no sense if from_labels: y = label_2_float(y, math.log2(mu)) mu", "def denormalize(S): return (np.clip(S, 0, 1) * -hp.min_level_db) + hp.min_level_db", "no sense if from_labels: y = label_2_float(y, math.log2(mu)) mu =", "= db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin)", "/ 2 * mu + 0.5) def decode_mu_law(y, mu, from_labels=True):", "return np.power(10.0, x * 0.05) def spectrogram(y): D = stft(y)", "S = amp_to_db(np.abs(D)) - hp.ref_level_db return normalize(S) def melspectrogram(y): D", "soundfile as sf def label_2_float(x, bits): return 2 * x", "mu = mu - 1 fx = np.sign(x) * np.log(1", "mu * ((1 + mu) ** np.abs(y) - 1) return", "return x def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim phase reconstruction to", "mu - 1 x = np.sign(y) / mu * ((1", "np.abs(y) - 1) return x def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim", "np.abs(x)) / np.log(1 + mu) return np.floor((fx + 1) /", "to convert from a normalized mel spectrogram back into a", "return lfilter([1, -hp.preemphasis], [1], x) def de_emphasis(x): return lfilter([1], [1,", "return 20 * np.log10(np.maximum(1e-5, x)) def db_to_amp(x): return np.power(10.0, x", "from utils import hparams as hp from scipy.signal import lfilter", "waveform.\"\"\" denormalized = denormalize(mel) amp_mel = db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft(", "= amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def stft(y): return librosa.stft( y=y, n_fft=hp.n_fft,", "unsigned = x + 2**15 coarse = unsigned // 256", "spectrogram back into a waveform.\"\"\" denormalized = denormalize(mel) amp_mel =", "numpy as np import librosa from utils import hparams as", "back into a waveform.\"\"\" denormalized = denormalize(mel) amp_mel = db_to_amp(denormalized)", "from scipy.signal import lfilter import soundfile as sf def label_2_float(x,", "n_iter=32): \"\"\"Uses Griffin-Lim phase reconstruction to convert from a normalized", "-hp.min_level_db, 0, 1) def denormalize(S): return (np.clip(S, 0, 1) *", "0, 1) * -hp.min_level_db) + hp.min_level_db def amp_to_db(x): return 20", "librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x): return lfilter([1, -hp.preemphasis],", "= mu - 1 fx = np.sign(x) * np.log(1 +", "* 2**15, -2**15, 2**15 - 1).astype(np.int16) def linear_to_mel(spectrogram): return librosa.feature.melspectrogram(", "* np.log10(np.maximum(1e-5, x)) def db_to_amp(x): return np.power(10.0, x * 0.05)", "** np.abs(y) - 1) return x def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses", "1) return x def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim phase reconstruction", "(2**bits - 1) / 2 return x.clip(0, 2**bits - 1)", "samplerate=hp.sample_rate) def split_signal(x): unsigned = x + 2**15 coarse =", "hp.ref_level_db return normalize(S) def melspectrogram(y): D = stft(y) S =", "x / (2**bits - 1.) - 1. def float_2_label(x, bits):", "stft(y) S = amp_to_db(np.abs(D)) - hp.ref_level_db return normalize(S) def melspectrogram(y):", "combine_signal(coarse, fine): return coarse * 256 + fine - 2**15", "def pre_emphasis(x): return lfilter([1, -hp.preemphasis], [1], x) def de_emphasis(x): return", "def combine_signal(coarse, fine): return coarse * 256 + fine -", "hp.min_level_db) / -hp.min_level_db, 0, 1) def denormalize(S): return (np.clip(S, 0,", "1) def denormalize(S): return (np.clip(S, 0, 1) * -hp.min_level_db) +", "2**bits - 1) def load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x,", "hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def normalize(S): return np.clip((S - hp.min_level_db)", "fmin=hp.fmin) wav = librosa.core.griffinlim( S, n_iter=n_iter, hop_length=hp.hop_length, win_length=hp.win_length) return wav", "amp_to_db(np.abs(D)) - hp.ref_level_db return normalize(S) def melspectrogram(y): D = stft(y)", "/ -hp.min_level_db, 0, 1) def denormalize(S): return (np.clip(S, 0, 1)", "import numpy as np import librosa from utils import hparams", "- 1).astype(np.int16) def linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels,", "y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x): return lfilter([1, -hp.preemphasis], [1],", "return 2 * x / (2**bits - 1.) - 1.", "mu): mu = mu - 1 fx = np.sign(x) *", "denormalize(S): return (np.clip(S, 0, 1) * -hp.min_level_db) + hp.min_level_db def", "fine - 2**15 def encode_16bits(x): return np.clip(x * 2**15, -2**15,", "- 1. def float_2_label(x, bits): assert abs(x).max() <= 1.0 x", "2 return x.clip(0, 2**bits - 1) def load_wav(path): return librosa.load(path,", "return librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x): return lfilter([1,", "n_fft=hp.n_fft, fmin=hp.fmin) wav = librosa.core.griffinlim( S, n_iter=n_iter, hop_length=hp.hop_length, win_length=hp.win_length) return", "denormalized = denormalize(mel) amp_mel = db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft( amp_mel,", "TODO: get rid of log2 - makes no sense if", "convert from a normalized mel spectrogram back into a waveform.\"\"\"", "encode_16bits(x): return np.clip(x * 2**15, -2**15, 2**15 - 1).astype(np.int16) def", "= librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav = librosa.core.griffinlim(", "build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def normalize(S): return", "- 1 fx = np.sign(x) * np.log(1 + mu *", "as hp from scipy.signal import lfilter import soundfile as sf", "x def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim phase reconstruction to convert", "- 1) def load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x, path):", "2 * mu + 0.5) def decode_mu_law(y, mu, from_labels=True): #", "librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x, path): # librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path,", "assert abs(x).max() <= 1.0 x = (x + 1.) *", "= (x + 1.) * (2**bits - 1) / 2", "2**15, -2**15, 2**15 - 1).astype(np.int16) def linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram,", "# TODO: get rid of log2 - makes no sense", "+ hp.min_level_db def amp_to_db(x): return 20 * np.log10(np.maximum(1e-5, x)) def", "* ((1 + mu) ** np.abs(y) - 1) return x", "def de_emphasis(x): return lfilter([1], [1, -hp.preemphasis], x) def encode_mu_law(x, mu):", "- 1.) - 1. def float_2_label(x, bits): assert abs(x).max() <=", "fine = unsigned % 256 return coarse, fine def combine_signal(coarse,", "n_mels=hp.num_mels, fmin=hp.fmin) ''' def build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin)", "/ (2**bits - 1.) - 1. def float_2_label(x, bits): assert", "melspectrogram(y): D = stft(y) S = amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def", "db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav", "lfilter import soundfile as sf def label_2_float(x, bits): return 2", "return normalize(S) def stft(y): return librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length)", "D = stft(y) S = amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def stft(y):", "np.log(1 + mu) return np.floor((fx + 1) / 2 *", "import hparams as hp from scipy.signal import lfilter import soundfile", "sf def label_2_float(x, bits): return 2 * x / (2**bits", "unsigned % 256 return coarse, fine def combine_signal(coarse, fine): return", "(2**bits - 1.) - 1. def float_2_label(x, bits): assert abs(x).max()", "* x / (2**bits - 1.) - 1. def float_2_label(x,", "2**15 coarse = unsigned // 256 fine = unsigned %", "* mu + 0.5) def decode_mu_law(y, mu, from_labels=True): # TODO:", "def load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x, path): # librosa.output.write_wav(path,", "def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim phase reconstruction to convert from", "= mu - 1 x = np.sign(y) / mu *", "return np.clip((S - hp.min_level_db) / -hp.min_level_db, 0, 1) def denormalize(S):", "+ 0.5) def decode_mu_law(y, mu, from_labels=True): # TODO: get rid", "/ mu * ((1 + mu) ** np.abs(y) - 1)", "bits): assert abs(x).max() <= 1.0 x = (x + 1.)", "a normalized mel spectrogram back into a waveform.\"\"\" denormalized =", "= np.sign(y) / mu * ((1 + mu) ** np.abs(y)", "D = stft(y) S = amp_to_db(np.abs(D)) - hp.ref_level_db return normalize(S)", "2**15 def encode_16bits(x): return np.clip(x * 2**15, -2**15, 2**15 -", "// 256 fine = unsigned % 256 return coarse, fine", "/ np.log(1 + mu) return np.floor((fx + 1) / 2", "fx = np.sign(x) * np.log(1 + mu * np.abs(x)) /", "np.floor((fx + 1) / 2 * mu + 0.5) def", "mu + 0.5) def decode_mu_law(y, mu, from_labels=True): # TODO: get", "hparams as hp from scipy.signal import lfilter import soundfile as", "1.) - 1. def float_2_label(x, bits): assert abs(x).max() <= 1.0", "mu - 1 fx = np.sign(x) * np.log(1 + mu", "+ mu * np.abs(x)) / np.log(1 + mu) return np.floor((fx", "''' def normalize(S): return np.clip((S - hp.min_level_db) / -hp.min_level_db, 0,", "import math import numpy as np import librosa from utils", "math.log2(mu)) mu = mu - 1 x = np.sign(y) /", "* np.abs(x)) / np.log(1 + mu) return np.floor((fx + 1)", "n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x): return lfilter([1, -hp.preemphasis], [1], x)", "normalized mel spectrogram back into a waveform.\"\"\" denormalized = denormalize(mel)", "def build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def normalize(S):", "n_mels=hp.num_mels, fmin=hp.fmin) ''' def normalize(S): return np.clip((S - hp.min_level_db) /", "* 256 + fine - 2**15 def encode_16bits(x): return np.clip(x", "return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def normalize(S): return np.clip((S", "scipy.signal import lfilter import soundfile as sf def label_2_float(x, bits):", "from_labels=True): # TODO: get rid of log2 - makes no", "- makes no sense if from_labels: y = label_2_float(y, math.log2(mu))", "= np.sign(x) * np.log(1 + mu * np.abs(x)) / np.log(1", "mu = mu - 1 x = np.sign(y) / mu", "save_wav(x, path): # librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def", "librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def build_mel_basis(): return", "linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def", "def float_2_label(x, bits): assert abs(x).max() <= 1.0 x = (x", "librosa from utils import hparams as hp from scipy.signal import", "label_2_float(x, bits): return 2 * x / (2**bits - 1.)", "def split_signal(x): unsigned = x + 2**15 coarse = unsigned", "= stft(y) S = amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def stft(y): return", "-hp.preemphasis], x) def encode_mu_law(x, mu): mu = mu - 1", "def save_wav(x, path): # librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate)", "+ 1.) * (2**bits - 1) / 2 return x.clip(0,", "\"\"\"Uses Griffin-Lim phase reconstruction to convert from a normalized mel", "return normalize(S) def melspectrogram(y): D = stft(y) S = amp_to_db(linear_to_mel(np.abs(D)))", "def normalize(S): return np.clip((S - hp.min_level_db) / -hp.min_level_db, 0, 1)", "256 fine = unsigned % 256 return coarse, fine def", "20 * np.log10(np.maximum(1e-5, x)) def db_to_amp(x): return np.power(10.0, x *", "coarse * 256 + fine - 2**15 def encode_16bits(x): return", "bits): return 2 * x / (2**bits - 1.) -", "x = (x + 1.) * (2**bits - 1) /", "-hp.min_level_db) + hp.min_level_db def amp_to_db(x): return 20 * np.log10(np.maximum(1e-5, x))", "0.05) def spectrogram(y): D = stft(y) S = amp_to_db(np.abs(D)) -", "+ mu) ** np.abs(y) - 1) return x def reconstruct_waveform(mel,", "Griffin-Lim phase reconstruction to convert from a normalized mel spectrogram", "return x.clip(0, 2**bits - 1) def load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0]", "amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav = librosa.core.griffinlim( S, n_iter=n_iter,", "sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x): unsigned = x +", "np.log10(np.maximum(1e-5, x)) def db_to_amp(x): return np.power(10.0, x * 0.05) def", "stft(y): return librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x): return", "def db_to_amp(x): return np.power(10.0, x * 0.05) def spectrogram(y): D", "from a normalized mel spectrogram back into a waveform.\"\"\" denormalized", "- 1) / 2 return x.clip(0, 2**bits - 1) def", "np.clip((S - hp.min_level_db) / -hp.min_level_db, 0, 1) def denormalize(S): return", "return lfilter([1], [1, -hp.preemphasis], x) def encode_mu_law(x, mu): mu =", "((1 + mu) ** np.abs(y) - 1) return x def", "= x + 2**15 coarse = unsigned // 256 fine", "1) / 2 return x.clip(0, 2**bits - 1) def load_wav(path):", "import librosa from utils import hparams as hp from scipy.signal", "1.) * (2**bits - 1) / 2 return x.clip(0, 2**bits", "- 2**15 def encode_16bits(x): return np.clip(x * 2**15, -2**15, 2**15", "win_length=hp.win_length) def pre_emphasis(x): return lfilter([1, -hp.preemphasis], [1], x) def de_emphasis(x):", "mel spectrogram back into a waveform.\"\"\" denormalized = denormalize(mel) amp_mel", "= amp_to_db(np.abs(D)) - hp.ref_level_db return normalize(S) def melspectrogram(y): D =", "lfilter([1], [1, -hp.preemphasis], x) def encode_mu_law(x, mu): mu = mu", "np.clip(x * 2**15, -2**15, 2**15 - 1).astype(np.int16) def linear_to_mel(spectrogram): return", "librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav = librosa.core.griffinlim( S,", "de_emphasis(x): return lfilter([1], [1, -hp.preemphasis], x) def encode_mu_law(x, mu): mu", "lfilter([1, -hp.preemphasis], [1], x) def de_emphasis(x): return lfilter([1], [1, -hp.preemphasis],", "reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim phase reconstruction to convert from a", "load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x, path): # librosa.output.write_wav(path, x.astype(np.float32),", "of log2 - makes no sense if from_labels: y =", "- 1) return x def reconstruct_waveform(mel, n_iter=32): \"\"\"Uses Griffin-Lim phase", "- 1 x = np.sign(y) / mu * ((1 +", "def stft(y): return librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x):", "def decode_mu_law(y, mu, from_labels=True): # TODO: get rid of log2", "label_2_float(y, math.log2(mu)) mu = mu - 1 x = np.sign(y)", "* 0.05) def spectrogram(y): D = stft(y) S = amp_to_db(np.abs(D))", "* -hp.min_level_db) + hp.min_level_db def amp_to_db(x): return 20 * np.log10(np.maximum(1e-5,", "0, 1) def denormalize(S): return (np.clip(S, 0, 1) * -hp.min_level_db)", "into a waveform.\"\"\" denormalized = denormalize(mel) amp_mel = db_to_amp(denormalized) S", "reconstruction to convert from a normalized mel spectrogram back into", "mu * np.abs(x)) / np.log(1 + mu) return np.floor((fx +", "fine): return coarse * 256 + fine - 2**15 def", "if from_labels: y = label_2_float(y, math.log2(mu)) mu = mu -", "/ 2 return x.clip(0, 2**bits - 1) def load_wav(path): return", "<reponame>huchenxucs/WaveRNN import math import numpy as np import librosa from", "def linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) '''", "x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x): unsigned = x + 2**15 coarse", "rid of log2 - makes no sense if from_labels: y", "1. def float_2_label(x, bits): assert abs(x).max() <= 1.0 x =", "1.0 x = (x + 1.) * (2**bits - 1)", "return (np.clip(S, 0, 1) * -hp.min_level_db) + hp.min_level_db def amp_to_db(x):", "x.clip(0, 2**bits - 1) def load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0] def", "utils import hparams as hp from scipy.signal import lfilter import", "spectrogram(y): D = stft(y) S = amp_to_db(np.abs(D)) - hp.ref_level_db return", "(x + 1.) * (2**bits - 1) / 2 return", "1).astype(np.int16) def linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin)", "encode_mu_law(x, mu): mu = mu - 1 fx = np.sign(x)", "''' def build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def", "import soundfile as sf def label_2_float(x, bits): return 2 *", "sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x): unsigned = x + 2**15", "y = label_2_float(y, math.log2(mu)) mu = mu - 1 x", "def label_2_float(x, bits): return 2 * x / (2**bits -", "S = librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav =", "normalize(S) def stft(y): return librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length, win_length=hp.win_length) def", "normalize(S) def melspectrogram(y): D = stft(y) S = amp_to_db(linear_to_mel(np.abs(D))) return", "return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def build_mel_basis():", "mu) ** np.abs(y) - 1) return x def reconstruct_waveform(mel, n_iter=32):", "% 256 return coarse, fine def combine_signal(coarse, fine): return coarse", "amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def stft(y): return librosa.stft( y=y, n_fft=hp.n_fft, hop_length=hp.hop_length,", "get rid of log2 - makes no sense if from_labels:", "float_2_label(x, bits): assert abs(x).max() <= 1.0 x = (x +", "fine def combine_signal(coarse, fine): return coarse * 256 + fine", "return np.clip(x * 2**15, -2**15, 2**15 - 1).astype(np.int16) def linear_to_mel(spectrogram):", "power=1, sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav = librosa.core.griffinlim( S, n_iter=n_iter, hop_length=hp.hop_length,", "def amp_to_db(x): return 20 * np.log10(np.maximum(1e-5, x)) def db_to_amp(x): return", "- hp.min_level_db) / -hp.min_level_db, 0, 1) def denormalize(S): return (np.clip(S,", "hop_length=hp.hop_length, win_length=hp.win_length) def pre_emphasis(x): return lfilter([1, -hp.preemphasis], [1], x) def", "log2 - makes no sense if from_labels: y = label_2_float(y,", "sr=hp.sample_rate, n_fft=hp.n_fft, fmin=hp.fmin) wav = librosa.core.griffinlim( S, n_iter=n_iter, hop_length=hp.hop_length, win_length=hp.win_length)", "(np.clip(S, 0, 1) * -hp.min_level_db) + hp.min_level_db def amp_to_db(x): return", "as np import librosa from utils import hparams as hp", "np.log(1 + mu * np.abs(x)) / np.log(1 + mu) return", "sr=hp.sample_rate)[0] def save_wav(x, path): # librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32),", "x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x): unsigned = x", "sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft,", "def spectrogram(y): D = stft(y) S = amp_to_db(np.abs(D)) - hp.ref_level_db", "x) def de_emphasis(x): return lfilter([1], [1, -hp.preemphasis], x) def encode_mu_law(x,", "1) def load_wav(path): return librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x, path): #", "S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def build_mel_basis(): return librosa.filters.mel(hp.sample_rate,", "def encode_mu_law(x, mu): mu = mu - 1 fx =", "math import numpy as np import librosa from utils import", "1 x = np.sign(y) / mu * ((1 + mu)", "x = np.sign(y) / mu * ((1 + mu) **", "np.power(10.0, x * 0.05) def spectrogram(y): D = stft(y) S", "librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def normalize(S): return np.clip((S -", "2 * x / (2**bits - 1.) - 1. def", "x)) def db_to_amp(x): return np.power(10.0, x * 0.05) def spectrogram(y):", "256 + fine - 2**15 def encode_16bits(x): return np.clip(x *", "= stft(y) S = amp_to_db(np.abs(D)) - hp.ref_level_db return normalize(S) def", "decode_mu_law(y, mu, from_labels=True): # TODO: get rid of log2 -", "= unsigned // 256 fine = unsigned % 256 return", "-2**15, 2**15 - 1).astype(np.int16) def linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate,", "[1], x) def de_emphasis(x): return lfilter([1], [1, -hp.preemphasis], x) def", "unsigned // 256 fine = unsigned % 256 return coarse,", "fmin=hp.fmin) ''' def build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) '''", "<= 1.0 x = (x + 1.) * (2**bits -", "fmin=hp.fmin) ''' def normalize(S): return np.clip((S - hp.min_level_db) / -hp.min_level_db,", "np.sign(y) / mu * ((1 + mu) ** np.abs(y) -", "db_to_amp(x): return np.power(10.0, x * 0.05) def spectrogram(y): D =", "0.5) def decode_mu_law(y, mu, from_labels=True): # TODO: get rid of", "* np.log(1 + mu * np.abs(x)) / np.log(1 + mu)", "phase reconstruction to convert from a normalized mel spectrogram back", "+ 1) / 2 * mu + 0.5) def decode_mu_law(y,", "mu, from_labels=True): # TODO: get rid of log2 - makes", "n_fft=hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin) ''' def build_mel_basis(): return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels,", "return np.floor((fx + 1) / 2 * mu + 0.5)", "x * 0.05) def spectrogram(y): D = stft(y) S =", "split_signal(x): unsigned = x + 2**15 coarse = unsigned //", "normalize(S): return np.clip((S - hp.min_level_db) / -hp.min_level_db, 0, 1) def", "x + 2**15 coarse = unsigned // 256 fine =", "= unsigned % 256 return coarse, fine def combine_signal(coarse, fine):", "2**15 - 1).astype(np.int16) def linear_to_mel(spectrogram): return librosa.feature.melspectrogram( S=spectrogram, sr=hp.sample_rate, n_fft=hp.n_fft,", "denormalize(mel) amp_mel = db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft( amp_mel, power=1, sr=hp.sample_rate,", "x) def encode_mu_law(x, mu): mu = mu - 1 fx", "- hp.ref_level_db return normalize(S) def melspectrogram(y): D = stft(y) S", "= label_2_float(y, math.log2(mu)) mu = mu - 1 x =", "+ fine - 2**15 def encode_16bits(x): return np.clip(x * 2**15,", "abs(x).max() <= 1.0 x = (x + 1.) * (2**bits", "[1, -hp.preemphasis], x) def encode_mu_law(x, mu): mu = mu -", "def encode_16bits(x): return np.clip(x * 2**15, -2**15, 2**15 - 1).astype(np.int16)", "+ mu) return np.floor((fx + 1) / 2 * mu", "hp.min_level_db def amp_to_db(x): return 20 * np.log10(np.maximum(1e-5, x)) def db_to_amp(x):", "as sf def label_2_float(x, bits): return 2 * x /", "return librosa.load(path, sr=hp.sample_rate)[0] def save_wav(x, path): # librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate)", "mu) return np.floor((fx + 1) / 2 * mu +", "1) / 2 * mu + 0.5) def decode_mu_law(y, mu,", "coarse = unsigned // 256 fine = unsigned % 256", "1 fx = np.sign(x) * np.log(1 + mu * np.abs(x))", "pre_emphasis(x): return lfilter([1, -hp.preemphasis], [1], x) def de_emphasis(x): return lfilter([1],", "coarse, fine def combine_signal(coarse, fine): return coarse * 256 +", "path): # librosa.output.write_wav(path, x.astype(np.float32), sr=hp.sample_rate) sf.write(path, x.astype(np.float32), samplerate=hp.sample_rate) def split_signal(x):", "a waveform.\"\"\" denormalized = denormalize(mel) amp_mel = db_to_amp(denormalized) S =", "return coarse, fine def combine_signal(coarse, fine): return coarse * 256", "= denormalize(mel) amp_mel = db_to_amp(denormalized) S = librosa.feature.inverse.mel_to_stft( amp_mel, power=1,", "stft(y) S = amp_to_db(linear_to_mel(np.abs(D))) return normalize(S) def stft(y): return librosa.stft(", "def melspectrogram(y): D = stft(y) S = amp_to_db(linear_to_mel(np.abs(D))) return normalize(S)", "import lfilter import soundfile as sf def label_2_float(x, bits): return", "-hp.preemphasis], [1], x) def de_emphasis(x): return lfilter([1], [1, -hp.preemphasis], x)" ]
[ "NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings):", "pass class NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings): pass", "pass class NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings): pass", "pass class NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings): pass", "class NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings): pass class", "NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings):", "class NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings): pass class", "NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings):", "class NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings): pass class", "NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings):", "pass class NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings): pass", "class NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings): pass class", "NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings):", "pass class NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings): pass", "pass class NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings): pass", "NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings):", "NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings):", "class NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings): pass class", "pass class NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings): pass", "NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings):", "class NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings): pass class", "pass class NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings): pass", "NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings):", "class NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings): pass class", "pass class NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings): pass", "pass class NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings): pass", "class NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings): pass class", "class NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings): pass class", "NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings):", "pass class NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings): pass", "pass class NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings): pass", "class NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings): pass class", "pass class NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings): pass", "class NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings): pass class", "class NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings): pass class", "class NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings): pass class", "class NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings): pass class", "pass class NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings): pass", "pass class NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings): pass", "NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings):", "class NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings): pass class", "class NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings): pass class", "NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings):", "NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings):", "NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings):", "NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings):", "class NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings): pass class", "class NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings): pass class", "NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings):", "NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings):", "class NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings): pass class", "NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings):", "NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings):", "class NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings): pass class", "getratings.models.ratings import Ratings class NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings): pass class", "NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings):", "NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings):", "NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings):", "pass class NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings): pass", "class NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings): pass class", "from getratings.models.ratings import Ratings class NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings): pass", "class NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings): pass class", "class NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings): pass class", "pass class NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings): pass", "NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings):", "pass class NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings): pass", "class NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings): pass class", "class NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings): pass class", "NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings):", "class NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings): pass class", "pass class NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings): pass", "NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings):", "class NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings): pass class", "class NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings): pass class", "class NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings): pass class", "class NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings): pass class", "NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings):", "NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings):", "pass class NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings): pass", "pass class NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings): pass", "NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings):", "class NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings): pass class", "NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings):", "pass class NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings): pass", "class NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings): pass class", "pass class NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings): pass", "class NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings): pass class", "NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings):", "class NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings): pass class", "NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings):", "NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings):", "NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings):", "NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings):", "class NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings): pass class", "class NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings): pass class", "NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings):", "class NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings): pass class", "NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings):", "pass class NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings): pass", "pass class NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings): pass", "class NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings): pass class", "NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings):", "NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings):", "pass class NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings): pass", "NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings):", "pass class NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings): pass", "NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings):", "NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings):", "NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings):", "NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings):", "pass class NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings): pass", "NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings):", "NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings):", "NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings):", "class NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings): pass class", "pass class NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings): pass", "NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings):", "NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings):", "NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings):", "NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings):", "class NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings): pass class", "pass class NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings): pass", "NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings):", "pass class NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings): pass", "pass class NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings): pass", "class NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings): pass class", "class NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings): pass class", "NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings):", "class NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings): pass class", "pass class NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings): pass", "class NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings): pass class", "NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings):", "class NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings): pass class", "NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings):", "class NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings): pass class", "class NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings): pass class", "NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings):", "pass class NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings): pass", "NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings):", "class NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings): pass class", "NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings):", "pass class NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings): pass", "class NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings): pass class", "NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings):", "NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings):", "pass class NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings): pass", "NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings):", "Ratings class NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings): pass", "pass class NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings): pass", "NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings):", "pass class NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings): pass", "class NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings): pass class", "pass class NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings): pass", "class NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings): pass class", "pass class NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings): pass", "pass class NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings): pass", "class NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings): pass class", "class NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings): pass class", "NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings):", "NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings):", "pass class NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings): pass", "NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings):", "pass class NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings): pass", "NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings):", "NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings):", "NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings):", "pass class NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings): pass", "NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings):", "pass class NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings): pass", "class NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings): pass class", "pass class NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings): pass", "pass class NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings): pass", "pass class NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings): pass", "pass class NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings): pass", "class NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings): pass class", "pass class NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings): pass", "class NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings): pass class", "pass class NA_Talon_Jng_Ziggs(Ratings): pass class NA_Talon_Jng_Zilean(Ratings): pass class NA_Talon_Jng_Zyra(Ratings): pass", "pass class NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings): pass", "pass class NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings): pass", "pass class NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings): pass", "NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings):", "pass class NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings): pass", "pass class NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings): pass", "class NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings): pass class", "class NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings): pass class", "NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings):", "pass class NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings): pass", "class NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings): pass class", "pass class NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings): pass", "NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings):", "class NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings): pass class", "NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings):", "pass class NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings): pass", "pass class NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings): pass", "class NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings): pass class", "pass class NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings): pass", "pass class NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings): pass", "pass class NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings): pass", "pass class NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings): pass", "class NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings): pass class", "pass class NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings): pass", "NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings): pass class NA_Talon_Jng_Zilean(Ratings):", "class NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings): pass class", "pass class NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings): pass", "NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings):", "class NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings): pass class", "pass class NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings): pass", "class NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings): pass class NA_Talon_Jng_Malzahar(Ratings): pass class", "NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings):", "NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings):", "NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings):", "NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings):", "NA_Talon_Jng_Ivern(Ratings): pass class NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings):", "class NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings): pass class", "NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings):", "pass class NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings): pass", "class NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings): pass class", "NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings):", "pass class NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings): pass", "pass class NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings): pass", "class NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings): pass class NA_Talon_Jng_Vladimir(Ratings): pass class", "class NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings): pass class", "NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings):", "class NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings): pass class", "pass class NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings): pass", "class NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings): pass class", "import Ratings class NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings):", "class NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings): pass class", "class NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings): pass class NA_Talon_Jng_Quinn(Ratings): pass class", "pass class NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings): pass", "pass class NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings): pass", "NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings):", "class NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings): pass class", "NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings):", "NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings):", "pass class NA_Talon_Jng_Bard(Ratings): pass class NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings): pass", "pass class NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings): pass", "NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings):", "class NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings): pass class NA_Talon_Jng_Rengar(Ratings): pass class", "class NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings): pass class", "pass class NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings): pass", "class NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings): pass class", "pass class NA_Talon_Jng_Chogath(Ratings): pass class NA_Talon_Jng_Corki(Ratings): pass class NA_Talon_Jng_Darius(Ratings): pass", "pass class NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings): pass", "class NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings): pass class", "class NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings): pass class", "NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings):", "NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings):", "pass class NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings): pass", "NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings):", "class NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings): pass class", "NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings):", "pass class NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings): pass", "class NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings): pass class", "NA_Talon_Jng_Janna(Ratings): pass class NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings):", "pass class NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings): pass", "pass class NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings): pass", "class NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings): pass class", "NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings):", "NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings):", "pass class NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings): pass", "NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings):", "pass class NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings): pass", "pass class NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings): pass", "pass class NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings): pass", "class NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings): pass class", "pass class NA_Talon_Jng_Braum(Ratings): pass class NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings): pass", "NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings): pass class NA_Talon_Jng_Karthus(Ratings):", "NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings):", "class NA_Talon_Jng_Morgana(Ratings): pass class NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings): pass class", "class NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings): pass class", "class NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings): pass class", "class NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings): pass class", "class NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings): pass class", "class NA_Talon_Jng_Blitzcrank(Ratings): pass class NA_Talon_Jng_Brand(Ratings): pass class NA_Talon_Jng_Braum(Ratings): pass class", "pass class NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings): pass", "NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings):", "pass class NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings): pass", "pass class NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings): pass", "class NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings): pass class", "class NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings): pass class", "NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings): pass class NA_Talon_Jng_Mordekaiser(Ratings): pass class NA_Talon_Jng_Morgana(Ratings):", "class NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings): pass class", "class NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings): pass class NA_Talon_Jng_XinZhao(Ratings): pass class", "class NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings): pass class", "pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings): pass", "pass class NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings): pass", "class NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings): pass class", "NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings):", "class NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings): pass class NA_Talon_Jng_Annie(Ratings): pass class", "pass class NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings): pass class NA_Talon_Jng_Ivern(Ratings): pass", "class NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings): pass class", "NA_Talon_Jng_Rengar(Ratings): pass class NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings):", "pass class NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings): pass", "pass class NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings): pass", "pass class NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings): pass", "class NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings): pass class", "NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings): pass class NA_Talon_Jng_Zilean(Ratings): pass class NA_Talon_Jng_Zyra(Ratings):", "class NA_Talon_Jng_Warwick(Ratings): pass class NA_Talon_Jng_Xayah(Ratings): pass class NA_Talon_Jng_Xerath(Ratings): pass class", "NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings): pass class NA_Talon_Jng_Evelynn(Ratings):", "pass class NA_Talon_Jng_Teemo(Ratings): pass class NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings): pass", "NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings): pass class NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings):", "class NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass class", "class NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings): pass class", "pass class NA_Talon_Jng_Vladimir(Ratings): pass class NA_Talon_Jng_Volibear(Ratings): pass class NA_Talon_Jng_Warwick(Ratings): pass", "class NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings): pass class", "pass class NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings): pass", "class NA_Talon_Jng_Singed(Ratings): pass class NA_Talon_Jng_Sion(Ratings): pass class NA_Talon_Jng_Sivir(Ratings): pass class", "class NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings): pass class", "pass class NA_Talon_Jng_Evelynn(Ratings): pass class NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass", "pass class NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings): pass", "pass class NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings): pass", "pass class NA_Talon_Jng_Sona(Ratings): pass class NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings): pass", "NA_Talon_Jng_Taliyah(Ratings): pass class NA_Talon_Jng_Talon(Ratings): pass class NA_Talon_Jng_Taric(Ratings): pass class NA_Talon_Jng_Teemo(Ratings):", "NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings):", "class NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings): pass class", "class NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings): pass class NA_Talon_Jng_Karma(Ratings): pass class", "class NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings): pass class", "NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings):", "class NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings): pass class", "class NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings): pass class", "class NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings): pass class", "NA_Talon_Jng_Annie(Ratings): pass class NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings):", "pass class NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings): pass", "NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings):", "pass class NA_Talon_Jng_Quinn(Ratings): pass class NA_Talon_Jng_Rakan(Ratings): pass class NA_Talon_Jng_Rammus(Ratings): pass", "NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings):", "NA_Talon_Jng_Caitlyn(Ratings): pass class NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings):", "class NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings): pass class", "NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings): pass class NA_Talon_Jng_Singed(Ratings):", "class NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings): pass class NA_Talon_Jng_Zilean(Ratings): pass class", "pass class NA_Talon_Jng_Tryndamere(Ratings): pass class NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings): pass", "class NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings): pass class", "NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings): pass class NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings):", "pass class NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings): pass", "class NA_Talon_Jng_Rammus(Ratings): pass class NA_Talon_Jng_RekSai(Ratings): pass class NA_Talon_Jng_Renekton(Ratings): pass class", "NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings):", "NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings):", "NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings):", "class NA_Talon_Jng_Thresh(Ratings): pass class NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings): pass class", "pass class NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings): pass", "class NA_Talon_Jng_Nami(Ratings): pass class NA_Talon_Jng_Nasus(Ratings): pass class NA_Talon_Jng_Nautilus(Ratings): pass class", "class NA_Talon_Jng_Camille(Ratings): pass class NA_Talon_Jng_Cassiopeia(Ratings): pass class NA_Talon_Jng_Chogath(Ratings): pass class", "class NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings): pass class", "class NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings): pass class", "class NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings): pass class", "pass class NA_Talon_Jng_Zed(Ratings): pass class NA_Talon_Jng_Ziggs(Ratings): pass class NA_Talon_Jng_Zilean(Ratings): pass", "class NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings): pass class", "pass class NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings): pass class NA_Talon_Jng_Jhin(Ratings): pass", "class NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings): pass class", "NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings): pass class NA_Talon_Jng_Lissandra(Ratings): pass class NA_Talon_Jng_Lucian(Ratings):", "NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings): pass class NA_Talon_Jng_Heimerdinger(Ratings):", "pass class NA_Talon_Jng_Heimerdinger(Ratings): pass class NA_Talon_Jng_Illaoi(Ratings): pass class NA_Talon_Jng_Irelia(Ratings): pass", "pass class NA_Talon_Jng_Gangplank(Ratings): pass class NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings): pass", "pass class NA_Talon_Jng_JarvanIV(Ratings): pass class NA_Talon_Jng_Jax(Ratings): pass class NA_Talon_Jng_Jayce(Ratings): pass", "class NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings): pass class NA_Talon_Jng_Ornn(Ratings): pass class", "pass class NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings): pass", "pass class NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings): pass", "NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings):", "NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings): pass class NA_Talon_Jng_Kayn(Ratings):", "NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings): pass class NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings):", "pass class NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings): pass", "NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings):", "NA_Talon_Jng_Ezreal(Ratings): pass class NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings):", "class NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings): pass class", "NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings):", "NA_Talon_Jng_Ryze(Ratings): pass class NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings):", "pass class NA_Talon_Jng_Sivir(Ratings): pass class NA_Talon_Jng_Skarner(Ratings): pass class NA_Talon_Jng_Sona(Ratings): pass", "NA_Talon_Jng_Soraka(Ratings): pass class NA_Talon_Jng_Swain(Ratings): pass class NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings):", "NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings): pass class NA_Talon_Jng_Kayle(Ratings):", "NA_Talon_Jng_Sejuani(Ratings): pass class NA_Talon_Jng_Shaco(Ratings): pass class NA_Talon_Jng_Shen(Ratings): pass class NA_Talon_Jng_Shyvana(Ratings):", "pass class NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings): pass class NA_Talon_Jng_Bard(Ratings): pass", "pass class NA_Talon_Jng_Ashe(Ratings): pass class NA_Talon_Jng_AurelionSol(Ratings): pass class NA_Talon_Jng_Azir(Ratings): pass", "class NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings): pass class", "class NA_Talon_Jng_Ahri(Ratings): pass class NA_Talon_Jng_Akali(Ratings): pass class NA_Talon_Jng_Alistar(Ratings): pass class", "NA_Talon_Jng_Kled(Ratings): pass class NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings):", "<filename>loldib/getratings/models/NA/na_talon/na_talon_jng.py from getratings.models.ratings import Ratings class NA_Talon_Jng_Aatrox(Ratings): pass class NA_Talon_Jng_Ahri(Ratings):", "pass class NA_Talon_Jng_Riven(Ratings): pass class NA_Talon_Jng_Rumble(Ratings): pass class NA_Talon_Jng_Ryze(Ratings): pass", "NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings):", "pass class NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings): pass", "pass class NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings): pass", "class NA_Talon_Jng_MasterYi(Ratings): pass class NA_Talon_Jng_MissFortune(Ratings): pass class NA_Talon_Jng_MonkeyKing(Ratings): pass class", "pass class NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings): pass class NA_Talon_Jng_Zac(Ratings): pass", "pass class NA_Talon_Jng_Varus(Ratings): pass class NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings): pass", "pass class NA_Talon_Jng_Malzahar(Ratings): pass class NA_Talon_Jng_Maokai(Ratings): pass class NA_Talon_Jng_MasterYi(Ratings): pass", "NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings): pass class NA_Talon_Jng_Graves(Ratings): pass class NA_Talon_Jng_Hecarim(Ratings):", "class NA_Talon_Jng_Alistar(Ratings): pass class NA_Talon_Jng_Amumu(Ratings): pass class NA_Talon_Jng_Anivia(Ratings): pass class", "class NA_Talon_Jng_Vayne(Ratings): pass class NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings): pass class", "pass class NA_Talon_Jng_Jhin(Ratings): pass class NA_Talon_Jng_Jinx(Ratings): pass class NA_Talon_Jng_Kalista(Ratings): pass", "pass class NA_Talon_Jng_Ornn(Ratings): pass class NA_Talon_Jng_Pantheon(Ratings): pass class NA_Talon_Jng_Poppy(Ratings): pass", "pass class NA_Talon_Jng_XinZhao(Ratings): pass class NA_Talon_Jng_Yasuo(Ratings): pass class NA_Talon_Jng_Yorick(Ratings): pass", "pass class NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings): pass class NA_Talon_Jng_Nunu(Ratings): pass", "pass class NA_Talon_Jng_Tristana(Ratings): pass class NA_Talon_Jng_Trundle(Ratings): pass class NA_Talon_Jng_Tryndamere(Ratings): pass", "class NA_Talon_Jng_DrMundo(Ratings): pass class NA_Talon_Jng_Ekko(Ratings): pass class NA_Talon_Jng_Elise(Ratings): pass class", "class NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings): pass class", "NA_Talon_Jng_Kennen(Ratings): pass class NA_Talon_Jng_Khazix(Ratings): pass class NA_Talon_Jng_Kindred(Ratings): pass class NA_Talon_Jng_Kled(Ratings):", "class NA_Talon_Jng_Nunu(Ratings): pass class NA_Talon_Jng_Olaf(Ratings): pass class NA_Talon_Jng_Orianna(Ratings): pass class", "pass class NA_Talon_Jng_Syndra(Ratings): pass class NA_Talon_Jng_TahmKench(Ratings): pass class NA_Talon_Jng_Taliyah(Ratings): pass", "pass class NA_Talon_Jng_Fizz(Ratings): pass class NA_Talon_Jng_Galio(Ratings): pass class NA_Talon_Jng_Gangplank(Ratings): pass", "pass class NA_Talon_Jng_Garen(Ratings): pass class NA_Talon_Jng_Gnar(Ratings): pass class NA_Talon_Jng_Gragas(Ratings): pass", "NA_Talon_Jng_Veigar(Ratings): pass class NA_Talon_Jng_Velkoz(Ratings): pass class NA_Talon_Jng_Vi(Ratings): pass class NA_Talon_Jng_Viktor(Ratings):", "pass class NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings): pass class NA_Talon_Jng_Leona(Ratings): pass", "class NA_Talon_Jng_Fiddlesticks(Ratings): pass class NA_Talon_Jng_Fiora(Ratings): pass class NA_Talon_Jng_Fizz(Ratings): pass class", "pass class NA_Talon_Jng_KogMaw(Ratings): pass class NA_Talon_Jng_Leblanc(Ratings): pass class NA_Talon_Jng_LeeSin(Ratings): pass", "NA_Talon_Jng_Lucian(Ratings): pass class NA_Talon_Jng_Lulu(Ratings): pass class NA_Talon_Jng_Lux(Ratings): pass class NA_Talon_Jng_Malphite(Ratings):", "NA_Talon_Jng_TwistedFate(Ratings): pass class NA_Talon_Jng_Twitch(Ratings): pass class NA_Talon_Jng_Udyr(Ratings): pass class NA_Talon_Jng_Urgot(Ratings):", "class NA_Talon_Jng_Karthus(Ratings): pass class NA_Talon_Jng_Kassadin(Ratings): pass class NA_Talon_Jng_Katarina(Ratings): pass class", "class NA_Talon_Jng_Nautilus(Ratings): pass class NA_Talon_Jng_Nidalee(Ratings): pass class NA_Talon_Jng_Nocturne(Ratings): pass class", "NA_Talon_Jng_Darius(Ratings): pass class NA_Talon_Jng_Diana(Ratings): pass class NA_Talon_Jng_Draven(Ratings): pass class NA_Talon_Jng_DrMundo(Ratings):" ]
[ "TurkishText(): \"\"\"Class for handling lowercase/uppercase conversions of Turkish characters.. Attributes:", "for i in self.text: if i in self.u: res +=", "i in self.text: if i in self.l: res += self.u[self.l.index(i)]", "in self.l: res += self.u[self.l.index(i)] else : res += i.upper()", "if i in self.l: res += self.u[self.l.index(i)] else : res", "characters.. Attributes: text -- Turkish text to be handled \"\"\"", ": res += i.lower() return res def capitalize(self): \"\"\"Converts each", "text into lowercase letters. Returns string. \"\"\" res = \"\"", "'İ', 'Ö', 'Ç'] def __init__(self, text): self.text = text def", "'Ş', 'İ', 'Ö', 'Ç'] def __init__(self, text): self.text = text", "the text into lowercase letters. Returns string. \"\"\" res =", "\"\"\"Converts each first letter to uppercase, and the rest to", "lower(self): \"\"\"Converts the text into lowercase letters. Returns string. \"\"\"", "into lowercase letters. Returns string. \"\"\" res = \"\" for", "= ['ı', 'ğ', 'ü', 'ş', 'i', 'ö', 'ç'] u =", "\"\" for i in self.text: if i in self.u: res", "text into uppercase letters. Returns string. \"\"\" res = \"\"", "i in m: res += TurkishText(i[0]).upper() + TurkishText(i[1:]).lower() + \"", "'ç'] u = ['I', 'Ğ', 'Ü', 'Ş', 'İ', 'Ö', 'Ç']", "self.l: res += self.u[self.l.index(i)] else : res += i.upper() return", "'Ü', 'Ş', 'İ', 'Ö', 'Ç'] def __init__(self, text): self.text =", "+= i.upper() return res def lower(self): \"\"\"Converts the text into", "'ü', 'ş', 'i', 'ö', 'ç'] u = ['I', 'Ğ', 'Ü',", "in self.text: if i in self.l: res += self.u[self.l.index(i)] else", "into uppercase letters. Returns string. \"\"\" res = \"\" for", "self.text.split() res = \"\" for i in m: res +=", "lowercase letters. Returns string. \"\"\" m = self.text.split() res =", "\"\"\"Converts the text into uppercase letters. Returns string. \"\"\" res", "to lowercase letters. Returns string. \"\"\" m = self.text.split() res", "res += TurkishText(i[0]).upper() + TurkishText(i[1:]).lower() + \" \" return res[:-1:]", "self.l[self.u.index(i)] else : res += i.lower() return res def capitalize(self):", "text = \"\" l = ['ı', 'ğ', 'ü', 'ş', 'i',", "\"\" for i in m: res += TurkishText(i[0]).upper() + TurkishText(i[1:]).lower()", "['I', 'Ğ', 'Ü', 'Ş', 'İ', 'Ö', 'Ç'] def __init__(self, text):", "'ş', 'i', 'ö', 'ç'] u = ['I', 'Ğ', 'Ü', 'Ş',", "= \"\" for i in self.text: if i in self.l:", "if i in self.u: res += self.l[self.u.index(i)] else : res", "uppercase, and the rest to lowercase letters. Returns string. \"\"\"", "m: res += TurkishText(i[0]).upper() + TurkishText(i[1:]).lower() + \" \" return", "for handling lowercase/uppercase conversions of Turkish characters.. Attributes: text --", "'i', 'ö', 'ç'] u = ['I', 'Ğ', 'Ü', 'Ş', 'İ',", "self.u: res += self.l[self.u.index(i)] else : res += i.lower() return", "res += i.lower() return res def capitalize(self): \"\"\"Converts each first", "else : res += i.upper() return res def lower(self): \"\"\"Converts", "Turkish text to be handled \"\"\" text = \"\" l", "for i in self.text: if i in self.l: res +=", "class TurkishText(): \"\"\"Class for handling lowercase/uppercase conversions of Turkish characters..", "string. \"\"\" res = \"\" for i in self.text: if", "'Ö', 'Ç'] def __init__(self, text): self.text = text def upper(self):", "\"\"\" res = \"\" for i in self.text: if i", "Turkish characters.. Attributes: text -- Turkish text to be handled", "string. \"\"\" m = self.text.split() res = \"\" for i", "= self.text.split() res = \"\" for i in m: res", "i.upper() return res def lower(self): \"\"\"Converts the text into lowercase", "in self.text: if i in self.u: res += self.l[self.u.index(i)] else", "= text def upper(self): \"\"\"Converts the text into uppercase letters.", "l = ['ı', 'ğ', 'ü', 'ş', 'i', 'ö', 'ç'] u", "\"\"\"Converts the text into lowercase letters. Returns string. \"\"\" res", "self.text: if i in self.u: res += self.l[self.u.index(i)] else :", "def upper(self): \"\"\"Converts the text into uppercase letters. Returns string.", "__init__(self, text): self.text = text def upper(self): \"\"\"Converts the text", "+= i.lower() return res def capitalize(self): \"\"\"Converts each first letter", "lowercase letters. Returns string. \"\"\" res = \"\" for i", "Returns string. \"\"\" res = \"\" for i in self.text:", "to be handled \"\"\" text = \"\" l = ['ı',", "letter to uppercase, and the rest to lowercase letters. Returns", "+= self.u[self.l.index(i)] else : res += i.upper() return res def", "Returns string. \"\"\" m = self.text.split() res = \"\" for", "res = \"\" for i in self.text: if i in", "\"\" l = ['ı', 'ğ', 'ü', 'ş', 'i', 'ö', 'ç']", "handled \"\"\" text = \"\" l = ['ı', 'ğ', 'ü',", "handling lowercase/uppercase conversions of Turkish characters.. Attributes: text -- Turkish", "the rest to lowercase letters. Returns string. \"\"\" m =", "capitalize(self): \"\"\"Converts each first letter to uppercase, and the rest", "upper(self): \"\"\"Converts the text into uppercase letters. Returns string. \"\"\"", "def __init__(self, text): self.text = text def upper(self): \"\"\"Converts the", "= \"\" for i in self.text: if i in self.u:", "the text into uppercase letters. Returns string. \"\"\" res =", "uppercase letters. Returns string. \"\"\" res = \"\" for i", "res = \"\" for i in m: res += TurkishText(i[0]).upper()", "= \"\" l = ['ı', 'ğ', 'ü', 'ş', 'i', 'ö',", "and the rest to lowercase letters. Returns string. \"\"\" m", "i in self.u: res += self.l[self.u.index(i)] else : res +=", "text def upper(self): \"\"\"Converts the text into uppercase letters. Returns", "def capitalize(self): \"\"\"Converts each first letter to uppercase, and the", "i in self.l: res += self.u[self.l.index(i)] else : res +=", "u = ['I', 'Ğ', 'Ü', 'Ş', 'İ', 'Ö', 'Ç'] def", "\"\"\" m = self.text.split() res = \"\" for i in", "-- Turkish text to be handled \"\"\" text = \"\"", "+= self.l[self.u.index(i)] else : res += i.lower() return res def", "self.u[self.l.index(i)] else : res += i.upper() return res def lower(self):", "'Ğ', 'Ü', 'Ş', 'İ', 'Ö', 'Ç'] def __init__(self, text): self.text", "else : res += i.lower() return res def capitalize(self): \"\"\"Converts", "for i in m: res += TurkishText(i[0]).upper() + TurkishText(i[1:]).lower() +", "each first letter to uppercase, and the rest to lowercase", "i in self.text: if i in self.u: res += self.l[self.u.index(i)]", "Attributes: text -- Turkish text to be handled \"\"\" text", "conversions of Turkish characters.. Attributes: text -- Turkish text to", "return res def lower(self): \"\"\"Converts the text into lowercase letters.", "= \"\" for i in m: res += TurkishText(i[0]).upper() +", "text): self.text = text def upper(self): \"\"\"Converts the text into", "res += self.l[self.u.index(i)] else : res += i.lower() return res", "i.lower() return res def capitalize(self): \"\"\"Converts each first letter to", "in self.u: res += self.l[self.u.index(i)] else : res += i.lower()", "res += i.upper() return res def lower(self): \"\"\"Converts the text", "of Turkish characters.. Attributes: text -- Turkish text to be", "\"\" for i in self.text: if i in self.l: res", "return res def capitalize(self): \"\"\"Converts each first letter to uppercase,", "m = self.text.split() res = \"\" for i in m:", "res def capitalize(self): \"\"\"Converts each first letter to uppercase, and", "lowercase/uppercase conversions of Turkish characters.. Attributes: text -- Turkish text", "self.text: if i in self.l: res += self.u[self.l.index(i)] else :", "'ö', 'ç'] u = ['I', 'Ğ', 'Ü', 'Ş', 'İ', 'Ö',", "'ğ', 'ü', 'ş', 'i', 'ö', 'ç'] u = ['I', 'Ğ',", "text -- Turkish text to be handled \"\"\" text =", "rest to lowercase letters. Returns string. \"\"\" m = self.text.split()", "to uppercase, and the rest to lowercase letters. Returns string.", "\"\"\"Class for handling lowercase/uppercase conversions of Turkish characters.. Attributes: text", "text to be handled \"\"\" text = \"\" l =", "= ['I', 'Ğ', 'Ü', 'Ş', 'İ', 'Ö', 'Ç'] def __init__(self,", "in m: res += TurkishText(i[0]).upper() + TurkishText(i[1:]).lower() + \" \"", "'Ç'] def __init__(self, text): self.text = text def upper(self): \"\"\"Converts", "\"\"\" text = \"\" l = ['ı', 'ğ', 'ü', 'ş',", "res def lower(self): \"\"\"Converts the text into lowercase letters. Returns", "letters. Returns string. \"\"\" m = self.text.split() res = \"\"", "self.text = text def upper(self): \"\"\"Converts the text into uppercase", "['ı', 'ğ', 'ü', 'ş', 'i', 'ö', 'ç'] u = ['I',", "first letter to uppercase, and the rest to lowercase letters.", ": res += i.upper() return res def lower(self): \"\"\"Converts the", "res += self.u[self.l.index(i)] else : res += i.upper() return res", "letters. Returns string. \"\"\" res = \"\" for i in", "be handled \"\"\" text = \"\" l = ['ı', 'ğ',", "def lower(self): \"\"\"Converts the text into lowercase letters. Returns string." ]
[ "import googlemaps gmaps = googlemaps.Client(key='google_key') def get_markers(address): geocode_result = gmaps.geocode(address)", "googlemaps gmaps = googlemaps.Client(key='google_key') def get_markers(address): geocode_result = gmaps.geocode(address) return", "gmaps = googlemaps.Client(key='google_key') def get_markers(address): geocode_result = gmaps.geocode(address) return geocode_result[0]['geometry']['location']" ]
[ "import print_function # Imports import os import numpy as np", "print(\"Model path chosen : \", dir_path) if (not os.path.exists(dir_path)): os.mkdir(dir_path)", "None: optimizer = tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True) # 1.", "Create optimizer and compile model if optimizer is None if", "the model model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est, model_eval def", "Run the training model_est = tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict),", "metrics=['accuracy']) # 2. Create an estimator model_est = tf.keras.estimator.model_to_estimator( keras_model=model,", "2. Create an estimator model_est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') #", "tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') # Training # 3a. Create the training", ":param eval_fn_dict : dictionary containing params for eval input_fn :param", "division from __future__ import print_function # Imports import os import", "num_epochs=nb_epochs, shuffle=True ) # 4b. Evaluate the model model_eval =", "compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 3. create", "to store the trained model \"\"\" # 1. Create optimizer", "estimator :param input_fn_dict : dictionary containing input params for input_fn", "dictionary containing params for eval input_fn :param model_dir : directory", "and compile model if optimizer is None if (optimizer is", "# Training # 3a. Create the training function train_input_fn =", "num_epochs=nb_epochs, shuffle=True ) # 3b. Train the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches)", "create an estimator using tf.data.Dataset :param model : uncompiled keras", "= tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True) # 2. compile the", "optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 3. create estimator dir_path = os.path.join(os.getcwd(),", "path chosen : \", dir_path) if (not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating", ":param model : uncompiled keras model :param input_fn : input", "tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run the training model_est = tf.estimator.train_and_evaluate(est, train_spec,", "tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 4b.", "training function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs,", "model : uncompiled keras model :param input_fn : input function", "chosen : \", dir_path) if (not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\")", "train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True )", "tf.data.Dataset to the estimator :param input_fn_dict : dictionary containing input", "\"\"\" Run the estimator \"\"\" if optimizer is None: optimizer", "params for input_fn :param eval_fn_dict : dictionary containing params for", "3a. Create the training function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)},", "estimator dir_path = os.path.join(os.getcwd(), model_dir) print(\"Model path chosen : \",", "__future__ import division from __future__ import print_function # Imports import", "model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 2. Create an estimator model_est", "batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 3b. Train the model model_est.train(input_fn=train_input_fn,", "spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run the training model_est", "= tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run the training model_est = tf.estimator.train_and_evaluate(est,", "as tf def run(model, X, Y, optimizer=None, nb_epochs=30, nb_batches=128): \"\"\"", "to the estimator :param input_fn_dict : dictionary containing input params", "dictionary containing input params for input_fn :param eval_fn_dict : dictionary", "4. Train and Evaluate the model print(\"Training...\") # training spec", "X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 3b. Train the", "the estimator :param input_fn_dict : dictionary containing input params for", "as np import tensorflow as tf def run(model, X, Y,", "steps=nb_epochs*nb_batches) # Evaluate # 4a. Evaluate the model eval_input_fn =", "nb_epochs=30, nb_batches=128): \"\"\" Run the estimator \"\"\" if optimizer is", "= tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), # steps=None) # #est.evalute(input_fn=lambda:", "model eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True", "train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), # steps=None) # #est.evalute(input_fn=lambda: input_func(eval_func_dict)) return", ") # 4b. Evaluate the model model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval)", "if optimizer is None if (optimizer is None): optimizer =", "lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True) # 2. compile the model model.compile(", "if (not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\") est = tf.keras.estimator.model_to_estimator( keras_model=model,", "if optimizer is None: optimizer = tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9,", ":param input_fn : input function providing tf.data.Dataset to the estimator", "y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 3b. Train the model", "model_dir=dir_path) # 4. Train and Evaluate the model print(\"Training...\") #", ": dictionary containing params for eval input_fn :param model_dir :", "input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None): \"\"\" Overloaded function to", "shuffle=True ) # 4b. Evaluate the model model_eval = model_est.evaluate(input_fn=eval_input_fn)", "eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run the training model_est =", "numpy as np import tensorflow as tf def run(model, X,", "is None): optimizer = tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True) #", "Training # 3a. Create the training function train_input_fn = tf.estimator.inputs.numpy_input_fn(", "X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 4b. Evaluate the", "tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 3b.", "y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 4b. Evaluate the model", "np import tensorflow as tf def run(model, X, Y, optimizer=None,", "= tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) #", "Train the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate # 4a. Evaluate", "to create an estimator using tf.data.Dataset :param model : uncompiled", "is None if (optimizer is None): optimizer = tf.keras.optimizers.SGD( lr=1e-3,", "decay=1e-5, momentum=0.9, nesterov=True) # 2. compile the model model.compile( optimizer=optimizer,", "eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True )", "providing tf.data.Dataset to the estimator :param input_fn_dict : dictionary containing", "dir_path) if (not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\") est = tf.keras.estimator.model_to_estimator(", "\"\"\" Overloaded function to create an estimator using tf.data.Dataset :param", "X, Y, optimizer=None, nb_epochs=30, nb_batches=128): \"\"\" Run the estimator \"\"\"", "model model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est, model_eval def run_from_generator(", "\", dir_path) if (not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\") est =", "run(model, X, Y, optimizer=None, nb_epochs=30, nb_batches=128): \"\"\" Run the estimator", "os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\") est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) #", "\"\"\" # 1. Create optimizer and compile model if optimizer", "os.mkdir(dir_path) print(\"Creating estimator...\") est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) # 4.", "= os.path.join(os.getcwd(), model_dir) print(\"Model path chosen : \", dir_path) if", "tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), # steps=None) # #est.evalute(input_fn=lambda: input_func(eval_func_dict))", "import os import numpy as np import tensorflow as tf", "x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 3b. Train", "optimizer and compile model if optimizer is None if (optimizer", "nb_batches=128): \"\"\" Run the estimator \"\"\" if optimizer is None:", "= model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est, model_eval def run_from_generator( model, input_func=None,", "for input_fn :param eval_fn_dict : dictionary containing params for eval", "input_func(input_func_dict), max_steps=500) # evaluation spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) #", "model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 3. create estimator dir_path", "model print(\"Training...\") # training spec train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500)", "create estimator dir_path = os.path.join(os.getcwd(), model_dir) print(\"Model path chosen :", "os.path.join(os.getcwd(), model_dir) print(\"Model path chosen : \", dir_path) if (not", "Evaluate the model eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches,", "def run_from_generator( model, input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None): \"\"\"", "# 2. Create an estimator model_est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet')", "= tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') # Training # 3a. Create the", "(optimizer is None): optimizer = tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True)", "tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True) # 2. compile the model", "input_fn : input function providing tf.data.Dataset to the estimator :param", "tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True) # 1. Compile the model", "trained model \"\"\" # 1. Create optimizer and compile model", "Evaluate the model model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est, model_eval", "evaluation spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run the training", "x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 4b. Evaluate", "model_est, model_eval def run_from_generator( model, input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None,", ":param input_fn_dict : dictionary containing input params for input_fn :param", "the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 3. create estimator", "eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), # steps=None) # #est.evalute(input_fn=lambda: input_func(eval_func_dict)) return est", "4a. Evaluate the model eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32),", "function to create an estimator using tf.data.Dataset :param model :", "input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None): \"\"\" Overloaded function to create", "tf.data.Dataset :param model : uncompiled keras model :param input_fn :", "model_dir : directory to store the trained model \"\"\" #", "containing params for eval input_fn :param model_dir : directory to", "def run(model, X, Y, optimizer=None, nb_epochs=30, nb_batches=128): \"\"\" Run the", "estimator using tf.data.Dataset :param model : uncompiled keras model :param", "import division from __future__ import print_function # Imports import os", "keras model :param input_fn : input function providing tf.data.Dataset to", "model if optimizer is None if (optimizer is None): optimizer", "# 2. compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) #", "eval_fn_dict : dictionary containing params for eval input_fn :param model_dir", "the training model_est = tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), #", "eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None): \"\"\" Overloaded function to create an", "input params for input_fn :param eval_fn_dict : dictionary containing params", "model_est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') # Training # 3a. Create", "# 1. Create optimizer and compile model if optimizer is", "lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True) # 1. Compile the model model.compile(", "# 4. Train and Evaluate the model print(\"Training...\") # training", ": dictionary containing input params for input_fn :param eval_fn_dict :", "from __future__ import absolute_import from __future__ import division from __future__", "model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate # 4a. Evaluate the model", "keras_model=model, model_dir='./lenet') # Training # 3a. Create the training function", "uncompiled keras model :param input_fn : input function providing tf.data.Dataset", "Evaluate the model print(\"Training...\") # training spec train_spec = tf.estimator.TrainSpec(input_fn=lambda:", "import numpy as np import tensorflow as tf def run(model,", "containing input params for input_fn :param eval_fn_dict : dictionary containing", ": uncompiled keras model :param input_fn : input function providing", "the training function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches,", "tf def run(model, X, Y, optimizer=None, nb_epochs=30, nb_batches=128): \"\"\" Run", "using tf.data.Dataset :param model : uncompiled keras model :param input_fn", "batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) # 4b. Evaluate the model model_eval", "return model_est, model_eval def run_from_generator( model, input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10,", "3b. Train the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate # 4a.", "1. Create optimizer and compile model if optimizer is None", ":param model_dir : directory to store the trained model \"\"\"", "print_function # Imports import os import numpy as np import", "loss='categorical_crossentropy', metrics=['accuracy']) # 2. Create an estimator model_est = tf.keras.estimator.model_to_estimator(", "and Evaluate the model print(\"Training...\") # training spec train_spec =", "optimizer=None, nb_epochs=30, nb_batches=128): \"\"\" Run the estimator \"\"\" if optimizer", "keras_model=model, model_dir=dir_path) # 4. Train and Evaluate the model print(\"Training...\")", "function providing tf.data.Dataset to the estimator :param input_fn_dict : dictionary", ": input function providing tf.data.Dataset to the estimator :param input_fn_dict", "print(\"Creating estimator...\") est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) # 4. Train", "Imports import os import numpy as np import tensorflow as", "Y, optimizer=None, nb_epochs=30, nb_batches=128): \"\"\" Run the estimator \"\"\" if", "optimizer=None, model_dir=None): \"\"\" Overloaded function to create an estimator using", "for eval input_fn :param model_dir : directory to store the", "tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) # 4. Train and Evaluate the model", "momentum=0.9, nesterov=True) # 2. compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy',", "# training spec train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) # evaluation", "= tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True ) #", "tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) # evaluation spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict))", "model_dir) print(\"Model path chosen : \", dir_path) if (not os.path.exists(dir_path)):", "estimator \"\"\" if optimizer is None: optimizer = tf.keras.estimators.SGD( lr=0.0009,", "input_fn :param eval_fn_dict : dictionary containing params for eval input_fn", "optimizer is None if (optimizer is None): optimizer = tf.keras.optimizers.SGD(", "metrics=['accuracy']) # 3. create estimator dir_path = os.path.join(os.getcwd(), model_dir) print(\"Model", "Compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 2. Create", "model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 3. create estimator dir_path =", "__future__ import print_function # Imports import os import numpy as", "# Imports import os import numpy as np import tensorflow", "4b. Evaluate the model model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est,", "model, input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None): \"\"\" Overloaded function", "run_from_generator( model, input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None): \"\"\" Overloaded", "the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate # 4a. Evaluate the", "estimator...\") est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) # 4. Train and", "an estimator model_est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') # Training #", "Overloaded function to create an estimator using tf.data.Dataset :param model", "function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs, shuffle=True", "input function providing tf.data.Dataset to the estimator :param input_fn_dict :", "# Evaluate # 4a. Evaluate the model eval_input_fn = tf.estimator.inputs.numpy_input_fn(", "= tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True) # 1. Compile the", "__future__ import absolute_import from __future__ import division from __future__ import", "Create an estimator model_est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') # Training", "model_dir='./lenet') # Training # 3a. Create the training function train_input_fn", "eval input_fn :param model_dir : directory to store the trained", ": directory to store the trained model \"\"\" # 1.", "# 3. create estimator dir_path = os.path.join(os.getcwd(), model_dir) print(\"Model path", "training model_est = tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), # steps=None)", "Evaluate # 4a. Evaluate the model eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]:", "# 3a. Create the training function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]:", "shuffle=True ) # 3b. Train the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) #", "optimizer = tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True) # 2. compile", ": \", dir_path) if (not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\") est", "from __future__ import division from __future__ import print_function # Imports", "# Run the training model_est = tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda:", "compile model if optimizer is None if (optimizer is None):", "input_fn :param model_dir : directory to store the trained model", "model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est, model_eval def run_from_generator( model, input_func=None, input_func_dict=None,", "decay=1e-5, momentum=0.9, nesterov=True) # 1. Compile the model model.compile( optimizer=optimizer,", "dir_path = os.path.join(os.getcwd(), model_dir) print(\"Model path chosen : \", dir_path)", "estimator model_est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir='./lenet') # Training # 3a.", ") # 3b. Train the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate", "absolute_import from __future__ import division from __future__ import print_function #", "print(model_eval) return model_est, model_eval def run_from_generator( model, input_func=None, input_func_dict=None, eval_func_dict=None,", "(not os.path.exists(dir_path)): os.mkdir(dir_path) print(\"Creating estimator...\") est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path)", "2. compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 3.", "model_est = tf.estimator.train_and_evaluate(est, train_spec, eval_spec) #est.train(input_fn=lambda: input_func(input_func_dict), # steps=None) #", "import tensorflow as tf def run(model, X, Y, optimizer=None, nb_epochs=30,", "Run the estimator \"\"\" if optimizer is None: optimizer =", "Create the training function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['train'].astype(np.float32)}, y=Y['train'].astype(np.float32),", "None): optimizer = tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9, nesterov=True) # 2.", "model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 2. Create an estimator", "spec train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) # evaluation spec eval_spec", "model_dir=None): \"\"\" Overloaded function to create an estimator using tf.data.Dataset", "# evaluation spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run the", "nesterov=True) # 2. compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])", "store the trained model \"\"\" # 1. Create optimizer and", "# 3b. Train the model model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate #", "train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) # evaluation spec eval_spec =", "from __future__ import print_function # Imports import os import numpy", "# 1. Compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) #", "optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 2. Create an estimator model_est =", "nb_epochs=10, optimizer=None, model_dir=None): \"\"\" Overloaded function to create an estimator", "directory to store the trained model \"\"\" # 1. Create", "model \"\"\" # 1. Create optimizer and compile model if", "loss='categorical_crossentropy', metrics=['accuracy']) # 3. create estimator dir_path = os.path.join(os.getcwd(), model_dir)", "# 4b. Evaluate the model model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return", "1. Compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 2.", "if (optimizer is None): optimizer = tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5, momentum=0.9,", "max_steps=500) # evaluation spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda: input_func(eval_func_dict)) # Run", "the model print(\"Training...\") # training spec train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict),", "input_func(eval_func_dict)) # Run the training model_est = tf.estimator.train_and_evaluate(est, train_spec, eval_spec)", "optimizer = tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True) # 1. Compile", "model_est.train(input_fn=train_input_fn, steps=nb_epochs*nb_batches) # Evaluate # 4a. Evaluate the model eval_input_fn", "tensorflow as tf def run(model, X, Y, optimizer=None, nb_epochs=30, nb_batches=128):", "None if (optimizer is None): optimizer = tf.keras.optimizers.SGD( lr=1e-3, decay=1e-5,", "Train and Evaluate the model print(\"Training...\") # training spec train_spec", "the estimator \"\"\" if optimizer is None: optimizer = tf.keras.estimators.SGD(", "is None: optimizer = tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True) #", "the trained model \"\"\" # 1. Create optimizer and compile", "model_eval = model_est.evaluate(input_fn=eval_input_fn) print(model_eval) return model_est, model_eval def run_from_generator( model,", "= tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) # 4. Train and Evaluate the", "params for eval input_fn :param model_dir : directory to store", "the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 2. Create an", "model :param input_fn : input function providing tf.data.Dataset to the", "3. create estimator dir_path = os.path.join(os.getcwd(), model_dir) print(\"Model path chosen", "\"\"\" if optimizer is None: optimizer = tf.keras.estimators.SGD( lr=0.0009, decay=1e-5,", "the model eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)}, y=Y['test'].astype(np.float32), batch_size=nb_batches, num_epochs=nb_epochs,", "model_eval def run_from_generator( model, input_func=None, input_func_dict=None, eval_func_dict=None, nb_epochs=10, optimizer=None, model_dir=None):", "= tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) # evaluation spec eval_spec = tf.estimator.EvalSpec(input_fn=lambda:", "print(\"Training...\") # training spec train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) #", "import absolute_import from __future__ import division from __future__ import print_function", "est = tf.keras.estimator.model_to_estimator( keras_model=model, model_dir=dir_path) # 4. Train and Evaluate", "an estimator using tf.data.Dataset :param model : uncompiled keras model", "nesterov=True) # 1. Compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])", "optimizer is None: optimizer = tf.keras.estimators.SGD( lr=0.0009, decay=1e-5, momentum=0.9, nesterov=True)", "# 4a. Evaluate the model eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={model.input_names[0]: X['test'].astype(np.float32)},", "momentum=0.9, nesterov=True) # 1. Compile the model model.compile( optimizer=optimizer, loss='categorical_crossentropy',", "os import numpy as np import tensorflow as tf def", "input_fn_dict : dictionary containing input params for input_fn :param eval_fn_dict", "training spec train_spec = tf.estimator.TrainSpec(input_fn=lambda: input_func(input_func_dict), max_steps=500) # evaluation spec" ]
[ "\"\"\" @classmethod def find_bundle_dir(cls, path): \"\"\" Included for similarity with", "just keeps track of some state with an unzipped app", "= abc.ABCMeta # we use abc.abstractmethod throughout because there are", "Check if this is, in fact, an archive of this", "process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod def archive(cls, containing_dir,", "target_path): \"\"\" Copy the uncompressed archive somewhere else, return initialized", "just yet. This recapitulates a very similar precheck in the", "@abc.abstractmethod def archive(cls, path, output_path): \"\"\" Archive a directory to", "archive for that resigned app \"\"\" if not exists(input_path): raise", "Unified interface to extract any kind of archive from a", "is the \"Containing dir\", the dir at the root level", "in archive') return relative_bundle_dir @classmethod def _get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir,", "*containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths def process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately,", "helper_name not in helper_paths or helper_paths[helper_name] is None: # note,", "IOError(\"{0} not found\".format(input_path)) ua = None bundle_info = None try:", "that runs on the Watch # Info.plist <-- WKWatchKitApp=True #", "# So we move it to the output_path later. #", "{}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate)) log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile)) signer", "\"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path) if len(watchkit_paths) > 0: if should_remove:", "import shutil import zipfile REMOVE_WATCHKIT = True helper_paths = {}", "for helper_name in cls.helpers: if get_helper(helper_name) is None: log.error(\"missing helper", "credentials, and create a similar archive for that resigned app", "to remove it, so that's the default. Remove when https://github.com/saucelabs/isign/issues/20", "= ['.zip'] helpers = ['zip', 'unzip'] @classmethod def is_helpers_present(cls): \"\"\"", "dealing with, return an archive object. Returns None if path", "an AppArchive archive) relative bundle dir is the dir containing", "is_helpers_present(cls): \"\"\" returns False if any of our helper apps", "Watch # Info.plist <-- WKWatchKitApp=True # watchkit_paths = [] for", "class IpaArchive(AppZipArchive): \"\"\" IPA is Apple's standard for distributing apps.", "b/c AppArchive simply moves # it to the desired target", "log.debug('removing ua: %s', self.path) shutil.rmtree(self.path) def archive_factory(path): \"\"\" Guess what", "ContainingDir/Payload/something.app This class is also useful if you have an", "if any of our helper apps wasn't found in class", "retrying until found helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got executable {} for", "@classmethod def precheck(cls, path): if not isdir(path): return False if", "be re-zipped. \"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$' extensions = ['.zip'] helpers", "certificate, key, apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): \"\"\" Unified interface", "view(input_path): if not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) ua =", "root level of the unzipped archive (or the dir itself,", "similarity with the zipped archive classes. In this case, the", "= relative_bundle_dir self.archive_class = archive_class bundle_path = normpath(join(path, relative_bundle_dir)) self.bundle", "structure, compression, etc \"\"\" @classmethod def find_bundle_dir(cls, path): \"\"\" Included", "def view(input_path): if not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) ua", "b/c we don't want to make temp dirs just yet.", "of app. Have to examine within the zipfile, b/c we", "{} log = logging.getLogger(__name__) def get_helper(helper_name): \"\"\" find paths to", "this up into a zipfile. Note this is a classmethod,", "resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): \"\"\" Unified", "containing_dir = make_temp_dir() log.debug(\"unarchiving to temp... %s -> %s\", self.path,", "relative bundle dir is the dir containing the bundle, e.g.", "path, _, _ in os.walk(root_bundle_path): if path == root_bundle_path: continue", "This just keeps track of some state with an unzipped", "get_watchkit_paths(root_bundle_path) if len(watchkit_paths) > 0: if should_remove: for path in", "ua.bundle.info ua.archive(output_path) except NotSignable as e: msg = \"Not signable:", "is a classmethod, because the caller will use us on", "temp directory just # to construct the zip file. This", "and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\" IPA is Apple's standard", "classmethod, because the caller will use us on a temp", "is stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir, 'temp.zip') call([get_helper('zip'),", "you have an app that's already unzipped and you want", "output path \"\"\" pass @abc.abstractmethod def get_info(cls, path): \"\"\" Obtain", "don't want to make temp dirs just yet. This recapitulates", "class init \"\"\" is_present = True for helper_name in cls.helpers:", "False if any of our helper apps wasn't found in", "== root_bundle_path: continue try: bundle = Bundle(path) except NotMatched: #", "# this directory is not a bundle continue if bundle.info.get('WKWatchKitApp')", "down, like in a ContainingDir/Payload/something.app This class is also useful", "file_name) if matched: apps.add(matched.group(1)) if len(apps) == 1: log.debug(\"found one", "zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def", "path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls, path): if not isdir(path):", "= archive.unarchive_to_temp() bundle_info = ua.bundle.info finally: if ua is not", "zipfile\") zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is", "\"\"\" Locate the directory of the main app (aka bundle)", "and you want to sign it. \"\"\" def __init__(self, path,", "with key: {}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate)) log.debug('Signing with provisioning_profile:", "not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert))", "make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles of this", "app, except it's zipped up, and when repackaged, should be", "path): if not isdir(path): return False if not os.path.exists(cls._get_plist_path(path)): return", "import tempfile import re from subprocess import call from signer", "type \"\"\" pass @abc.abstractmethod def find_bundle_dir(cls, path): \"\"\" Locate the", "bundle_info = ua.bundle.info ua.archive(output_path) except NotSignable as e: msg =", "# it to the desired target when done if exists(self.path)", "tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles of this bundle that", "= path self.relative_bundle_dir = relative_bundle_dir self.archive_class = archive_class bundle_path =", "log = logging.getLogger(__name__) def get_helper(helper_name): \"\"\" find paths to executables.", "log.debug('extension match') for extension in cls.extensions: log.debug('extension match: %s', extension)", "cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is not None: plist_path = cls._get_plist_path(relative_bundle_dir) if", "shutil.copytree(self.path, target_path) return self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def remove(self): # the", "the Watch # Info.plist <-- WKWatchKitApp=True # watchkit_paths = []", "but slightly different paths \"\"\" extensions = ['.ipa'] app_dir_pattern =", "unzipped app archive and how to re-zip it back up", "match any archive type \"\"\" archive = None for cls", "= join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path)", "app archive. This is an app at rest, whether it's", "path \"\"\" pass @abc.abstractmethod def get_info(cls, path): \"\"\" Obtain app", "kind of archive from a temporary file, resign it with", "from os.path import abspath, dirname, exists, isdir, isfile, join, normpath", "case of an AppArchive archive) relative bundle dir is the", "a temp file, then resign them, and create an archive", "(cls.__name__, output_path)) def __init__(self, path): self.path = path self.relative_bundle_dir =", "\"\"\" Unarchive and copy to a temp directory \"\"\" pass", "len(watchkit_paths) > 0: if should_remove: for path in watchkit_paths: log.warning(\"Removing", "(aka bundle) \"\"\" pass class AppArchive(Archive): \"\"\" The simplest form", "to sign it. \"\"\" def __init__(self, path, relative_bundle_dir, archive_class): \"\"\"", "with certificate: {}'.format(certificate)) log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate,", "bundle = Bundle(path) except NotMatched: # this directory is not", "is generally harmless to remove it, so that's the default.", "join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod def", "\"\"\" IPA is Apple's standard for distributing apps. Much like", "if path did not match any archive type \"\"\" archive", "naked app bundle in a directory, or a zipped app", "want to sign it. \"\"\" def __init__(self, path, relative_bundle_dir, archive_class):", "have an app that's already unzipped and you want to", "(or the dir itself, in the case of an AppArchive", "out, depending on what the original archive class did \"\"\"", "@classmethod def is_helpers_present(cls): \"\"\" returns False if any of our", "the directory \"\"\" return path @classmethod def _get_plist_path(cls, path): return", "in file_list: matched = re.match(cls.app_dir_pattern, file_name) if matched: apps.add(matched.group(1)) if", "In this case, the bundle dir *is* the directory \"\"\"", "app archive and how to re-zip it back up once", "def archive(cls, path, output_path): if exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived", "Represents an app archive. This is an app at rest,", "def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir = None apps = set() file_list", "the root level of the unzipped archive (or the dir", "if exists(self.path) and isdir(self.path): log.debug('removing ua: %s', self.path) shutil.rmtree(self.path) def", "log.debug(\"got executable {} for {}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name] def make_temp_dir():", "<-- this is the part that runs on the Watch", "if not os.path.exists(cls._get_plist_path(path)): return False plist = cls.get_info(path) is_native =", "keeps track of some state with an unzipped app archive", "bundle_path = normpath(join(path, relative_bundle_dir)) self.bundle = App(bundle_path) def archive(self, output_path):", "with the zipped archive classes. In this case, the bundle", "is located somewhere inside the containing directory, but might be", "an app that's already unzipped and you want to sign", "the zipfile, b/c we don't want to make temp dirs", "type found') ua = archive.unarchive_to_temp() if info_props: # Override info.plist", "be a few directories down, like in a ContainingDir/Payload/something.app This", "in fact, an archive of this type \"\"\" pass @abc.abstractmethod", "\"\"\" self.path = path self.relative_bundle_dir = relative_bundle_dir self.archive_class = archive_class", "if should_remove: for path in watchkit_paths: log.warning(\"Removing WatchKit bundle {}\".format(path))", "is an archive, and a zipfile\") zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir", "path, cls.__name__) break return archive def view(input_path): if not exists(input_path):", "app (aka bundle) \"\"\" pass class AppArchive(Archive): \"\"\" The simplest", "a temp directory \"\"\" pass @abc.abstractmethod def archive(cls, path, output_path):", "os.path.exists(cls._get_plist_path(path)): return False plist = cls.get_info(path) is_native = is_info_plist_native(plist) log.debug(\"is_native:", "log.debug(\"unarchiving to temp... %s -> %s\", self.path, containing_dir) shutil.rmtree(containing_dir) #", "signer_key_file=key, apple_cert_file=apple_cert) ua = None bundle_info = None try: archive", "output_path later. # # We also do a little dance", "if temp_zip_dir is not None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive):", "self.bundle_info = self.get_info(self.path) def unarchive_to_temp(self): containing_dir = make_temp_dir() log.debug(\"unarchiving to", "raise finally: if ua is not None: ua.remove() return bundle_info", "wasn't found in class init \"\"\" is_present = True for", "= cls.get_info(path) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod", "REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.', self.__class__) class AppZipArchive(Archive): \"\"\" Just like", "This recapitulates a very similar precheck in the Bundle class", "relative_bundle_dir @classmethod def _get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\") @classmethod def", "once re-signed. The bundle is located somewhere inside the containing", "ua = archive.unarchive_to_temp() bundle_info = ua.bundle.info finally: if ua is", "return path @classmethod def _get_plist_path(cls, path): return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod", "have watchkit \"\"\" # typical structure: # # app_bundle #", "UncompressedArchive(containing_dir, '.', self.__class__) class AppZipArchive(Archive): \"\"\" Just like an app,", "continue try: bundle = Bundle(path) except NotMatched: # this directory", "or an IPA. We have a common interface to extract", "root_bundle_path: continue try: bundle = Bundle(path) except NotMatched: # this", "\"\"\" Unified interface to extract any kind of archive from", "import spawn import logging import os from os.path import abspath,", "self.archive_class.archive(self.path, output_path) def clone(self, target_path): \"\"\" Copy the uncompressed archive", "target when done if exists(self.path) and isdir(self.path): log.debug('removing ua: %s',", "import Signer import shutil import zipfile REMOVE_WATCHKIT = True helper_paths", "archive class did \"\"\" self.archive_class.archive(self.path, output_path) def clone(self, target_path): \"\"\"", "process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.', self.__class__) class AppZipArchive(Archive): \"\"\" Just", "to the output_path later. # # We also do a", "self.relative_bundle_dir = '.' self.bundle_info = self.get_info(self.path) def unarchive_to_temp(self): containing_dir =", "{}'.format(certificate)) log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert)", "in watchkit_paths: log.warning(\"Removing WatchKit bundle {}\".format(path)) shutil.rmtree(path) else: raise NotSignable(\"Cannot", "def unarchive_to_temp(self): containing_dir = make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path, \"-d\", containing_dir])", "break return is_present @classmethod def is_archive_extension_match(cls, path): \"\"\" does this", "if not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) ua = None", "found') ua = archive.unarchive_to_temp() bundle_info = ua.bundle.info finally: if ua", "= cls(path) log.debug(\"File %s matched as %s\", path, cls.__name__) break", "it # does not have an extension. But we want", "join(relative_bundle_dir, \"Info.plist\") @classmethod def precheck(cls, path): \"\"\" Checks if an", "found in archive') else: log.warning('no apps found in archive') return", "except NotSignable as e: msg = \"Not signable: <{0}>: {1}\\n\".format(input_path,", "adds \".zip\" if it # does not have an extension.", "it is generally harmless to remove it, so that's the", "form of archive -- a naked App Bundle, with no", "functionality, it is generally harmless to remove it, so that's", "directory \"\"\" pass @abc.abstractmethod def archive(cls, path, output_path): \"\"\" Archive", "if path == root_bundle_path: continue try: bundle = Bundle(path) except", "these apps to a temp file, then resign them, and", "at the root level of the unzipped archive (or the", "self.path) shutil.rmtree(self.path) def archive_factory(path): \"\"\" Guess what kind of archive", "we move it to the output_path later. # # We", "watchkit_paths = get_watchkit_paths(root_bundle_path) if len(watchkit_paths) > 0: if should_remove: for", "app bundle in a directory, or a zipped app bundle,", "yet sign WatchKit bundles\") class Archive(object): __metaclass__ = abc.ABCMeta #", "= r'^([^/]+\\.app/).*$' extensions = ['.zip'] helpers = ['zip', 'unzip'] @classmethod", "an archive, and a zipfile\") zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir =", "runs on the Watch # Info.plist <-- WKWatchKitApp=True # watchkit_paths", "Signer import shutil import zipfile REMOVE_WATCHKIT = True helper_paths =", "archive_factory(input_path) if archive is None: raise NotMatched('No matching archive type", "['.zip'] helpers = ['zip', 'unzip'] @classmethod def is_helpers_present(cls): \"\"\" returns", "necessary because zip always adds \".zip\" if it # does", "zipped up, and when repackaged, should be re-zipped. \"\"\" app_dir_pattern", "{}: {}\".format(cls.__name__, helper_name)) is_present = False break return is_present @classmethod", "respect the desired # output_path's extension, which could be \".ipa\"", "to %s\" % (cls.__name__, output_path)) finally: if temp_zip_dir is not", "of this type \"\"\" pass @abc.abstractmethod def find_bundle_dir(cls, path): \"\"\"", "zip is stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir, 'temp.zip')", "raise IOError(\"{0} not found\".format(input_path)) ua = None bundle_info = None", "self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self): containing_dir = make_temp_dir() call([get_helper('unzip'),", "WatchKit bundle {}\".format(path)) shutil.rmtree(path) else: raise NotSignable(\"Cannot yet sign WatchKit", "@classmethod def _get_plist_path(cls, path): return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def get_info(cls,", "cls.get_info(path) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def", "might be a few directories down, like in a ContainingDir/Payload/something.app", "this is a classmethod, because the caller will use us", "def unarchive_to_temp(self): containing_dir = make_temp_dir() log.debug(\"unarchiving to temp... %s ->", "= \"Not signable: <{0}>: {1}\\n\".format(input_path, e) log.info(msg) raise finally: if", "a directory, or a zipped app bundle, or an IPA.", "extension, which could be \".ipa\" or who knows. # So", "we don't want to make temp dirs just yet. This", "\"\"\" self.archive_class.archive(self.path, output_path) def clone(self, target_path): \"\"\" Copy the uncompressed", "a very similar precheck in the Bundle class \"\"\" if", "structure: # # app_bundle # ... # some_directory # watchkit_extension", "info.plist props of the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path)", "= None try: archive = archive_factory(input_path) if archive is None:", "re-zipped. \"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$' extensions = ['.zip'] helpers =", "not in helper_paths or helper_paths[helper_name] is None: # note, find_executable", "examine within the zipfile, b/c we don't want to make", "# the containing dir might be gone already b/c AppArchive", "inside the containing directory, but might be a few directories", "exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived %s to %s\" % (cls.__name__,", "try: # need to chdir and use relative paths, because", "executables. Cached in helper_paths \"\"\" if helper_name not in helper_paths", "if len(watchkit_paths) > 0: if should_remove: for path in watchkit_paths:", "who knows. # So we move it to the output_path", "is_info_plist_native from exceptions import MissingHelpers, NotSignable, NotMatched from distutils import", "output_path): \"\"\" Archive a directory to an output path \"\"\"", "re.match(cls.app_dir_pattern, file_name) if matched: apps.add(matched.group(1)) if len(apps) == 1: log.debug(\"found", "return False if not cls.is_helpers_present(): raise MissingHelpers(\"helpers not present\") is_native", "is safer. temp_zip_dir = None try: # need to chdir", "Info.plist without unarchiving \"\"\" pass @abc.abstractmethod def precheck(cls, path): \"\"\"", "abc import biplist from bundle import App, Bundle, is_info_plist_native from", "temporary file, resign it with these credentials, and create a", "the dir at the root level of the unzipped archive", "us on a temp directory somewhere \"\"\" # the temp", "archive = None for cls in [IpaArchive, AppZipArchive, AppArchive]: if", "compression, etc \"\"\" @classmethod def find_bundle_dir(cls, path): \"\"\" Included for", "return initialized UncompressedArchive \"\"\" shutil.copytree(self.path, target_path) return self.__class__(target_path, self.relative_bundle_dir, self.archive_class)", "different paths \"\"\" extensions = ['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class", "\"\"\" pass @abc.abstractmethod def archive(cls, path, output_path): \"\"\" Archive a", "<-- WKWatchKitApp=True # watchkit_paths = [] for path, _, _", "found # in other words, we keep retrying until found", "need to chdir and use relative paths, because zip is", "the unzipped archive (or the dir itself, in the case", "the caller will use us on a temp directory somewhere", "relative paths, because zip is stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file", "a little dance with making another temp directory just #", "log.debug('path: %s', path) if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this is an", "True return False @classmethod def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir = None", "with an unzipped app archive and how to re-zip it", "= ['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\" This just", "dir\", the dir at the root level of the unzipped", "import App, Bundle, is_info_plist_native from exceptions import MissingHelpers, NotSignable, NotMatched", "NotSignable, NotMatched from distutils import spawn import logging import os", "NotMatched('No matching archive type found') ua = archive.unarchive_to_temp() bundle_info =", "for extension in cls.extensions: log.debug('extension match: %s', extension) if path.endswith(extension):", "exist already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.', self.__class__)", "def __init__(self, path, relative_bundle_dir, archive_class): \"\"\" Path is the \"Containing", "info_props: # Override info.plist props of the parent bundle ua.bundle.update_info_props(info_props)", "will use us on a temp directory somewhere \"\"\" #", "methods we want to ensure are implemented. @abc.abstractmethod def unarchive_to_temp(self):", "return join(relative_bundle_dir, \"Info.plist\") @classmethod def precheck(cls, path): \"\"\" Checks if", "into a zipfile. Note this is a classmethod, because the", "zip always adds \".zip\" if it # does not have", "None try: # need to chdir and use relative paths,", "it's a naked app bundle in a directory, or a", "zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self):", "if exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived %s to %s\" %", "an unused # filename. Also, `zip` won't overwrite existing files,", "if archive is None: raise NotSignable('No matching archive type found')", "call([get_helper('unzip'), \"-qu\", self.path, \"-d\", containing_dir]) app_dir = abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir,", "Checks if an archive looks like this kind of app.", "*is* the directory \"\"\" return path @classmethod def _get_plist_path(cls, path):", "tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"], cwd=containing_dir)", "class did \"\"\" self.archive_class.archive(self.path, output_path) def clone(self, target_path): \"\"\" Copy", "implemented. @abc.abstractmethod def unarchive_to_temp(self): \"\"\" Unarchive and copy to a", "it's zipped up, and when repackaged, should be re-zipped. \"\"\"", "self.path = path zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info", "because the caller will use us on a temp directory", "returns None is not found # in other words, we", "\"\"\" Re-zip this back up, or simply copy it out,", "output_path)) def __init__(self, path): self.path = path self.relative_bundle_dir = '.'", "init \"\"\" is_present = True for helper_name in cls.helpers: if", "another temp directory just # to construct the zip file.", "self.path = path self.relative_bundle_dir = '.' self.bundle_info = self.get_info(self.path) def", "an archive of the same type \"\"\" import abc import", "original archive class did \"\"\" self.archive_class.archive(self.path, output_path) def clone(self, target_path):", "directory structure, compression, etc \"\"\" @classmethod def find_bundle_dir(cls, path): \"\"\"", "def __init__(self, path): self.path = path zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir", "cls.precheck(path): archive = cls(path) log.debug(\"File %s matched as %s\", path,", "to extract these apps to a temp file, then resign", "find_bundle_dir(cls, zipfile_obj): relative_bundle_dir = None apps = set() file_list =", "Also, `zip` won't overwrite existing files, so this is safer.", "%s matched as %s\", path, cls.__name__) break return archive def", "return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles of this bundle", "the case of an AppArchive archive) relative bundle dir is", "\"Containing dir\", the dir at the root level of the", "gone already b/c AppArchive simply moves # it to the", "the part that runs on the Watch # Info.plist <--", "archive -- a naked App Bundle, with no extra directory", "temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived %s to %s\" %", "not None: ua.remove() return bundle_info def resign(input_path, certificate, key, apple_cert,", "path): \"\"\" Check if this is, in fact, an archive", "break return archive def view(input_path): if not exists(input_path): raise IOError(\"{0}", "of the same type \"\"\" import abc import biplist from", "\"\"\" archive = None for cls in [IpaArchive, AppZipArchive, AppArchive]:", "@classmethod def precheck(cls, path): \"\"\" Checks if an archive looks", "@abc.abstractmethod def unarchive_to_temp(self): \"\"\" Unarchive and copy to a temp", "= False break return is_present @classmethod def is_archive_extension_match(cls, path): \"\"\"", "# typical structure: # # app_bundle # ... # some_directory", "ua.remove() return bundle_info def resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path,", "\"\"\" import abc import biplist from bundle import App, Bundle,", "knows. # So we move it to the output_path later.", "WatchKit. If you don't care about watchkit functionality, it is", "if matched: apps.add(matched.group(1)) if len(apps) == 1: log.debug(\"found one app\")", "@classmethod def _get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\") @classmethod def precheck(cls,", "containing_dir = make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path, \"-d\", containing_dir]) app_dir =", "__init__(self, path, relative_bundle_dir, archive_class): \"\"\" Path is the \"Containing dir\",", "\".zip\" if it # does not have an extension. But", "object. Returns None if path did not match any archive", "dirs just yet. This recapitulates a very similar precheck in", "self.relative_bundle_dir = relative_bundle_dir self.archive_class = archive_class bundle_path = normpath(join(path, relative_bundle_dir))", "the bundle dir *is* the directory \"\"\" return path @classmethod", "log.debug('extension match: %s', extension) if path.endswith(extension): return True return False", "kind of archive this was (Ipa, etc.) \"\"\" self.path =", "Note this is a classmethod, because the caller will use", "% (cls.__name__, output_path)) def __init__(self, path): self.path = path self.relative_bundle_dir", "path): \"\"\" Included for similarity with the zipped archive classes.", "signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua = None bundle_info =", "up, and when repackaged, should be re-zipped. \"\"\" app_dir_pattern =", "simply moves # it to the desired target when done", "be gone already b/c AppArchive simply moves # it to", "normpath import tempfile import re from subprocess import call from", "NotSignable as e: msg = \"Not signable: <{0}>: {1}\\n\".format(input_path, e)", "and a zipfile\") zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if", "IPA. We have a common interface to extract these apps", "is_present = True for helper_name in cls.helpers: if get_helper(helper_name) is", "# the temp file is necessary because zip always adds", "is not a bundle continue if bundle.info.get('WKWatchKitApp') is True: #", "= cls.get_info(relative_bundle_dir, zipfile_obj) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native", "the \"Containing dir\", the dir at the root level of", "exists(input_path): raise IOError(\"{0} not found\".format(input_path)) ua = None bundle_info =", "helper_name)) return helper_paths[helper_name] def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\"", "archive class is the kind of archive this was (Ipa,", "alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path) except NotSignable as e: msg", "how to re-zip it back up once re-signed. The bundle", "want to respect the desired # output_path's extension, which could", "watchkit_paths: log.warning(\"Removing WatchKit bundle {}\".format(path)) shutil.rmtree(path) else: raise NotSignable(\"Cannot yet", "an archive of this type \"\"\" pass @abc.abstractmethod def find_bundle_dir(cls,", "few directories down, like in a ContainingDir/Payload/something.app This class is", "not a bundle continue if bundle.info.get('WKWatchKitApp') is True: # get", "in zipfile_obj.namelist(): return False plist = cls.get_info(relative_bundle_dir, zipfile_obj) is_native =", "a bundle continue if bundle.info.get('WKWatchKitApp') is True: # get the", "cls.is_helpers_present(): raise MissingHelpers(\"helpers not present\") is_native = False log.debug('precheck') log.debug('path:", "you want to sign it. \"\"\" def __init__(self, path, relative_bundle_dir,", "archive (or the dir itself, in the case of an", "this path have the right extension \"\"\" log.debug('extension match') for", "@classmethod def get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls, path):", "if get_helper(helper_name) is None: log.error(\"missing helper for class {}: {}\".format(cls.__name__,", "with provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua =", "in a directory, or a zipped app bundle, or an", "pass @abc.abstractmethod def precheck(cls, path): \"\"\" Check if this is,", "# in other words, we keep retrying until found helper_paths[helper_name]", "% (cls.__name__, output_path)) finally: if temp_zip_dir is not None and", "not None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\" IPA is", "as e: msg = \"Not signable: <{0}>: {1}\\n\".format(input_path, e) log.info(msg)", "The simplest form of archive -- a naked App Bundle,", "key, apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): \"\"\" Unified interface to", "provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): \"\"\" Unified interface to extract any", "is the best way to ensure the an unused #", "@abc.abstractmethod def precheck(cls, path): \"\"\" Check if this is, in", "also useful if you have an app that's already unzipped", "paths, because zip is stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file =", "found\".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key)) log.debug('Signing", "archive def view(input_path): if not exists(input_path): raise IOError(\"{0} not found\".format(input_path))", "does this path have the right extension \"\"\" log.debug('extension match')", "# watchkit_extension <-- this is the watchkit bundle # Info.plist", "'.' self.bundle_info = self.get_info(self.path) def unarchive_to_temp(self): containing_dir = make_temp_dir() log.debug(\"unarchiving", "App, Bundle, is_info_plist_native from exceptions import MissingHelpers, NotSignable, NotMatched from", "an extension. But we want to respect the desired #", "# some_directory # watchkit_extension <-- this is the watchkit bundle", "in class init \"\"\" is_present = True for helper_name in", "app at rest, whether it's a naked app bundle in", "bundle in a directory, or a zipped app bundle, or", "archive of the same type \"\"\" import abc import biplist", "this is, in fact, an archive of this type \"\"\"", "log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def archive(cls, path, output_path): if", "in a ContainingDir/Payload/something.app This class is also useful if you", "try: archive = archive_factory(input_path) if archive is None: raise NotSignable('No", "the best way to ensure the an unused # filename.", "UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod def archive(cls, containing_dir, output_path): \"\"\" archive", "= Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua = None bundle_info = None", "zipfile_obj.namelist(): return False plist = cls.get_info(relative_bundle_dir, zipfile_obj) is_native = is_info_plist_native(plist)", "output_path): if exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived %s to %s\"", "paths to executables. Cached in helper_paths \"\"\" if helper_name not", "not found # in other words, we keep retrying until", "an app at rest, whether it's a naked app bundle", "Bundle class \"\"\" if not isfile(path): return False if not", "= archive_class bundle_path = normpath(join(path, relative_bundle_dir)) self.bundle = App(bundle_path) def", "def get_info(cls, path): \"\"\" Obtain app metadata from Info.plist without", "elif len(apps) > 1: log.warning('more than one app found in", "path zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir,", "like an app, except it's zipped up, and when repackaged,", "like in a ContainingDir/Payload/something.app This class is also useful if", "AppZip, but slightly different paths \"\"\" extensions = ['.ipa'] app_dir_pattern", "output_path) log.info(\"archived %s to %s\" % (cls.__name__, output_path)) finally: if", "bundle_info def resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None):", "dir containing the bundle, e.g. Payload/Foo.app archive class is the", "\"\"\" if not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) log.debug('Signing with", "desired target when done if exists(self.path) and isdir(self.path): log.debug('removing ua:", "log.info(\"archived %s to %s\" % (cls.__name__, output_path)) def __init__(self, path):", "None: log.error(\"missing helper for class {}: {}\".format(cls.__name__, helper_name)) is_present =", "{}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate)) log.debug('Signing", "_get_plist_path(cls, path): return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def get_info(cls, path): return", "return biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls, path): if not isdir(path): return", "# Info.plist # watchkit_bundle <-- this is the part that", "state with an unzipped app archive and how to re-zip", "an app archive. This is an app at rest, whether", "in cls.extensions: log.debug('extension match: %s', extension) if path.endswith(extension): return True", "path.endswith(extension): return True return False @classmethod def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir", "'unzip'] @classmethod def is_helpers_present(cls): \"\"\" returns False if any of", "True: # get the *containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths def", "for class {}: {}\".format(cls.__name__, helper_name)) is_present = False break return", "are certain class # methods we want to ensure are", "raise NotSignable(\"Cannot yet sign WatchKit bundles\") class Archive(object): __metaclass__ =", "are implemented. @abc.abstractmethod def unarchive_to_temp(self): \"\"\" Unarchive and copy to", "matching archive type found') ua = archive.unarchive_to_temp() if info_props: #", "simplest form of archive -- a naked App Bundle, with", "return False plist = cls.get_info(path) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native))", "if an archive looks like this kind of app. Have", "class is also useful if you have an app that's", "is_present = False break return is_present @classmethod def is_archive_extension_match(cls, path):", "def find_bundle_dir(cls, path): \"\"\" Locate the directory of the main", "# we use abc.abstractmethod throughout because there are certain class", "# output_path's extension, which could be \".ipa\" or who knows.", "apple_cert_file=apple_cert) ua = None bundle_info = None try: archive =", "\"\"\" Just like an app, except it's zipped up, and", "return False @classmethod def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir = None apps", "None apps = set() file_list = zipfile_obj.namelist() for file_name in", "on the Watch # Info.plist <-- WKWatchKitApp=True # watchkit_paths =", "\"\"\" # typical structure: # # app_bundle # ... #", "= is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def get_info(cls, relative_bundle_dir,", "is an app at rest, whether it's a naked app", "zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def __init__(self, path): self.path = path zipfile_obj", "app metadata from Info.plist without unarchiving \"\"\" pass @abc.abstractmethod def", "self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def remove(self): # the containing dir might", "containing_dir) shutil.rmtree(containing_dir) # quirk of copytree, top dir can't exist", "= zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj) def", "def get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls, path): if", "for file_name in file_list: matched = re.match(cls.app_dir_pattern, file_name) if matched:", "REMOVE_WATCHKIT = True helper_paths = {} log = logging.getLogger(__name__) def", "import re from subprocess import call from signer import Signer", "path): \"\"\" Locate the directory of the main app (aka", "Bundle, with no extra directory structure, compression, etc \"\"\" @classmethod", "helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got executable {} for {}\".format(helper_paths[helper_name], helper_name)) return", "we use abc.abstractmethod throughout because there are certain class #", "the containing directory, but might be a few directories down,", "archive we are dealing with, return an archive object. Returns", "have an extension. But we want to respect the desired", "return helper_paths[helper_name] def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\" collect", "bundle that have watchkit \"\"\" # typical structure: # #", "archive') return relative_bundle_dir @classmethod def _get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\")", "archive classes. In this case, the bundle dir *is* the", "abc.ABCMeta # we use abc.abstractmethod throughout because there are certain", "that have watchkit \"\"\" # typical structure: # # app_bundle", "on a temp directory somewhere \"\"\" # the temp file", "should_remove: for path in watchkit_paths: log.warning(\"Removing WatchKit bundle {}\".format(path)) shutil.rmtree(path)", "\"\"\" Represents an app archive. This is an app at", "> 0: if should_remove: for path in watchkit_paths: log.warning(\"Removing WatchKit", "the an unused # filename. Also, `zip` won't overwrite existing", "the dir itself, in the case of an AppArchive archive)", "\"\"\" log.debug('extension match') for extension in cls.extensions: log.debug('extension match: %s',", "this back up, or simply copy it out, depending on", "class UncompressedArchive(object): \"\"\" This just keeps track of some state", "somewhere else, return initialized UncompressedArchive \"\"\" shutil.copytree(self.path, target_path) return self.__class__(target_path,", "the zipped archive classes. In this case, the bundle dir", "the right extension \"\"\" log.debug('extension match') for extension in cls.extensions:", "sign WatchKit. If you don't care about watchkit functionality, it", "a zipped app bundle, or an IPA. We have a", "log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def get_info(cls, relative_bundle_dir, zipfile_obj): plist_path", "# methods we want to ensure are implemented. @abc.abstractmethod def", "abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod def", "from Info.plist without unarchiving \"\"\" pass @abc.abstractmethod def precheck(cls, path):", "@classmethod def get_info(cls, relative_bundle_dir, zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes =", "relative_bundle_dir = None apps = set() file_list = zipfile_obj.namelist() for", "use relative paths, because zip is stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\")", "zipped app bundle, or an IPA. We have a common", "temp_zip_dir = None try: # need to chdir and use", "parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path)", "etc.) \"\"\" self.path = path self.relative_bundle_dir = relative_bundle_dir self.archive_class =", "dir itself, in the case of an AppArchive archive) relative", "Just like an app, except it's zipped up, and when", "the output_path later. # # We also do a little", "remove it, so that's the default. Remove when https://github.com/saucelabs/isign/issues/20 is", "in the Bundle class \"\"\" if not isfile(path): return False", "= archive_factory(input_path) if archive is None: raise NotMatched('No matching archive", "dirname, exists, isdir, isfile, join, normpath import tempfile import re", "containing dir might be gone already b/c AppArchive simply moves", "the zip file. This is the best way to ensure", "located somewhere inside the containing directory, but might be a", "bundle, or an IPA. We have a common interface to", "= zipfile_obj.namelist() for file_name in file_list: matched = re.match(cls.app_dir_pattern, file_name)", "AppArchive]: if cls.precheck(path): archive = cls(path) log.debug(\"File %s matched as", "is_native @classmethod def archive(cls, path, output_path): if exists(output_path): shutil.rmtree(output_path) shutil.move(path,", "path did not match any archive type \"\"\" archive =", "None: plist_path = cls._get_plist_path(relative_bundle_dir) if plist_path not in zipfile_obj.namelist(): return", "return False plist = cls.get_info(relative_bundle_dir, zipfile_obj) is_native = is_info_plist_native(plist) log.debug(\"is_native:", "normpath(join(path, relative_bundle_dir)) self.bundle = App(bundle_path) def archive(self, output_path): \"\"\" Re-zip", "shutil import zipfile REMOVE_WATCHKIT = True helper_paths = {} log", "temp directory \"\"\" pass @abc.abstractmethod def archive(cls, path, output_path): \"\"\"", "the Bundle class \"\"\" if not isfile(path): return False if", "zipfile_obj) def unarchive_to_temp(self): containing_dir = make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path, \"-d\",", "if info_props: # Override info.plist props of the parent bundle", "from exceptions import MissingHelpers, NotSignable, NotMatched from distutils import spawn", "if it # does not have an extension. But we", "abc.abstractmethod throughout because there are certain class # methods we", "\".ipa\" or who knows. # So we move it to", "except it's zipped up, and when repackaged, should be re-zipped.", "path, output_path): \"\"\" Archive a directory to an output path", "log.debug('Signing with key: {}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate)) log.debug('Signing with", "\"\"\" return path @classmethod def _get_plist_path(cls, path): return join(cls.find_bundle_dir(path), \"Info.plist\")", "finally: if temp_zip_dir is not None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class", "extension in cls.extensions: log.debug('extension match: %s', extension) if path.endswith(extension): return", "than one app found in archive') else: log.warning('no apps found", "IOError(\"{0} not found\".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing with key:", "def clone(self, target_path): \"\"\" Copy the uncompressed archive somewhere else,", "\"\"\" Check if this is, in fact, an archive of", "= None apps = set() file_list = zipfile_obj.namelist() for file_name", "is not None: ua.remove() return bundle_info def resign(input_path, certificate, key,", "class {}: {}\".format(cls.__name__, helper_name)) is_present = False break return is_present", "get_helper(helper_name): \"\"\" find paths to executables. Cached in helper_paths \"\"\"", "shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived %s to %s\" % (cls.__name__, output_path))", "apps to a temp file, then resign them, and create", "@classmethod def archive(cls, path, output_path): if exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path)", "%s\" % (cls.__name__, output_path)) finally: if temp_zip_dir is not None", "We also do a little dance with making another temp", "def process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately, we currently can't sign WatchKit.", "the desired target when done if exists(self.path) and isdir(self.path): log.debug('removing", "Override info.plist props of the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile,", "== 1: log.debug(\"found one app\") relative_bundle_dir = apps.pop() elif len(apps)", "Archive a directory to an output path \"\"\" pass @abc.abstractmethod", "files, so this is safer. temp_zip_dir = None try: #", "returns False if any of our helper apps wasn't found", "and zipfile.is_zipfile(path)): log.debug(\"this is an archive, and a zipfile\") zipfile_obj", "= ua.bundle.info finally: if ua is not None: ua.remove() return", "if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this is an archive, and a", "bundle, e.g. Payload/Foo.app archive class is the kind of archive", "return biplist.readPlistFromString(plist_bytes) def __init__(self, path): self.path = path zipfile_obj =", "matched as %s\", path, cls.__name__) break return archive def view(input_path):", "might be gone already b/c AppArchive simply moves # it", "re-signed. The bundle is located somewhere inside the containing directory,", "best way to ensure the an unused # filename. Also,", "log.info(msg) raise finally: if ua is not None: ua.remove() return", "def archive(cls, containing_dir, output_path): \"\"\" archive this up into a", "Returns None if path did not match any archive type", "self.get_info(self.path) def unarchive_to_temp(self): containing_dir = make_temp_dir() log.debug(\"unarchiving to temp... %s", "\".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived %s to %s\" % (cls.__name__,", "... # some_directory # watchkit_extension <-- this is the watchkit", "watchkit_extension <-- this is the watchkit bundle # Info.plist #", "sub-bundles of this bundle that have watchkit \"\"\" # typical", "path have the right extension \"\"\" log.debug('extension match') for extension", "from bundle import App, Bundle, is_info_plist_native from exceptions import MissingHelpers,", "find_executable returns None is not found # in other words,", "NotMatched from distutils import spawn import logging import os from", "from subprocess import call from signer import Signer import shutil", "to a temp directory \"\"\" pass @abc.abstractmethod def archive(cls, path,", "def unarchive_to_temp(self): \"\"\" Unarchive and copy to a temp directory", "subprocess import call from signer import Signer import shutil import", "1: log.warning('more than one app found in archive') else: log.warning('no", "apps.add(matched.group(1)) if len(apps) == 1: log.debug(\"found one app\") relative_bundle_dir =", "(cls.__name__, output_path)) finally: if temp_zip_dir is not None and isdir(temp_zip_dir):", "import abspath, dirname, exists, isdir, isfile, join, normpath import tempfile", "zipfile.is_zipfile(path)): log.debug(\"this is an archive, and a zipfile\") zipfile_obj =", "precheck in the Bundle class \"\"\" if not isfile(path): return", "re from subprocess import call from signer import Signer import", "r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\" This just keeps track of some", "def precheck(cls, path): \"\"\" Checks if an archive looks like", "provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua = None", "metadata from Info.plist without unarchiving \"\"\" pass @abc.abstractmethod def precheck(cls,", "is not None: plist_path = cls._get_plist_path(relative_bundle_dir) if plist_path not in", "up once re-signed. The bundle is located somewhere inside the", "this bundle that have watchkit \"\"\" # typical structure: #", "it to the desired target when done if exists(self.path) and", "__init__(self, path): self.path = path zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir =", "case, the bundle dir *is* the directory \"\"\" return path", "output_path, info_props=None, alternate_entitlements_path=None): \"\"\" Unified interface to extract any kind", "file, resign it with these credentials, and create a similar", "_, _ in os.walk(root_bundle_path): if path == root_bundle_path: continue try:", "about watchkit functionality, it is generally harmless to remove it,", "process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately, we currently can't sign WatchKit. If", "there are certain class # methods we want to ensure", "temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file,", "is the kind of archive this was (Ipa, etc.) \"\"\"", "\"\"\" def __init__(self, path, relative_bundle_dir, archive_class): \"\"\" Path is the", "exists(self.path) and isdir(self.path): log.debug('removing ua: %s', self.path) shutil.rmtree(self.path) def archive_factory(path):", "= cls._get_plist_path(relative_bundle_dir) if plist_path not in zipfile_obj.namelist(): return False plist", "with apple_cert: {}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key)) log.debug('Signing with certificate:", "is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def get_info(cls, relative_bundle_dir, zipfile_obj):", "looks like this kind of app. Have to examine within", "e.g. Payload/Foo.app archive class is the kind of archive this", "throughout because there are certain class # methods we want", "should_remove=False): \"\"\" Unfortunately, we currently can't sign WatchKit. If you", "Archive(object): __metaclass__ = abc.ABCMeta # we use abc.abstractmethod throughout because", "an archive looks like this kind of app. Have to", "to %s\" % (cls.__name__, output_path)) def __init__(self, path): self.path =", "archive type \"\"\" archive = None for cls in [IpaArchive,", "class # methods we want to ensure are implemented. @abc.abstractmethod", "some_directory # watchkit_extension <-- this is the watchkit bundle #", "initialized UncompressedArchive \"\"\" shutil.copytree(self.path, target_path) return self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def", "temp directory somewhere \"\"\" # the temp file is necessary", "# need to chdir and use relative paths, because zip", "\"\"\" # the temp file is necessary because zip always", "also do a little dance with making another temp directory", "= Bundle(path) except NotMatched: # this directory is not a", "extension \"\"\" log.debug('extension match') for extension in cls.extensions: log.debug('extension match:", "these credentials, and create a similar archive for that resigned", "get_info(cls, relative_bundle_dir, zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path) return", "to respect the desired # output_path's extension, which could be", "shutil.move(path, output_path) log.info(\"archived %s to %s\" % (cls.__name__, output_path)) def", "archive type found') ua = archive.unarchive_to_temp() bundle_info = ua.bundle.info finally:", "-- a naked App Bundle, with no extra directory structure,", "\"\"\" Checks if an archive looks like this kind of", "the containing dir might be gone already b/c AppArchive simply", "[] for path, _, _ in os.walk(root_bundle_path): if path ==", "app\") relative_bundle_dir = apps.pop() elif len(apps) > 1: log.warning('more than", "part that runs on the Watch # Info.plist <-- WKWatchKitApp=True", "cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def __init__(self, path): self.path", "unarchive_to_temp(self): \"\"\" Unarchive and copy to a temp directory \"\"\"", "archive_class): \"\"\" Path is the \"Containing dir\", the dir at", "watchkit \"\"\" # typical structure: # # app_bundle # ...", "log.debug(\"found one app\") relative_bundle_dir = apps.pop() elif len(apps) > 1:", "return is_native @classmethod def archive(cls, path, output_path): if exists(output_path): shutil.rmtree(output_path)", "bundles\") class Archive(object): __metaclass__ = abc.ABCMeta # we use abc.abstractmethod", "have the right extension \"\"\" log.debug('extension match') for extension in", "that's the default. Remove when https://github.com/saucelabs/isign/issues/20 is fixed \"\"\" watchkit_paths", "no extra directory structure, compression, etc \"\"\" @classmethod def find_bundle_dir(cls,", "MissingHelpers(\"helpers not present\") is_native = False log.debug('precheck') log.debug('path: %s', path)", "= {} log = logging.getLogger(__name__) def get_helper(helper_name): \"\"\" find paths", "{1}\\n\".format(input_path, e) log.info(msg) raise finally: if ua is not None:", "note, find_executable returns None is not found # in other", "finally: if ua is not None: ua.remove() return bundle_info def", "\"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$' extensions = ['.zip'] helpers = ['zip',", "archive, and a zipfile\") zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj)", "care about watchkit functionality, it is generally harmless to remove", "self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self): containing_dir = make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path,", "of the unzipped archive (or the dir itself, in the", "= normpath(join(path, relative_bundle_dir)) self.bundle = App(bundle_path) def archive(self, output_path): \"\"\"", "watchkit bundle # Info.plist # watchkit_bundle <-- this is the", "what kind of archive we are dealing with, return an", "path): \"\"\" Checks if an archive looks like this kind", "repackaged, should be re-zipped. \"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$' extensions =", "\"\"\" Archive a directory to an output path \"\"\" pass", "is fixed \"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path) if len(watchkit_paths) > 0:", "\"\"\" does this path have the right extension \"\"\" log.debug('extension", "to examine within the zipfile, b/c we don't want to", "containing_dir]) app_dir = abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir,", "biplist from bundle import App, Bundle, is_info_plist_native from exceptions import", "already unzipped and you want to sign it. \"\"\" def", "helper apps wasn't found in class init \"\"\" is_present =", "we keep retrying until found helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got executable", "match') for extension in cls.extensions: log.debug('extension match: %s', extension) if", "harmless to remove it, so that's the default. Remove when", "# note, find_executable returns None is not found # in", "a ContainingDir/Payload/something.app This class is also useful if you have", "archive(cls, path, output_path): if exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived %s", "we currently can't sign WatchKit. If you don't care about", "and isdir(self.path): log.debug('removing ua: %s', self.path) shutil.rmtree(self.path) def archive_factory(path): \"\"\"", "this was (Ipa, etc.) \"\"\" self.path = path self.relative_bundle_dir =", "if ua is not None: ua.remove() return bundle_info def resign(input_path,", "app \"\"\" if not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) log.debug('Signing", "depending on what the original archive class did \"\"\" self.archive_class.archive(self.path,", "shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.', self.__class__) class AppZipArchive(Archive):", "zipfile_obj): relative_bundle_dir = None apps = set() file_list = zipfile_obj.namelist()", "cls.__name__) break return archive def view(input_path): if not exists(input_path): raise", "extract any kind of archive from a temporary file, resign", "later. # # We also do a little dance with", "relative_bundle_dir = apps.pop() elif len(apps) > 1: log.warning('more than one", "in helper_paths \"\"\" if helper_name not in helper_paths or helper_paths[helper_name]", "def __init__(self, path): self.path = path self.relative_bundle_dir = '.' self.bundle_info", "little dance with making another temp directory just # to", "return is_present @classmethod def is_archive_extension_match(cls, path): \"\"\" does this path", "\"\"\" pass class AppArchive(Archive): \"\"\" The simplest form of archive", "slightly different paths \"\"\" extensions = ['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$'", "archive is None: raise NotMatched('No matching archive type found') ua", "some state with an unzipped app archive and how to", "path in watchkit_paths: log.warning(\"Removing WatchKit bundle {}\".format(path)) shutil.rmtree(path) else: raise", "to ensure the an unused # filename. Also, `zip` won't", "helpers = ['zip', 'unzip'] @classmethod def is_helpers_present(cls): \"\"\" returns False", "True for helper_name in cls.helpers: if get_helper(helper_name) is None: log.error(\"missing", "extension) if path.endswith(extension): return True return False @classmethod def find_bundle_dir(cls,", "plist_bytes = zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def __init__(self, path): self.path =", "Info.plist <-- WKWatchKitApp=True # watchkit_paths = [] for path, _,", "create an archive of the same type \"\"\" import abc", "don't care about watchkit functionality, it is generally harmless to", "is_native = False log.debug('precheck') log.debug('path: %s', path) if (cls.is_archive_extension_match(path) and", "try: archive = archive_factory(input_path) if archive is None: raise NotMatched('No", "apps. Much like an AppZip, but slightly different paths \"\"\"", "__metaclass__ = abc.ABCMeta # we use abc.abstractmethod throughout because there", "\"\"\" pass @abc.abstractmethod def get_info(cls, path): \"\"\" Obtain app metadata", "app_bundle # ... # some_directory # watchkit_extension <-- this is", "= App(bundle_path) def archive(self, output_path): \"\"\" Re-zip this back up,", "desired # output_path's extension, which could be \".ipa\" or who", "already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.', self.__class__) class", "chdir and use relative paths, because zip is stupid temp_zip_dir", "= True helper_paths = {} log = logging.getLogger(__name__) def get_helper(helper_name):", "False break return is_present @classmethod def is_archive_extension_match(cls, path): \"\"\" does", "helper_paths \"\"\" if helper_name not in helper_paths or helper_paths[helper_name] is", "the temp file is necessary because zip always adds \".zip\"", "@classmethod def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir = None apps = set()", "shutil.rmtree(path) else: raise NotSignable(\"Cannot yet sign WatchKit bundles\") class Archive(object):", "with no extra directory structure, compression, etc \"\"\" @classmethod def", "ua = None bundle_info = None try: archive = archive_factory(input_path)", "cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived %s to %s\" % (cls.__name__, output_path))", "caller will use us on a temp directory somewhere \"\"\"", "the *containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths def process_watchkit(root_bundle_path, should_remove=False): \"\"\"", "archive(cls, containing_dir, output_path): \"\"\" archive this up into a zipfile.", "= None for cls in [IpaArchive, AppZipArchive, AppArchive]: if cls.precheck(path):", "not present\") is_native = False log.debug('precheck') log.debug('path: %s', path) if", "log.warning(\"Removing WatchKit bundle {}\".format(path)) shutil.rmtree(path) else: raise NotSignable(\"Cannot yet sign", "did not match any archive type \"\"\" archive = None", "file_list = zipfile_obj.namelist() for file_name in file_list: matched = re.match(cls.app_dir_pattern,", "alternate_entitlements_path=None): \"\"\" Unified interface to extract any kind of archive", "%s', extension) if path.endswith(extension): return True return False @classmethod def", "distutils import spawn import logging import os from os.path import", "cls(path) log.debug(\"File %s matched as %s\", path, cls.__name__) break return", "resign it with these credentials, and create a similar archive", "log.debug('Signing with certificate: {}'.format(certificate)) log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile)) signer =", "unarchiving \"\"\" pass @abc.abstractmethod def precheck(cls, path): \"\"\" Check if", "zipped archive classes. In this case, the bundle dir *is*", "temp_zip_file = join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file,", "for path in watchkit_paths: log.warning(\"Removing WatchKit bundle {}\".format(path)) shutil.rmtree(path) else:", "AppZipArchive, AppArchive]: if cls.precheck(path): archive = cls(path) log.debug(\"File %s matched", "app bundle, or an IPA. We have a common interface", "is_archive_extension_match(cls, path): \"\"\" does this path have the right extension", "(Ipa, etc.) \"\"\" self.path = path self.relative_bundle_dir = relative_bundle_dir self.archive_class", "an unzipped app archive and how to re-zip it back", "self.path, \"-d\", containing_dir]) app_dir = abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return", "get_helper(helper_name) is None: log.error(\"missing helper for class {}: {}\".format(cls.__name__, helper_name))", "ua = archive.unarchive_to_temp() if info_props: # Override info.plist props of", "return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod", "None try: archive = archive_factory(input_path) if archive is None: raise", "path, relative_bundle_dir, archive_class): \"\"\" Path is the \"Containing dir\", the", "zip file. This is the best way to ensure the", "want to ensure are implemented. @abc.abstractmethod def unarchive_to_temp(self): \"\"\" Unarchive", "stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\",", "up into a zipfile. Note this is a classmethod, because", "archive type found') ua = archive.unarchive_to_temp() if info_props: # Override", "uncompressed archive somewhere else, return initialized UncompressedArchive \"\"\" shutil.copytree(self.path, target_path)", "on what the original archive class did \"\"\" self.archive_class.archive(self.path, output_path)", "dir might be gone already b/c AppArchive simply moves #", "= self.get_info(self.path) def unarchive_to_temp(self): containing_dir = make_temp_dir() log.debug(\"unarchiving to temp...", "plist_path = cls._get_plist_path(relative_bundle_dir) if plist_path not in zipfile_obj.namelist(): return False", "a common interface to extract these apps to a temp", "it, so that's the default. Remove when https://github.com/saucelabs/isign/issues/20 is fixed", "matched = re.match(cls.app_dir_pattern, file_name) if matched: apps.add(matched.group(1)) if len(apps) ==", "apps.pop() elif len(apps) > 1: log.warning('more than one app found", "a few directories down, like in a ContainingDir/Payload/something.app This class", "directories down, like in a ContainingDir/Payload/something.app This class is also", "= r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\" This just keeps track of", "not match any archive type \"\"\" archive = None for", "helper_paths[helper_name] def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles", "output_path)) finally: if temp_zip_dir is not None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir)", "%s\", self.path, containing_dir) shutil.rmtree(containing_dir) # quirk of copytree, top dir", "WKWatchKitApp=True # watchkit_paths = [] for path, _, _ in", "path): return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path))", "os.walk(root_bundle_path): if path == root_bundle_path: continue try: bundle = Bundle(path)", "def remove(self): # the containing dir might be gone already", "raise NotMatched('No matching archive type found') ua = archive.unarchive_to_temp() bundle_info", "precheck(cls, path): if not isdir(path): return False if not os.path.exists(cls._get_plist_path(path)):", "\"\"\" is_present = True for helper_name in cls.helpers: if get_helper(helper_name)", "from signer import Signer import shutil import zipfile REMOVE_WATCHKIT =", "Copy the uncompressed archive somewhere else, return initialized UncompressedArchive \"\"\"", "None: raise NotSignable('No matching archive type found') ua = archive.unarchive_to_temp()", "archive looks like this kind of app. Have to examine", "archive of this type \"\"\" pass @abc.abstractmethod def find_bundle_dir(cls, path):", "zipfile. Note this is a classmethod, because the caller will", "for cls in [IpaArchive, AppZipArchive, AppArchive]: if cls.precheck(path): archive =", "clone(self, target_path): \"\"\" Copy the uncompressed archive somewhere else, return", "and create a similar archive for that resigned app \"\"\"", "back up once re-signed. The bundle is located somewhere inside", "unzipped and you want to sign it. \"\"\" def __init__(self,", "etc \"\"\" @classmethod def find_bundle_dir(cls, path): \"\"\" Included for similarity", "Cached in helper_paths \"\"\" if helper_name not in helper_paths or", "# Info.plist <-- WKWatchKitApp=True # watchkit_paths = [] for path,", "any kind of archive from a temporary file, resign it", "whether it's a naked app bundle in a directory, or", "have a common interface to extract these apps to a", "helper_name in cls.helpers: if get_helper(helper_name) is None: log.error(\"missing helper for", "not None: plist_path = cls._get_plist_path(relative_bundle_dir) if plist_path not in zipfile_obj.namelist():", "MissingHelpers, NotSignable, NotMatched from distutils import spawn import logging import", "\"Info.plist\") @classmethod def get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls,", "collect sub-bundles of this bundle that have watchkit \"\"\" #", "path): self.path = path zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj)", "done if exists(self.path) and isdir(self.path): log.debug('removing ua: %s', self.path) shutil.rmtree(self.path)", "Remove when https://github.com/saucelabs/isign/issues/20 is fixed \"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path) if", "apple_cert: {}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate))", "naked App Bundle, with no extra directory structure, compression, etc", "archive = archive_factory(input_path) if archive is None: raise NotSignable('No matching", "is the watchkit bundle # Info.plist # watchkit_bundle <-- this", "safer. temp_zip_dir = None try: # need to chdir and", "the dir containing the bundle, e.g. Payload/Foo.app archive class is", "found\".format(input_path)) ua = None bundle_info = None try: archive =", "is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def archive(cls,", "logging import os from os.path import abspath, dirname, exists, isdir,", "path) if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this is an archive, and", "log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key)) log.debug('Signing with", "\"\"\" pass @abc.abstractmethod def find_bundle_dir(cls, path): \"\"\" Locate the directory", "If you don't care about watchkit functionality, it is generally", "of archive from a temporary file, resign it with these", "cls.helpers: if get_helper(helper_name) is None: log.error(\"missing helper for class {}:", "from distutils import spawn import logging import os from os.path", "def is_helpers_present(cls): \"\"\" returns False if any of our helper", "'.', self.__class__) class AppZipArchive(Archive): \"\"\" Just like an app, except", "%s\" % (cls.__name__, output_path)) def __init__(self, path): self.path = path", "directory just # to construct the zip file. This is", "right extension \"\"\" log.debug('extension match') for extension in cls.extensions: log.debug('extension", "= zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is not None:", "archive object. Returns None if path did not match any", "<-- this is the watchkit bundle # Info.plist # watchkit_bundle", "key: {}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate)) log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile))", "watchkit_paths = [] for path, _, _ in os.walk(root_bundle_path): if", "and use relative paths, because zip is stupid temp_zip_dir =", "if cls.precheck(path): archive = cls(path) log.debug(\"File %s matched as %s\",", "UncompressedArchive \"\"\" shutil.copytree(self.path, target_path) return self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def remove(self):", "join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived", "a naked app bundle in a directory, or a zipped", "apps = set() file_list = zipfile_obj.namelist() for file_name in file_list:", "cls._get_plist_path(relative_bundle_dir) if plist_path not in zipfile_obj.namelist(): return False plist =", "\"\"\" This just keeps track of some state with an", "log.info(\"archived %s to %s\" % (cls.__name__, output_path)) finally: if temp_zip_dir", "'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived %s", "path self.relative_bundle_dir = '.' self.bundle_info = self.get_info(self.path) def unarchive_to_temp(self): containing_dir", "one app\") relative_bundle_dir = apps.pop() elif len(apps) > 1: log.warning('more", "itself, in the case of an AppArchive archive) relative bundle", "# does not have an extension. But we want to", "e) log.info(msg) raise finally: if ua is not None: ua.remove()", "exceptions import MissingHelpers, NotSignable, NotMatched from distutils import spawn import", "bundle) \"\"\" pass class AppArchive(Archive): \"\"\" The simplest form of", "Re-zip this back up, or simply copy it out, depending", "self.__class__) class AppZipArchive(Archive): \"\"\" Just like an app, except it's", "import os from os.path import abspath, dirname, exists, isdir, isfile,", "isdir, isfile, join, normpath import tempfile import re from subprocess", "= path self.relative_bundle_dir = '.' self.bundle_info = self.get_info(self.path) def unarchive_to_temp(self):", "This is an app at rest, whether it's a naked", "self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self): containing_dir", "unarchive_to_temp(self): containing_dir = make_temp_dir() log.debug(\"unarchiving to temp... %s -> %s\",", "the original archive class did \"\"\" self.archive_class.archive(self.path, output_path) def clone(self,", "def get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles of this bundle that have", "relative_bundle_dir is not None: plist_path = cls._get_plist_path(relative_bundle_dir) if plist_path not", "path @classmethod def _get_plist_path(cls, path): return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def", "\"\"\" Included for similarity with the zipped archive classes. In", "NotMatched: # this directory is not a bundle continue if", "kind of archive we are dealing with, return an archive", "plist = cls.get_info(relative_bundle_dir, zipfile_obj) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return", "%s', path) if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this is an archive,", "rest, whether it's a naked app bundle in a directory,", "None: # note, find_executable returns None is not found #", "But we want to respect the desired # output_path's extension,", "%s to %s\" % (cls.__name__, output_path)) def __init__(self, path): self.path", "import MissingHelpers, NotSignable, NotMatched from distutils import spawn import logging", "output_path): \"\"\" archive this up into a zipfile. Note this", "in [IpaArchive, AppZipArchive, AppArchive]: if cls.precheck(path): archive = cls(path) log.debug(\"File", "call from signer import Signer import shutil import zipfile REMOVE_WATCHKIT", "and create an archive of the same type \"\"\" import", "this directory is not a bundle continue if bundle.info.get('WKWatchKitApp') is", "copytree, top dir can't exist already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT)", "it to the output_path later. # # We also do", "then resign them, and create an archive of the same", "isfile, join, normpath import tempfile import re from subprocess import", "def precheck(cls, path): if not isdir(path): return False if not", "bundle.info.get('WKWatchKitApp') is True: # get the *containing* bundle watchkit_paths.append(dirname(path)) return", "that resigned app \"\"\" if not exists(input_path): raise IOError(\"{0} not", "generally harmless to remove it, so that's the default. Remove", "set() file_list = zipfile_obj.namelist() for file_name in file_list: matched =", "get_info(cls, path): \"\"\" Obtain app metadata from Info.plist without unarchiving", "filename. Also, `zip` won't overwrite existing files, so this is", "type \"\"\" import abc import biplist from bundle import App,", "e: msg = \"Not signable: <{0}>: {1}\\n\".format(input_path, e) log.info(msg) raise", "path): \"\"\" Obtain app metadata from Info.plist without unarchiving \"\"\"", "common interface to extract these apps to a temp file,", "class Archive(object): __metaclass__ = abc.ABCMeta # we use abc.abstractmethod throughout", "app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\" This just keeps track", "False @classmethod def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir = None apps =", "if path.endswith(extension): return True return False @classmethod def find_bundle_dir(cls, zipfile_obj):", "you don't care about watchkit functionality, it is generally harmless", "relative_bundle_dir, archive_class): \"\"\" Path is the \"Containing dir\", the dir", "We have a common interface to extract these apps to", "not isfile(path): return False if not cls.is_helpers_present(): raise MissingHelpers(\"helpers not", "-> %s\", self.path, containing_dir) shutil.rmtree(containing_dir) # quirk of copytree, top", "{}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua = None bundle_info", "helper_paths or helper_paths[helper_name] is None: # note, find_executable returns None", "self.__class__) @classmethod def archive(cls, containing_dir, output_path): \"\"\" archive this up", "ensure are implemented. @abc.abstractmethod def unarchive_to_temp(self): \"\"\" Unarchive and copy", "just # to construct the zip file. This is the", "if you have an app that's already unzipped and you", "else, return initialized UncompressedArchive \"\"\" shutil.copytree(self.path, target_path) return self.__class__(target_path, self.relative_bundle_dir,", "pass @abc.abstractmethod def get_info(cls, path): \"\"\" Obtain app metadata from", "if this is, in fact, an archive of this type", "zipfile_obj.namelist() for file_name in file_list: matched = re.match(cls.app_dir_pattern, file_name) if", "archive) relative bundle dir is the dir containing the bundle,", "of our helper apps wasn't found in class init \"\"\"", "archive') else: log.warning('no apps found in archive') return relative_bundle_dir @classmethod", "path, output_path): if exists(output_path): shutil.rmtree(output_path) shutil.move(path, output_path) log.info(\"archived %s to", "be \".ipa\" or who knows. # So we move it", "App(bundle_path) def archive(self, output_path): \"\"\" Re-zip this back up, or", "similar archive for that resigned app \"\"\" if not exists(input_path):", "None is not found # in other words, we keep", "or who knows. # So we move it to the", "join, normpath import tempfile import re from subprocess import call", "target_path) return self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def remove(self): # the containing", "# to construct the zip file. This is the best", "similar precheck in the Bundle class \"\"\" if not isfile(path):", "output_path's extension, which could be \".ipa\" or who knows. #", "to executables. Cached in helper_paths \"\"\" if helper_name not in", "= True for helper_name in cls.helpers: if get_helper(helper_name) is None:", "\"Info.plist\") @classmethod def precheck(cls, path): \"\"\" Checks if an archive", "import zipfile REMOVE_WATCHKIT = True helper_paths = {} log =", "%s to %s\" % (cls.__name__, output_path)) finally: if temp_zip_dir is", "= ['zip', 'unzip'] @classmethod def is_helpers_present(cls): \"\"\" returns False if", "class \"\"\" if not isfile(path): return False if not cls.is_helpers_present():", "bundle_info = ua.bundle.info finally: if ua is not None: ua.remove()", "raise IOError(\"{0} not found\".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing with", "a classmethod, because the caller will use us on a", "already b/c AppArchive simply moves # it to the desired", "when done if exists(self.path) and isdir(self.path): log.debug('removing ua: %s', self.path)", "watchkit_paths.append(dirname(path)) return watchkit_paths def process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately, we currently", "main app (aka bundle) \"\"\" pass class AppArchive(Archive): \"\"\" The", "not found\".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key))", "quirk of copytree, top dir can't exist already shutil.copytree(self.path, containing_dir)", "is the dir containing the bundle, e.g. Payload/Foo.app archive class", "type found') ua = archive.unarchive_to_temp() bundle_info = ua.bundle.info finally: if", "NotSignable('No matching archive type found') ua = archive.unarchive_to_temp() if info_props:", "always adds \".zip\" if it # does not have an", "so that's the default. Remove when https://github.com/saucelabs/isign/issues/20 is fixed \"\"\"", "= apps.pop() elif len(apps) > 1: log.warning('more than one app", "False if not os.path.exists(cls._get_plist_path(path)): return False plist = cls.get_info(path) is_native", "not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) ua = None bundle_info", "tempfile import re from subprocess import call from signer import", "plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def __init__(self,", "= abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod", "use abc.abstractmethod throughout because there are certain class # methods", "cls in [IpaArchive, AppZipArchive, AppArchive]: if cls.precheck(path): archive = cls(path)", "None: ua.remove() return bundle_info def resign(input_path, certificate, key, apple_cert, provisioning_profile,", "ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path) except NotSignable as", "plist_path not in zipfile_obj.namelist(): return False plist = cls.get_info(relative_bundle_dir, zipfile_obj)", "> 1: log.warning('more than one app found in archive') else:", "archive. This is an app at rest, whether it's a", "False if not cls.is_helpers_present(): raise MissingHelpers(\"helpers not present\") is_native =", "is also useful if you have an app that's already", "is the part that runs on the Watch # Info.plist", "watchkit functionality, it is generally harmless to remove it, so", "because there are certain class # methods we want to", "if relative_bundle_dir is not None: plist_path = cls._get_plist_path(relative_bundle_dir) if plist_path", "found in class init \"\"\" is_present = True for helper_name", "The bundle is located somewhere inside the containing directory, but", "exists, isdir, isfile, join, normpath import tempfile import re from", "import call from signer import Signer import shutil import zipfile", "won't overwrite existing files, so this is safer. temp_zip_dir =", "and when repackaged, should be re-zipped. \"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$'", "path): \"\"\" does this path have the right extension \"\"\"", "file is necessary because zip always adds \".zip\" if it", "WatchKit bundles\") class Archive(object): __metaclass__ = abc.ABCMeta # we use", "relative_bundle_dir, zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes)", "sign it. \"\"\" def __init__(self, path, relative_bundle_dir, archive_class): \"\"\" Path", "os from os.path import abspath, dirname, exists, isdir, isfile, join,", "archive = cls(path) log.debug(\"File %s matched as %s\", path, cls.__name__)", "are dealing with, return an archive object. Returns None if", "<{0}>: {1}\\n\".format(input_path, e) log.info(msg) raise finally: if ua is not", "bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path) except", "%s', self.path) shutil.rmtree(self.path) def archive_factory(path): \"\"\" Guess what kind of", "as %s\", path, cls.__name__) break return archive def view(input_path): if", "distributing apps. Much like an AppZip, but slightly different paths", "with making another temp directory just # to construct the", "file_list: matched = re.match(cls.app_dir_pattern, file_name) if matched: apps.add(matched.group(1)) if len(apps)", "apps found in archive') return relative_bundle_dir @classmethod def _get_plist_path(cls, relative_bundle_dir):", "overwrite existing files, so this is safer. temp_zip_dir = None", "track of some state with an unzipped app archive and", "unzipped archive (or the dir itself, in the case of", "extra directory structure, compression, etc \"\"\" @classmethod def find_bundle_dir(cls, path):", "make_temp_dir() log.debug(\"unarchiving to temp... %s -> %s\", self.path, containing_dir) shutil.rmtree(containing_dir)", "exists(input_path): raise IOError(\"{0} not found\".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing", "to construct the zip file. This is the best way", "not found\".format(input_path)) ua = None bundle_info = None try: archive", "apps wasn't found in class init \"\"\" is_present = True", "archive = archive_factory(input_path) if archive is None: raise NotMatched('No matching", "of an AppArchive archive) relative bundle dir is the dir", "can't sign WatchKit. If you don't care about watchkit functionality,", "top dir can't exist already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return", "resign them, and create an archive of the same type", "in cls.helpers: if get_helper(helper_name) is None: log.error(\"missing helper for class", "len(apps) == 1: log.debug(\"found one app\") relative_bundle_dir = apps.pop() elif", "bundle is located somewhere inside the containing directory, but might", "is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def archive(cls, path, output_path):", "self.path, containing_dir) shutil.rmtree(containing_dir) # quirk of copytree, top dir can't", "an output path \"\"\" pass @abc.abstractmethod def get_info(cls, path): \"\"\"", "interface to extract these apps to a temp file, then", "\"\"\" archive this up into a zipfile. Note this is", "temp_zip_dir is not None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\"", "AppZipArchive(Archive): \"\"\" Just like an app, except it's zipped up,", "self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self): containing_dir = make_temp_dir()", "or a zipped app bundle, or an IPA. We have", "path): self.path = path self.relative_bundle_dir = '.' self.bundle_info = self.get_info(self.path)", "level of the unzipped archive (or the dir itself, in", "= False log.debug('precheck') log.debug('path: %s', path) if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)):", "classes. In this case, the bundle dir *is* the directory", "standard for distributing apps. Much like an AppZip, but slightly", "app found in archive') else: log.warning('no apps found in archive')", "because zip always adds \".zip\" if it # does not", "precheck(cls, path): \"\"\" Check if this is, in fact, an", "False plist = cls.get_info(relative_bundle_dir, zipfile_obj) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native))", "return UncompressedArchive(containing_dir, '.', self.__class__) class AppZipArchive(Archive): \"\"\" Just like an", "self.bundle = App(bundle_path) def archive(self, output_path): \"\"\" Re-zip this back", "watchkit_bundle <-- this is the part that runs on the", "it out, depending on what the original archive class did", "Included for similarity with the zipped archive classes. In this", "try: bundle = Bundle(path) except NotMatched: # this directory is", "find paths to executables. Cached in helper_paths \"\"\" if helper_name", "1: log.debug(\"found one app\") relative_bundle_dir = apps.pop() elif len(apps) >", "log.debug(\"File %s matched as %s\", path, cls.__name__) break return archive", "return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod def archive(cls, containing_dir, output_path): \"\"\"", "bundle import App, Bundle, is_info_plist_native from exceptions import MissingHelpers, NotSignable,", "IpaArchive(AppZipArchive): \"\"\" IPA is Apple's standard for distributing apps. Much", "this is the watchkit bundle # Info.plist # watchkit_bundle <--", "the kind of archive this was (Ipa, etc.) \"\"\" self.path", "archive somewhere else, return initialized UncompressedArchive \"\"\" shutil.copytree(self.path, target_path) return", "zipfile_obj) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def", "is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def get_info(cls,", "call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived %s to", "if helper_name not in helper_paths or helper_paths[helper_name] is None: #", "= re.match(cls.app_dir_pattern, file_name) if matched: apps.add(matched.group(1)) if len(apps) == 1:", "this is safer. temp_zip_dir = None try: # need to", "r'^([^/]+\\.app/).*$' extensions = ['.zip'] helpers = ['zip', 'unzip'] @classmethod def", "pass @abc.abstractmethod def archive(cls, path, output_path): \"\"\" Archive a directory", "msg = \"Not signable: <{0}>: {1}\\n\".format(input_path, e) log.info(msg) raise finally:", "re-zip it back up once re-signed. The bundle is located", "directory, or a zipped app bundle, or an IPA. We", "helper_name)) is_present = False break return is_present @classmethod def is_archive_extension_match(cls,", "existing files, so this is safer. temp_zip_dir = None try:", "def is_archive_extension_match(cls, path): \"\"\" does this path have the right", "\"Not signable: <{0}>: {1}\\n\".format(input_path, e) log.info(msg) raise finally: if ua", "def resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): \"\"\"", "if plist_path not in zipfile_obj.namelist(): return False plist = cls.get_info(relative_bundle_dir,", "with, return an archive object. Returns None if path did", "@classmethod def archive(cls, containing_dir, output_path): \"\"\" archive this up into", "one app found in archive') else: log.warning('no apps found in", "do a little dance with making another temp directory just", "containing the bundle, e.g. Payload/Foo.app archive class is the kind", "Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua = None bundle_info = None try:", "shutil.rmtree(self.path) def archive_factory(path): \"\"\" Guess what kind of archive we", "archive(self, output_path): \"\"\" Re-zip this back up, or simply copy", "in the case of an AppArchive archive) relative bundle dir", "is Apple's standard for distributing apps. Much like an AppZip,", "archive and how to re-zip it back up once re-signed.", "return False if not os.path.exists(cls._get_plist_path(path)): return False plist = cls.get_info(path)", "remove(self): # the containing dir might be gone already b/c", "Locate the directory of the main app (aka bundle) \"\"\"", "back up, or simply copy it out, depending on what", "return archive def view(input_path): if not exists(input_path): raise IOError(\"{0} not", "= archive_factory(input_path) if archive is None: raise NotSignable('No matching archive", "Path is the \"Containing dir\", the dir at the root", "unused # filename. Also, `zip` won't overwrite existing files, so", "Bundle(path) except NotMatched: # this directory is not a bundle", "dir is the dir containing the bundle, e.g. Payload/Foo.app archive", "archive_class bundle_path = normpath(join(path, relative_bundle_dir)) self.bundle = App(bundle_path) def archive(self,", "\"\"\" Guess what kind of archive we are dealing with,", "# quirk of copytree, top dir can't exist already shutil.copytree(self.path,", "helper for class {}: {}\".format(cls.__name__, helper_name)) is_present = False break", "AppArchive simply moves # it to the desired target when", "spawn import logging import os from os.path import abspath, dirname,", "this kind of app. Have to examine within the zipfile,", "is None: # note, find_executable returns None is not found", "relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\") @classmethod def precheck(cls, path): \"\"\" Checks", "log.warning('more than one app found in archive') else: log.warning('no apps", "and copy to a temp directory \"\"\" pass @abc.abstractmethod def", "it with these credentials, and create a similar archive for", "any of our helper apps wasn't found in class init", "@abc.abstractmethod def get_info(cls, path): \"\"\" Obtain app metadata from Info.plist", "an IPA. We have a common interface to extract these", "create a similar archive for that resigned app \"\"\" if", "= spawn.find_executable(helper_name) log.debug(\"got executable {} for {}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name]", "make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path, \"-d\", containing_dir]) app_dir = abspath(join(containing_dir, self.relative_bundle_dir))", "copy to a temp directory \"\"\" pass @abc.abstractmethod def archive(cls,", "of some state with an unzipped app archive and how", "if len(apps) == 1: log.debug(\"found one app\") relative_bundle_dir = apps.pop()", "So we move it to the output_path later. # #", "return is_native @classmethod def get_info(cls, relative_bundle_dir, zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir)", "so this is safer. temp_zip_dir = None try: # need", "fact, an archive of this type \"\"\" pass @abc.abstractmethod def", "construct the zip file. This is the best way to", "helper_paths = {} log = logging.getLogger(__name__) def get_helper(helper_name): \"\"\" find", "Have to examine within the zipfile, b/c we don't want", "\"\"\" if helper_name not in helper_paths or helper_paths[helper_name] is None:", "Guess what kind of archive we are dealing with, return", "find_bundle_dir(cls, path): \"\"\" Included for similarity with the zipped archive", "containing_dir, output_path): \"\"\" archive this up into a zipfile. Note", "log.warning('no apps found in archive') return relative_bundle_dir @classmethod def _get_plist_path(cls,", "matched: apps.add(matched.group(1)) if len(apps) == 1: log.debug(\"found one app\") relative_bundle_dir", "dance with making another temp directory just # to construct", "we are dealing with, return an archive object. Returns None", "{}\".format(cls.__name__, helper_name)) is_present = False break return is_present @classmethod def", "from a temporary file, resign it with these credentials, and", "file. This is the best way to ensure the an", "NotSignable(\"Cannot yet sign WatchKit bundles\") class Archive(object): __metaclass__ = abc.ABCMeta", "app. Have to examine within the zipfile, b/c we don't", "= set() file_list = zipfile_obj.namelist() for file_name in file_list: matched", "a temp directory somewhere \"\"\" # the temp file is", "# filename. Also, `zip` won't overwrite existing files, so this", "False log.debug('precheck') log.debug('path: %s', path) if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this", "[IpaArchive, AppZipArchive, AppArchive]: if cls.precheck(path): archive = cls(path) log.debug(\"File %s", "simply copy it out, depending on what the original archive", "pass class AppArchive(Archive): \"\"\" The simplest form of archive --", "is_present @classmethod def is_archive_extension_match(cls, path): \"\"\" does this path have", "# ... # some_directory # watchkit_extension <-- this is the", "= None bundle_info = None try: archive = archive_factory(input_path) if", "is None: raise NotMatched('No matching archive type found') ua =", "def _get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\") @classmethod def precheck(cls, path):", "of archive we are dealing with, return an archive object.", "not have an extension. But we want to respect the", "{} for {}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name] def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\")", "directory somewhere \"\"\" # the temp file is necessary because", "output_path) def clone(self, target_path): \"\"\" Copy the uncompressed archive somewhere", "an archive object. Returns None if path did not match", "@classmethod def find_bundle_dir(cls, path): \"\"\" Included for similarity with the", "self.relative_bundle_dir, self.__class__) @classmethod def archive(cls, containing_dir, output_path): \"\"\" archive this", "AppArchive(Archive): \"\"\" The simplest form of archive -- a naked", "temp file, then resign them, and create an archive of", "\"\"\" The simplest form of archive -- a naked App", "not os.path.exists(cls._get_plist_path(path)): return False plist = cls.get_info(path) is_native = is_info_plist_native(plist)", "Unarchive and copy to a temp directory \"\"\" pass @abc.abstractmethod", "def find_bundle_dir(cls, path): \"\"\" Included for similarity with the zipped", "%s -> %s\", self.path, containing_dir) shutil.rmtree(containing_dir) # quirk of copytree,", "\"\"\" collect sub-bundles of this bundle that have watchkit \"\"\"", "__init__(self, path): self.path = path self.relative_bundle_dir = '.' self.bundle_info =", "should be re-zipped. \"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$' extensions = ['.zip']", "archive this up into a zipfile. Note this is a", "signer import Signer import shutil import zipfile REMOVE_WATCHKIT = True", "useful if you have an app that's already unzipped and", "# Override info.plist props of the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer,", "until found helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got executable {} for {}\".format(helper_paths[helper_name],", "return watchkit_paths def process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately, we currently can't", "find_bundle_dir(cls, path): \"\"\" Locate the directory of the main app", "import biplist from bundle import App, Bundle, is_info_plist_native from exceptions", "is True: # get the *containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths", "zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj)", "This class is also useful if you have an app", "this type \"\"\" pass @abc.abstractmethod def find_bundle_dir(cls, path): \"\"\" Locate", "is None: raise NotSignable('No matching archive type found') ua =", "ua: %s', self.path) shutil.rmtree(self.path) def archive_factory(path): \"\"\" Guess what kind", "the default. Remove when https://github.com/saucelabs/isign/issues/20 is fixed \"\"\" watchkit_paths =", "abspath, dirname, exists, isdir, isfile, join, normpath import tempfile import", "Much like an AppZip, but slightly different paths \"\"\" extensions", "cls.get_info(relative_bundle_dir, zipfile_obj) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod", "def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles of", "log.debug(\"this is an archive, and a zipfile\") zipfile_obj = zipfile.ZipFile(path)", "ua.archive(output_path) except NotSignable as e: msg = \"Not signable: <{0}>:", "bundle dir *is* the directory \"\"\" return path @classmethod def", "to extract any kind of archive from a temporary file,", "isdir(self.path): log.debug('removing ua: %s', self.path) shutil.rmtree(self.path) def archive_factory(path): \"\"\" Guess", "= cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def __init__(self, path):", "to an output path \"\"\" pass @abc.abstractmethod def get_info(cls, path):", "is not None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\" IPA", "move it to the output_path later. # # We also", "# get the *containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths def process_watchkit(root_bundle_path,", "temp dirs just yet. This recapitulates a very similar precheck", "directory is not a bundle continue if bundle.info.get('WKWatchKitApp') is True:", "file, then resign them, and create an archive of the", "# app_bundle # ... # some_directory # watchkit_extension <-- this", "to the desired target when done if exists(self.path) and isdir(self.path):", "the main app (aka bundle) \"\"\" pass class AppArchive(Archive): \"\"\"", "This is the best way to ensure the an unused", "is not found # in other words, we keep retrying", "path self.relative_bundle_dir = relative_bundle_dir self.archive_class = archive_class bundle_path = normpath(join(path,", "up, or simply copy it out, depending on what the", "ensure the an unused # filename. Also, `zip` won't overwrite", "ua is not None: ua.remove() return bundle_info def resign(input_path, certificate,", "copy it out, depending on what the original archive class", "match: %s', extension) if path.endswith(extension): return True return False @classmethod", "0: if should_remove: for path in watchkit_paths: log.warning(\"Removing WatchKit bundle", "def precheck(cls, path): \"\"\" Check if this is, in fact,", "to re-zip it back up once re-signed. The bundle is", "biplist.readPlistFromString(plist_bytes) def __init__(self, path): self.path = path zipfile_obj = zipfile.ZipFile(path)", "which could be \".ipa\" or who knows. # So we", "use us on a temp directory somewhere \"\"\" # the", "zipfile REMOVE_WATCHKIT = True helper_paths = {} log = logging.getLogger(__name__)", "in helper_paths or helper_paths[helper_name] is None: # note, find_executable returns", "a directory to an output path \"\"\" pass @abc.abstractmethod def", "not in zipfile_obj.namelist(): return False plist = cls.get_info(relative_bundle_dir, zipfile_obj) is_native", "a temporary file, resign it with these credentials, and create", "raise MissingHelpers(\"helpers not present\") is_native = False log.debug('precheck') log.debug('path: %s',", "return self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def remove(self): # the containing dir", "to ensure are implemented. @abc.abstractmethod def unarchive_to_temp(self): \"\"\" Unarchive and", "for {}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name] def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def", "get_info(cls, path): return biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls, path): if not", "shutil.rmtree(containing_dir) # quirk of copytree, top dir can't exist already", "make temp dirs just yet. This recapitulates a very similar", "Unfortunately, we currently can't sign WatchKit. If you don't care", "yet. This recapitulates a very similar precheck in the Bundle", "making another temp directory just # to construct the zip", "currently can't sign WatchKit. If you don't care about watchkit", "ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path) except NotSignable", "sign WatchKit bundles\") class Archive(object): __metaclass__ = abc.ABCMeta # we", "directory, but might be a few directories down, like in", "without unarchiving \"\"\" pass @abc.abstractmethod def precheck(cls, path): \"\"\" Check", "None: raise NotMatched('No matching archive type found') ua = archive.unarchive_to_temp()", "def get_info(cls, relative_bundle_dir, zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes = zipfile_obj.read(plist_path)", "shutil.move(temp_zip_file, output_path) log.info(\"archived %s to %s\" % (cls.__name__, output_path)) finally:", "\"\"\" shutil.copytree(self.path, target_path) return self.__class__(target_path, self.relative_bundle_dir, self.archive_class) def remove(self): #", "bundle watchkit_paths.append(dirname(path)) return watchkit_paths def process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately, we", "isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\" IPA is Apple's standard for", "return True return False @classmethod def find_bundle_dir(cls, zipfile_obj): relative_bundle_dir =", "did \"\"\" self.archive_class.archive(self.path, output_path) def clone(self, target_path): \"\"\" Copy the", "archive from a temporary file, resign it with these credentials,", "archive is None: raise NotSignable('No matching archive type found') ua", "is necessary because zip always adds \".zip\" if it #", "= None try: # need to chdir and use relative", "of the main app (aka bundle) \"\"\" pass class AppArchive(Archive):", "self.archive_class) def remove(self): # the containing dir might be gone", "but might be a few directories down, like in a", "def get_helper(helper_name): \"\"\" find paths to executables. Cached in helper_paths", "certificate: {}'.format(certificate)) log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key,", "want to make temp dirs just yet. This recapitulates a", "= is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native @classmethod def archive(cls, path,", "\"\"\" extensions = ['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\"", "of the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info =", "class AppZipArchive(Archive): \"\"\" Just like an app, except it's zipped", "words, we keep retrying until found helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got", "is, in fact, an archive of this type \"\"\" pass", "\"\"\" Path is the \"Containing dir\", the dir at the", "the watchkit bundle # Info.plist # watchkit_bundle <-- this is", "archive this was (Ipa, etc.) \"\"\" self.path = path self.relative_bundle_dir", "like an AppZip, but slightly different paths \"\"\" extensions =", "relative_bundle_dir self.archive_class = archive_class bundle_path = normpath(join(path, relative_bundle_dir)) self.bundle =", "for similarity with the zipped archive classes. In this case,", "= get_watchkit_paths(root_bundle_path) if len(watchkit_paths) > 0: if should_remove: for path", "@abc.abstractmethod def find_bundle_dir(cls, path): \"\"\" Locate the directory of the", "Payload/Foo.app archive class is the kind of archive this was", "ua.bundle.info finally: if ua is not None: ua.remove() return bundle_info", "in archive') else: log.warning('no apps found in archive') return relative_bundle_dir", "we want to respect the desired # output_path's extension, which", "the same type \"\"\" import abc import biplist from bundle", "\"-qu\", self.path, \"-d\", containing_dir]) app_dir = abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT)", "_ in os.walk(root_bundle_path): if path == root_bundle_path: continue try: bundle", "len(apps) > 1: log.warning('more than one app found in archive')", "typical structure: # # app_bundle # ... # some_directory #", "that's already unzipped and you want to sign it. \"\"\"", "\"\"\" Copy the uncompressed archive somewhere else, return initialized UncompressedArchive", "https://github.com/saucelabs/isign/issues/20 is fixed \"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path) if len(watchkit_paths) >", "in os.walk(root_bundle_path): if path == root_bundle_path: continue try: bundle =", "somewhere inside the containing directory, but might be a few", "directory \"\"\" return path @classmethod def _get_plist_path(cls, path): return join(cls.find_bundle_dir(path),", "found') ua = archive.unarchive_to_temp() if info_props: # Override info.plist props", "to a temp file, then resign them, and create an", "for that resigned app \"\"\" if not exists(input_path): raise IOError(\"{0}", "apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): \"\"\" Unified interface to extract", "app_dir = abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__)", "= tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir, 'temp.zip') call([get_helper('zip'), \"-qr\", temp_zip_file, \".\"],", "other words, we keep retrying until found helper_paths[helper_name] = spawn.find_executable(helper_name)", "interface to extract any kind of archive from a temporary", "IPA is Apple's standard for distributing apps. Much like an", "UncompressedArchive(object): \"\"\" This just keeps track of some state with", "to chdir and use relative paths, because zip is stupid", "default. Remove when https://github.com/saucelabs/isign/issues/20 is fixed \"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path)", "path == root_bundle_path: continue try: bundle = Bundle(path) except NotMatched:", "def archive(self, output_path): \"\"\" Re-zip this back up, or simply", "keep retrying until found helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got executable {}", "['zip', 'unzip'] @classmethod def is_helpers_present(cls): \"\"\" returns False if any", "bundle dir is the dir containing the bundle, e.g. Payload/Foo.app", "of archive -- a naked App Bundle, with no extra", "type \"\"\" archive = None for cls in [IpaArchive, AppZipArchive,", "%s\", path, cls.__name__) break return archive def view(input_path): if not", "cls.extensions: log.debug('extension match: %s', extension) if path.endswith(extension): return True return", "to temp... %s -> %s\", self.path, containing_dir) shutil.rmtree(containing_dir) # quirk", "output_path): \"\"\" Re-zip this back up, or simply copy it", "moves # it to the desired target when done if", "paths \"\"\" extensions = ['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object):", "or simply copy it out, depending on what the original", "not cls.is_helpers_present(): raise MissingHelpers(\"helpers not present\") is_native = False log.debug('precheck')", "helper_paths[helper_name] is None: # note, find_executable returns None is not", "= [] for path, _, _ in os.walk(root_bundle_path): if path", "it. \"\"\" def __init__(self, path, relative_bundle_dir, archive_class): \"\"\" Path is", "this is the part that runs on the Watch #", "precheck(cls, path): \"\"\" Checks if an archive looks like this", "raise NotSignable('No matching archive type found') ua = archive.unarchive_to_temp() if", "info_props=None, alternate_entitlements_path=None): \"\"\" Unified interface to extract any kind of", "provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path) except NotSignable as e:", "unarchive_to_temp(self): containing_dir = make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path, \"-d\", containing_dir]) app_dir", "at rest, whether it's a naked app bundle in a", "isfile(path): return False if not cls.is_helpers_present(): raise MissingHelpers(\"helpers not present\")", "None bundle_info = None try: archive = archive_factory(input_path) if archive", "a zipfile\") zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir", "not isdir(path): return False if not os.path.exists(cls._get_plist_path(path)): return False plist", "dir can't exist already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir,", "when https://github.com/saucelabs/isign/issues/20 is fixed \"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path) if len(watchkit_paths)", "log.error(\"missing helper for class {}: {}\".format(cls.__name__, helper_name)) is_present = False", "app_dir_pattern = r'^([^/]+\\.app/).*$' extensions = ['.zip'] helpers = ['zip', 'unzip']", "spawn.find_executable(helper_name) log.debug(\"got executable {} for {}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name] def", "= self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self): containing_dir = make_temp_dir() call([get_helper('unzip'), \"-qu\",", "Apple's standard for distributing apps. Much like an AppZip, but", "fixed \"\"\" watchkit_paths = get_watchkit_paths(root_bundle_path) if len(watchkit_paths) > 0: if", "True helper_paths = {} log = logging.getLogger(__name__) def get_helper(helper_name): \"\"\"", "in other words, we keep retrying until found helper_paths[helper_name] =", "self.path = path self.relative_bundle_dir = relative_bundle_dir self.archive_class = archive_class bundle_path", "what the original archive class did \"\"\" self.archive_class.archive(self.path, output_path) def", "Bundle, is_info_plist_native from exceptions import MissingHelpers, NotSignable, NotMatched from distutils", "if not cls.is_helpers_present(): raise MissingHelpers(\"helpers not present\") is_native = False", "['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\" This just keeps", "if not isdir(path): return False if not os.path.exists(cls._get_plist_path(path)): return False", "of archive this was (Ipa, etc.) \"\"\" self.path = path", "None for cls in [IpaArchive, AppZipArchive, AppArchive]: if cls.precheck(path): archive", "None and isdir(temp_zip_dir): shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\" IPA is Apple's", "directory of the main app (aka bundle) \"\"\" pass class", "the bundle, e.g. Payload/Foo.app archive class is the kind of", "same type \"\"\" import abc import biplist from bundle import", "very similar precheck in the Bundle class \"\"\" if not", "except NotMatched: # this directory is not a bundle continue", "of copytree, top dir can't exist already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir,", "extract these apps to a temp file, then resign them,", "if not exists(input_path): raise IOError(\"{0} not found\".format(input_path)) log.debug('Signing with apple_cert:", "os.path import abspath, dirname, exists, isdir, isfile, join, normpath import", "or helper_paths[helper_name] is None: # note, find_executable returns None is", "def archive_factory(path): \"\"\" Guess what kind of archive we are", "import abc import biplist from bundle import App, Bundle, is_info_plist_native", "if bundle.info.get('WKWatchKitApp') is True: # get the *containing* bundle watchkit_paths.append(dirname(path))", "props of the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info", "if archive is None: raise NotMatched('No matching archive type found')", "app that's already unzipped and you want to sign it.", "dir at the root level of the unzipped archive (or", "self.relative_bundle_dir, self.archive_class) def remove(self): # the containing dir might be", "return an archive object. Returns None if path did not", "= logging.getLogger(__name__) def get_helper(helper_name): \"\"\" find paths to executables. Cached", "for distributing apps. Much like an AppZip, but slightly different", "# watchkit_bundle <-- this is the part that runs on", "{}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name] def make_temp_dir(): return tempfile.mkdtemp(prefix=\"isign-\") def get_watchkit_paths(root_bundle_path):", "could be \".ipa\" or who knows. # So we move", "\"\"\" Obtain app metadata from Info.plist without unarchiving \"\"\" pass", "Obtain app metadata from Info.plist without unarchiving \"\"\" pass @abc.abstractmethod", "`zip` won't overwrite existing files, so this is safer. temp_zip_dir", "= make_temp_dir() call([get_helper('unzip'), \"-qu\", self.path, \"-d\", containing_dir]) app_dir = abspath(join(containing_dir,", "certain class # methods we want to ensure are implemented.", "{}\".format(is_native)) return is_native @classmethod def archive(cls, path, output_path): if exists(output_path):", "\"\"\" returns False if any of our helper apps wasn't", "else: log.warning('no apps found in archive') return relative_bundle_dir @classmethod def", "is_native @classmethod def get_info(cls, relative_bundle_dir, zipfile_obj): plist_path = cls._get_plist_path(relative_bundle_dir) plist_bytes", "found helper_paths[helper_name] = spawn.find_executable(helper_name) log.debug(\"got executable {} for {}\".format(helper_paths[helper_name], helper_name))", "was (Ipa, etc.) \"\"\" self.path = path self.relative_bundle_dir = relative_bundle_dir", "\"\"\" if not isfile(path): return False if not cls.is_helpers_present(): raise", "the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info", "found in archive') return relative_bundle_dir @classmethod def _get_plist_path(cls, relative_bundle_dir): return", "to make temp dirs just yet. This recapitulates a very", "import logging import os from os.path import abspath, dirname, exists,", "recapitulates a very similar precheck in the Bundle class \"\"\"", "bundle {}\".format(path)) shutil.rmtree(path) else: raise NotSignable(\"Cannot yet sign WatchKit bundles\")", "does not have an extension. But we want to respect", "the uncompressed archive somewhere else, return initialized UncompressedArchive \"\"\" shutil.copytree(self.path,", "\"-qr\", temp_zip_file, \".\"], cwd=containing_dir) shutil.move(temp_zip_file, output_path) log.info(\"archived %s to %s\"", "archive.unarchive_to_temp() bundle_info = ua.bundle.info finally: if ua is not None:", "# # We also do a little dance with making", "them, and create an archive of the same type \"\"\"", "= archive.unarchive_to_temp() if info_props: # Override info.plist props of the", "App Bundle, with no extra directory structure, compression, etc \"\"\"", "continue if bundle.info.get('WKWatchKitApp') is True: # get the *containing* bundle", "executable {} for {}\".format(helper_paths[helper_name], helper_name)) return helper_paths[helper_name] def make_temp_dir(): return", "pass @abc.abstractmethod def find_bundle_dir(cls, path): \"\"\" Locate the directory of", "zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is not None: plist_path", "archive_factory(input_path) if archive is None: raise NotSignable('No matching archive type", "relative_bundle_dir)) self.bundle = App(bundle_path) def archive(self, output_path): \"\"\" Re-zip this", "bundle # Info.plist # watchkit_bundle <-- this is the part", "archive_factory(path): \"\"\" Guess what kind of archive we are dealing", "an app, except it's zipped up, and when repackaged, should", "we want to ensure are implemented. @abc.abstractmethod def unarchive_to_temp(self): \"\"\"", "kind of app. Have to examine within the zipfile, b/c", "of this bundle that have watchkit \"\"\" # typical structure:", "class is the kind of archive this was (Ipa, etc.)", "extension. But we want to respect the desired # output_path's", "if not isfile(path): return False if not cls.is_helpers_present(): raise MissingHelpers(\"helpers", "bundle continue if bundle.info.get('WKWatchKitApp') is True: # get the *containing*", "= ua.bundle.info ua.archive(output_path) except NotSignable as e: msg = \"Not", "# We also do a little dance with making another", "the desired # output_path's extension, which could be \".ipa\" or", "# # app_bundle # ... # some_directory # watchkit_extension <--", "log.debug('Signing with provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua", "= '.' self.bundle_info = self.get_info(self.path) def unarchive_to_temp(self): containing_dir = make_temp_dir()", "def _get_plist_path(cls, path): return join(cls.find_bundle_dir(path), \"Info.plist\") @classmethod def get_info(cls, path):", "(cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this is an archive, and a zipfile\")", "present\") is_native = False log.debug('precheck') log.debug('path: %s', path) if (cls.is_archive_extension_match(path)", "resigned app \"\"\" if not exists(input_path): raise IOError(\"{0} not found\".format(input_path))", "None if path did not match any archive type \"\"\"", "within the zipfile, b/c we don't want to make temp", "False plist = cls.get_info(path) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return", "the directory of the main app (aka bundle) \"\"\" pass", "a similar archive for that resigned app \"\"\" if not", "{}\".format(path)) shutil.rmtree(path) else: raise NotSignable(\"Cannot yet sign WatchKit bundles\") class", "can't exist already shutil.copytree(self.path, containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.',", "zipfile_obj = zipfile.ZipFile(path) relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is not", "self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod def archive(cls,", "\"\"\" find paths to executables. Cached in helper_paths \"\"\" if", "def archive(cls, path, output_path): \"\"\" Archive a directory to an", "a naked App Bundle, with no extra directory structure, compression,", "return relative_bundle_dir @classmethod def _get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\") @classmethod", "extensions = ['.zip'] helpers = ['zip', 'unzip'] @classmethod def is_helpers_present(cls):", "= self.find_bundle_dir(zipfile_obj) self.bundle_info = self.get_info(self.relative_bundle_dir, zipfile_obj) def unarchive_to_temp(self): containing_dir =", "somewhere \"\"\" # the temp file is necessary because zip", "= cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is not None: plist_path = cls._get_plist_path(relative_bundle_dir)", "@classmethod def is_archive_extension_match(cls, path): \"\"\" does this path have the", "it back up once re-signed. The bundle is located somewhere", "plist = cls.get_info(path) is_native = is_info_plist_native(plist) log.debug(\"is_native: {}\".format(is_native)) return is_native", "signable: <{0}>: {1}\\n\".format(input_path, e) log.info(msg) raise finally: if ua is", "self.archive_class = archive_class bundle_path = normpath(join(path, relative_bundle_dir)) self.bundle = App(bundle_path)", "and how to re-zip it back up once re-signed. The", "get_watchkit_paths(root_bundle_path): \"\"\" collect sub-bundles of this bundle that have watchkit", "this case, the bundle dir *is* the directory \"\"\" return", "= make_temp_dir() log.debug(\"unarchiving to temp... %s -> %s\", self.path, containing_dir)", "bundle_info = None try: archive = archive_factory(input_path) if archive is", "else: raise NotSignable(\"Cannot yet sign WatchKit bundles\") class Archive(object): __metaclass__", "# watchkit_paths = [] for path, _, _ in os.walk(root_bundle_path):", "for path, _, _ in os.walk(root_bundle_path): if path == root_bundle_path:", "any archive type \"\"\" archive = None for cls in", "shutil.rmtree(temp_zip_dir) class IpaArchive(AppZipArchive): \"\"\" IPA is Apple's standard for distributing", "logging.getLogger(__name__) def get_helper(helper_name): \"\"\" find paths to executables. Cached in", "archive(cls, path, output_path): \"\"\" Archive a directory to an output", "an AppZip, but slightly different paths \"\"\" extensions = ['.ipa']", "get the *containing* bundle watchkit_paths.append(dirname(path)) return watchkit_paths def process_watchkit(root_bundle_path, should_remove=False):", "= zipfile_obj.read(plist_path) return biplist.readPlistFromString(plist_bytes) def __init__(self, path): self.path = path", "containing_dir) process_watchkit(containing_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, '.', self.__class__) class AppZipArchive(Archive): \"\"\"", "AppArchive archive) relative bundle dir is the dir containing the", "temp... %s -> %s\", self.path, containing_dir) shutil.rmtree(containing_dir) # quirk of", "file_name in file_list: matched = re.match(cls.app_dir_pattern, file_name) if matched: apps.add(matched.group(1))", "directory to an output path \"\"\" pass @abc.abstractmethod def get_info(cls,", "archive.unarchive_to_temp() if info_props: # Override info.plist props of the parent", "because zip is stupid temp_zip_dir = tempfile.mkdtemp(prefix=\"isign-zip-\") temp_zip_file = join(temp_zip_dir,", "is None: log.error(\"missing helper for class {}: {}\".format(cls.__name__, helper_name)) is_present", "Info.plist # watchkit_bundle <-- this is the part that runs", "\"-d\", containing_dir]) app_dir = abspath(join(containing_dir, self.relative_bundle_dir)) process_watchkit(app_dir, REMOVE_WATCHKIT) return UncompressedArchive(containing_dir,", "biplist.readPlist(cls._get_plist_path(path)) @classmethod def precheck(cls, path): if not isdir(path): return False", "relative_bundle_dir = cls.find_bundle_dir(zipfile_obj) if relative_bundle_dir is not None: plist_path =", "dir *is* the directory \"\"\" return path @classmethod def _get_plist_path(cls,", "REMOVE_WATCHKIT) return UncompressedArchive(containing_dir, self.relative_bundle_dir, self.__class__) @classmethod def archive(cls, containing_dir, output_path):", "when repackaged, should be re-zipped. \"\"\" app_dir_pattern = r'^([^/]+\\.app/).*$' extensions", "with these credentials, and create a similar archive for that", "isdir(path): return False if not os.path.exists(cls._get_plist_path(path)): return False plist =", "like this kind of app. Have to examine within the", "\"\"\" pass @abc.abstractmethod def precheck(cls, path): \"\"\" Check if this", "way to ensure the an unused # filename. Also, `zip`", "a zipfile. Note this is a classmethod, because the caller", "= path zipfile_obj = zipfile.ZipFile(path) self.relative_bundle_dir = self.find_bundle_dir(zipfile_obj) self.bundle_info =", "log.debug('precheck') log.debug('path: %s', path) if (cls.is_archive_extension_match(path) and zipfile.is_zipfile(path)): log.debug(\"this is", "\"\"\" Unfortunately, we currently can't sign WatchKit. If you don't", "our helper apps wasn't found in class init \"\"\" is_present", "{}\".format(is_native)) return is_native @classmethod def get_info(cls, relative_bundle_dir, zipfile_obj): plist_path =", "output_path) log.info(\"archived %s to %s\" % (cls.__name__, output_path)) def __init__(self,", "watchkit_paths def process_watchkit(root_bundle_path, should_remove=False): \"\"\" Unfortunately, we currently can't sign", "return bundle_info def resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path, info_props=None,", "class AppArchive(Archive): \"\"\" The simplest form of archive -- a", "_get_plist_path(cls, relative_bundle_dir): return join(relative_bundle_dir, \"Info.plist\") @classmethod def precheck(cls, path): \"\"\"", "extensions = ['.ipa'] app_dir_pattern = r'^(Payload/[^/]+\\.app/).*$' class UncompressedArchive(object): \"\"\" This", "matching archive type found') ua = archive.unarchive_to_temp() bundle_info = ua.bundle.info", "zipfile, b/c we don't want to make temp dirs just", "containing directory, but might be a few directories down, like", "temp file is necessary because zip always adds \".zip\" if" ]
[ "environment(self): \"\"\" collects the runtime information from dependencies. For normal", "information from dependencies. For normal libraries should be very occasional", "runtime information from dependencies. For normal libraries should be very", "dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv def generate(self, auto_activate=False): run_env", "runenv_from_cpp_info(conanfile, cpp_info): \"\"\" return an Environment deducing the runtime information", "BINARY_SKIP return dyn_runenv if cpp_info.bin_paths: # cpp_info.exes is not defined", "= self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test for _, dep in list(host_req.items())", "will be the build-os, otherwise it will be the host-os", "return an Environment deducing the runtime information from a cpp_info", "dep in list(host_req.items()) + list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info))", "dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If it is a build_require this will", "private one = BINARY_SKIP return dyn_runenv if cpp_info.bin_paths: # cpp_info.exes", "the runtime information from a cpp_info \"\"\" dyn_runenv = Environment(conanfile)", "from conan.tools.env import Environment def runenv_from_cpp_info(conanfile, cpp_info): \"\"\" return an", "defined from its dependencies, and also from profiles \"\"\" def", "should be very occasional \"\"\" runenv = Environment(self._conanfile) # FIXME:", "cpp_info.bin_paths) # If it is a build_require this will be", "the dependency is a private one = BINARY_SKIP return dyn_runenv", "this will be the build-os, otherwise it will be the", "cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return", "For normal libraries should be very occasional \"\"\" runenv =", "occasional \"\"\" runenv = Environment(self._conanfile) # FIXME: Missing profile info", "Missing profile info # FIXME: Cache value? host_req = self._conanfile.dependencies.host", "if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv def generate(self, auto_activate=False):", "Environment deducing the runtime information from a cpp_info \"\"\" dyn_runenv", "profiles \"\"\" def __init__(self, conanfile): self._conanfile = conanfile def environment(self):", "deducing the runtime information from a cpp_info \"\"\" dyn_runenv =", "Cache value? host_req = self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test for _,", "\"\"\" runenv = Environment(self._conanfile) # FIXME: Missing profile info #", "is defined from its dependencies, and also from profiles \"\"\"", "if cpp_info.bin_paths: # cpp_info.exes is not defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths)", "environment that is defined from its dependencies, and also from", "cpp_info.exes is not defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If it", "FIXME: Cache value? host_req = self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test for", "very occasional \"\"\" runenv = Environment(self._conanfile) # FIXME: Missing profile", "dependencies. For normal libraries should be very occasional \"\"\" runenv", "conanfile def environment(self): \"\"\" collects the runtime information from dependencies.", "= Environment(conanfile) if cpp_info is None: # This happens when", "= Environment(self._conanfile) # FIXME: Missing profile info # FIXME: Cache", "a build_require this will be the build-os, otherwise it will", "# FIXME: Missing profile info # FIXME: Cache value? host_req", "runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv def generate(self, auto_activate=False): run_env = self.environment()", "class VirtualRunEnv: \"\"\" captures the conanfile environment that is defined", "cpp_info): \"\"\" return an Environment deducing the runtime information from", "= conanfile def environment(self): \"\"\" collects the runtime information from", "when the dependency is a private one = BINARY_SKIP return", "cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv class VirtualRunEnv: \"\"\"", "runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv def generate(self, auto_activate=False): run_env =", "if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv class VirtualRunEnv: \"\"\" captures", "__init__(self, conanfile): self._conanfile = conanfile def environment(self): \"\"\" collects the", "normal libraries should be very occasional \"\"\" runenv = Environment(self._conanfile)", "\"\"\" def __init__(self, conanfile): self._conanfile = conanfile def environment(self): \"\"\"", "dyn_runenv if cpp_info.bin_paths: # cpp_info.exes is not defined yet dyn_runenv.prepend_path(\"PATH\",", "= self._conanfile.dependencies.test for _, dep in list(host_req.items()) + list(test_req.items()): if", "dyn_runenv = Environment(conanfile) if cpp_info is None: # This happens", "its dependencies, and also from profiles \"\"\" def __init__(self, conanfile):", "cpp_info.bin_paths: # cpp_info.exes is not defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) #", "be the host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if", "runenv def generate(self, auto_activate=False): run_env = self.environment() if run_env: run_env.save_script(\"conanrunenv\",", "cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv class", "conan.tools.env import Environment def runenv_from_cpp_info(conanfile, cpp_info): \"\"\" return an Environment", "conanfile): self._conanfile = conanfile def environment(self): \"\"\" collects the runtime", "import Environment def runenv_from_cpp_info(conanfile, cpp_info): \"\"\" return an Environment deducing", "the runtime information from dependencies. For normal libraries should be", "self._conanfile.dependencies.test for _, dep in list(host_req.items()) + list(test_req.items()): if dep.runenv_info:", "Environment(conanfile) if cpp_info is None: # This happens when the", "Environment(self._conanfile) # FIXME: Missing profile info # FIXME: Cache value?", "profile info # FIXME: Cache value? host_req = self._conanfile.dependencies.host test_req", "self._conanfile = conanfile def environment(self): \"\"\" collects the runtime information", "runtime information from a cpp_info \"\"\" dyn_runenv = Environment(conanfile) if", "# If it is a build_require this will be the", "def generate(self, auto_activate=False): run_env = self.environment() if run_env: run_env.save_script(\"conanrunenv\", auto_activate=auto_activate)", "\"\"\" captures the conanfile environment that is defined from its", "an Environment deducing the runtime information from a cpp_info \"\"\"", "self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test for _, dep in list(host_req.items()) +", "host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\",", "\"\"\" dyn_runenv = Environment(conanfile) if cpp_info is None: # This", "from profiles \"\"\" def __init__(self, conanfile): self._conanfile = conanfile def", "list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv def generate(self,", "cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv class VirtualRunEnv: \"\"\" captures the", "it will be the host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\",", "is a build_require this will be the build-os, otherwise it", "dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv class VirtualRunEnv: \"\"\" captures the conanfile", "a cpp_info \"\"\" dyn_runenv = Environment(conanfile) if cpp_info is None:", "cpp_info \"\"\" dyn_runenv = Environment(conanfile) if cpp_info is None: #", "one = BINARY_SKIP return dyn_runenv if cpp_info.bin_paths: # cpp_info.exes is", "otherwise it will be the host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths)", "value? host_req = self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test for _, dep", "# FIXME: Cache value? host_req = self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test", "yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If it is a build_require this", "# cpp_info.exes is not defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If", "for _, dep in list(host_req.items()) + list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info)", "test_req = self._conanfile.dependencies.test for _, dep in list(host_req.items()) + list(test_req.items()):", "that is defined from its dependencies, and also from profiles", "will be the host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths)", "a private one = BINARY_SKIP return dyn_runenv if cpp_info.bin_paths: #", "# This happens when the dependency is a private one", "is None: # This happens when the dependency is a", "if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths)", "Environment def runenv_from_cpp_info(conanfile, cpp_info): \"\"\" return an Environment deducing the", "dependency is a private one = BINARY_SKIP return dyn_runenv if", "dyn_runenv class VirtualRunEnv: \"\"\" captures the conanfile environment that is", "def environment(self): \"\"\" collects the runtime information from dependencies. For", "= BINARY_SKIP return dyn_runenv if cpp_info.bin_paths: # cpp_info.exes is not", "info # FIXME: Cache value? host_req = self._conanfile.dependencies.host test_req =", "defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If it is a build_require", "cpp_info is None: # This happens when the dependency is", "happens when the dependency is a private one = BINARY_SKIP", "\"\"\" collects the runtime information from dependencies. For normal libraries", "\"\"\" return an Environment deducing the runtime information from a", "captures the conanfile environment that is defined from its dependencies,", "cpp_info.framework_paths) return dyn_runenv class VirtualRunEnv: \"\"\" captures the conanfile environment", "be very occasional \"\"\" runenv = Environment(self._conanfile) # FIXME: Missing", "information from a cpp_info \"\"\" dyn_runenv = Environment(conanfile) if cpp_info", "VirtualRunEnv: \"\"\" captures the conanfile environment that is defined from", "and also from profiles \"\"\" def __init__(self, conanfile): self._conanfile =", "the conanfile environment that is defined from its dependencies, and", "from dependencies. For normal libraries should be very occasional \"\"\"", "host_req = self._conanfile.dependencies.host test_req = self._conanfile.dependencies.test for _, dep in", "return dyn_runenv if cpp_info.bin_paths: # cpp_info.exes is not defined yet", "dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv class VirtualRunEnv:", "dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths: dyn_runenv.prepend_path(\"DYLD_FRAMEWORK_PATH\", cpp_info.framework_paths) return dyn_runenv", "FIXME: Missing profile info # FIXME: Cache value? host_req =", "+ list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv def", "return dyn_runenv class VirtualRunEnv: \"\"\" captures the conanfile environment that", "list(host_req.items()) + list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return runenv", "build_require this will be the build-os, otherwise it will be", "None: # This happens when the dependency is a private", "def runenv_from_cpp_info(conanfile, cpp_info): \"\"\" return an Environment deducing the runtime", "if cpp_info is None: # This happens when the dependency", "the host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\", cpp_info.lib_paths) dyn_runenv.prepend_path(\"DYLD_LIBRARY_PATH\", cpp_info.lib_paths) if cpp_info.framework_paths:", "This happens when the dependency is a private one =", "it is a build_require this will be the build-os, otherwise", "dep.cpp_info)) return runenv def generate(self, auto_activate=False): run_env = self.environment() if", "build-os, otherwise it will be the host-os if cpp_info.lib_paths: dyn_runenv.prepend_path(\"LD_LIBRARY_PATH\",", "conanfile environment that is defined from its dependencies, and also", "dependencies, and also from profiles \"\"\" def __init__(self, conanfile): self._conanfile", "libraries should be very occasional \"\"\" runenv = Environment(self._conanfile) #", "return runenv def generate(self, auto_activate=False): run_env = self.environment() if run_env:", "is a private one = BINARY_SKIP return dyn_runenv if cpp_info.bin_paths:", "also from profiles \"\"\" def __init__(self, conanfile): self._conanfile = conanfile", "the build-os, otherwise it will be the host-os if cpp_info.lib_paths:", "If it is a build_require this will be the build-os,", "runenv = Environment(self._conanfile) # FIXME: Missing profile info # FIXME:", "is not defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If it is", "be the build-os, otherwise it will be the host-os if", "from a cpp_info \"\"\" dyn_runenv = Environment(conanfile) if cpp_info is", "_, dep in list(host_req.items()) + list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile,", "from its dependencies, and also from profiles \"\"\" def __init__(self,", "not defined yet dyn_runenv.prepend_path(\"PATH\", cpp_info.bin_paths) # If it is a", "in list(host_req.items()) + list(test_req.items()): if dep.runenv_info: runenv.compose_env(dep.runenv_info) runenv.compose_env(runenv_from_cpp_info(self._conanfile, dep.cpp_info)) return", "def __init__(self, conanfile): self._conanfile = conanfile def environment(self): \"\"\" collects", "collects the runtime information from dependencies. For normal libraries should" ]
[ "import Enum from dataclasses import dataclass from uuid import UUID", "id : UUID = None user_id : UUID = None", "from datetime import datetime class ListType(str, Enum): LIST : str", "'list' TEMPLATE: str = 'template' @classmethod def _missing_(cls, value): return", "uuid import UUID from datetime import datetime class ListType(str, Enum):", "'template' @classmethod def _missing_(cls, value): return ListType.LIST @dataclass class List:", "dataclass from uuid import UUID from datetime import datetime class", "import UUID from datetime import datetime class ListType(str, Enum): LIST", "@classmethod def _missing_(cls, value): return ListType.LIST @dataclass class List: id", "str = None created_on: datetime = None type : ListType", "List model ********************************************************************************** \"\"\" from enum import Enum from dataclasses", "class List: id : UUID = None user_id : UUID", "UUID = None user_id : UUID = None name :", "import datetime class ListType(str, Enum): LIST : str = 'list'", "class ListType(str, Enum): LIST : str = 'list' TEMPLATE: str", "Enum from dataclasses import dataclass from uuid import UUID from", ": UUID = None user_id : UUID = None name", "= None user_id : UUID = None name : str", "None name : str = None created_on: datetime = None", "value): return ListType.LIST @dataclass class List: id : UUID =", "_missing_(cls, value): return ListType.LIST @dataclass class List: id : UUID", "********************************************************************************** List model ********************************************************************************** \"\"\" from enum import Enum from", "TEMPLATE: str = 'template' @classmethod def _missing_(cls, value): return ListType.LIST", "List: id : UUID = None user_id : UUID =", "name : str = None created_on: datetime = None type", "= None name : str = None created_on: datetime =", "import dataclass from uuid import UUID from datetime import datetime", "from uuid import UUID from datetime import datetime class ListType(str,", "\"\"\" ********************************************************************************** List model ********************************************************************************** \"\"\" from enum import Enum", "UUID = None name : str = None created_on: datetime", "ListType(str, Enum): LIST : str = 'list' TEMPLATE: str =", "********************************************************************************** \"\"\" from enum import Enum from dataclasses import dataclass", "str = 'list' TEMPLATE: str = 'template' @classmethod def _missing_(cls,", "datetime import datetime class ListType(str, Enum): LIST : str =", "from enum import Enum from dataclasses import dataclass from uuid", "= 'list' TEMPLATE: str = 'template' @classmethod def _missing_(cls, value):", "ListType.LIST @dataclass class List: id : UUID = None user_id", "@dataclass class List: id : UUID = None user_id :", "Enum): LIST : str = 'list' TEMPLATE: str = 'template'", "None created_on: datetime = None type : ListType = ListType.LIST", "datetime class ListType(str, Enum): LIST : str = 'list' TEMPLATE:", "None user_id : UUID = None name : str =", ": str = None created_on: datetime = None type :", "= 'template' @classmethod def _missing_(cls, value): return ListType.LIST @dataclass class", ": str = 'list' TEMPLATE: str = 'template' @classmethod def", "UUID from datetime import datetime class ListType(str, Enum): LIST :", "user_id : UUID = None name : str = None", "str = 'template' @classmethod def _missing_(cls, value): return ListType.LIST @dataclass", "<gh_stars>0 \"\"\" ********************************************************************************** List model ********************************************************************************** \"\"\" from enum import", "enum import Enum from dataclasses import dataclass from uuid import", ": UUID = None name : str = None created_on:", "model ********************************************************************************** \"\"\" from enum import Enum from dataclasses import", "= None created_on: datetime = None type : ListType =", "LIST : str = 'list' TEMPLATE: str = 'template' @classmethod", "return ListType.LIST @dataclass class List: id : UUID = None", "def _missing_(cls, value): return ListType.LIST @dataclass class List: id :", "\"\"\" from enum import Enum from dataclasses import dataclass from", "from dataclasses import dataclass from uuid import UUID from datetime", "dataclasses import dataclass from uuid import UUID from datetime import" ]
[ "1, \"sound\": _IOS_SOUND_POWER_PEAK, } else: push_data = { \"category\": \"confirm\",", "for {self._min_time_high} secs, \" f\"(low={self._lower_limit} W for {self._min_time_low} secs). \"", "notify when back to normal (< lower limit). \"\"\" #", ") self.log( f\"TRIGGER ALARM with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif,", "coding: utf-8 -*- \"\"\" Automation task as a AppDaemon App", "), } return data_msg # noinspection PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\"", "sostenidos)\" ), } data_msg[\"message\"] = data_msg[\"message\"].format( current_peak, time_now, pow_instant, pow_sustained", "dt from enum import IntEnum import appdaemon.plugins.hass.hassapi as hass LOG_LEVEL", "} data_msg[\"data\"] = {\"push\": push_data} return data_msg def make_telegram_push_data(self, data_msg:", "\"WARNING\" LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT = 1.1 # 10% over", "10% over limit MIN_TIME_TURN_OFF_AC = 60 # secs # Big", "\" f\"(low={self._lower_limit} W for {self._min_time_low} secs). \" f\"Notify: {self._notifier}.\", level=LOG_LEVEL,", "control.\"\"\" try: new = int(float(new)) except ValueError: return now =", "log=LOGGER, ) self._critical_alarm_state = True elif new < self._lower_limit: if", "self.log( \"RESET ALARM MODE at {}\".format(now), level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif,", "self._alarm_start = None self._turn_off_measure_taken = False self._current_peak = 0 elif", "def notify_alert(self, type_notif: TypeNotif, data: dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg", "60.0 data_msg = { \"title\": \"Consumo eléctrico: Normal\", \"message\": (", "new # Pre-Alarm state, before trigger if self._last_trigger is None:", "{pow_instant} W ({pow_sustained} sostenidos)\" ), } data_msg[\"message\"] = data_msg[\"message\"].format( current_peak,", "self.value == self.ALERT_CRITICAL: push_data = { \"category\": \"powerpeak\", \"badge\": 10,", "level=\"ERROR\", log=LOGGER, ) type_notif = TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message( self._current_peak,", "self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"] = [ [(\"Luces ON\", \"/luceson\"), (\"Luces", "[ (\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"), ], [ (", "= False devices_turning_off = \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off", "# TRIGGER ALARM self._alarm_start = now self._turn_off_measure_taken = False type_notif", "float _min_time_high: int _min_time_low: int # App user inputs _main_power:", "try: new = int(float(new)) except ValueError: return # Update peak", "than a certain limit), and after that, notify when back", "self._max_peak = float(self.args.get(\"max_power_peak_kw\")) * 1000.0 # Listen for Main Power", "self._current_peak = new if ( not self._turn_off_measure_taken and new >", "None self._turn_off_measure_taken = False self._current_peak = 0 elif ( not", "reset if new > self._current_peak: self._current_peak = new if (", "trigger alarm) # pass elif self._alarm_state: # Alarm state, waiting", "está a punto de saltar!\", \"message\": ( f\"Apagando {devices_off} para", "push message construction. \"\"\" ALERT_OFF = 0 ALERT_ON = 1", "self._critical_alarm_state = False self._last_trigger = None self._alarm_start = None self._turn_off_measure_taken", "{\"push\": push_data} return data_msg def make_telegram_push_data(self, data_msg: dict, target: int)", "= None self._turn_off_measure_taken = False self._current_peak = 0 elif (", "consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire acondicionado\" BIG_CONSUMER_2 =", "ALERT_CRITICAL = 2 def make_ios_push_data(self, data_msg: dict) -> dict: if", "Limit Values _max_peak: float _upper_limit: float _lower_limit: float _min_time_high: int", "W for {self._min_time_high} secs, \" f\"(low={self._lower_limit} W for {self._min_time_low} secs).", "= \"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\" Handler for", "\"badge\": 0, } data_msg[\"data\"] = {\"push\": push_data} return data_msg def", "< self._upper_limit ): self.log( \"DISABLE CRITICAL ALARM (now {} W)\".format(new),", "level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = True self._critical_alarm_state =", "= None _alarm_start = None _turn_off_measure_taken = False _current_peak =", "are greater than a certain limit), and after that, notify", "\"Alto consumo eléctrico!\", \"message\": ( f\"Peak: {current_peak} W en {time_now}.", "( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger is not None else \"???\" )", "self._alarm_state and (new > self._upper_limit): if new > self._current_peak: self._current_peak", "\"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\": 1.0, \"thread-id\": \"power-peak-group\", } elif", "now # else: # wait some more time # (this", "in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = None self._current_peak =", "self, current_peak, last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, ) -> dict:", "self.config.get(\"chatid_sensor\") # Power limits self._upper_limit = float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit", "BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off = BIG_CONSUMER_2_LABEL", "\"\"\" import datetime as dt from enum import IntEnum import", "self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif, data) self._last_trigger = now", "* 1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high = int(self.args.get(\"min_time_high\"))", "(self._last_trigger is not None) and ( (now - self._last_trigger).total_seconds() >", "for Home Assistant - current meter PEAK POWER notifications \"\"\"", "self.value == self.ALERT_ON: data_msg = { \"title\": \"Alto consumo eléctrico!\",", "TypeNotif.ALERT_ON data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, )", "\"Consumo eléctrico: Normal\", \"message\": ( f\"Potencia normal desde {time_now}, \"", "( (now - self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC ) ): # Turn", "_alarm_start = None _turn_off_measure_taken = False _current_peak = 0 def", "if AC + heater are ON self._turn_off_measure_taken = True self._critical_alarm_state", "import IntEnum import appdaemon.plugins.hass.hassapi as hass LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT", "import appdaemon.plugins.hass.hassapi as hass LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT = \"WARNING\"", "elif self._alarm_state: # Alarm state, waiting for reset if new", "peaks (when they are greater than a certain limit), and", "= False _critical_alarm_state: bool = False _last_trigger = None _alarm_start", "\"/service_call switch/turn_off switch.calentador\", ), ( \"AC OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\",", "\"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\": 1, \"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK,", "= int(self.args.get(\"min_time_low\")) # TODO implement _max_peak over _instant_power self._max_peak =", "= now # else: # wait some more time #", "TRIGGER (was in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = None", "= False self._critical_alarm_state = False self._last_trigger = None self._alarm_start =", "as a AppDaemon App for Home Assistant - current meter", "as dt from enum import IntEnum import appdaemon.plugins.hass.hassapi as hass", "= now elif ( now - self._last_trigger ).total_seconds() > self._min_time_high:", "hass LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT = \"WARNING\" LOGGER = \"special_event_log\"", "if last_trigger is not None else \"???\" ) if self.value", "def initialize(self): \"\"\"AppDaemon required method for app init.\"\"\" self._main_power =", "self._target_sensor = self.config.get(\"chatid_sensor\") # Power limits self._upper_limit = float(self.args.get(\"max_power_kw\")) *", "elif (self._last_trigger is not None) and ( (now - self._last_trigger).total_seconds()", "dict: if self.value == self.ALERT_CRITICAL: push_data = { \"category\": \"powerpeak\",", "self._last_trigger, self._alarm_start, ) self.log( \"RESET ALARM MODE at {}\".format(now), level=LOG_LEVEL,", "= int(float(new)) except ValueError: return # Update peak if new", "now - self._last_trigger ).total_seconds() > self._min_time_low: # RESET ALARM type_notif", "self._upper_limit and new > self._current_peak: self._current_peak = new # noinspection", "None _turn_off_measure_taken = False _current_peak = 0 def initialize(self): \"\"\"AppDaemon", "devices turned off self.log( f\"CRITICAL ACTION: Turn off '{devices_turning_off}'\", level=\"ERROR\",", "self.log( \"RESET LAST TRIGGER (was in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, )", "_min_time_high: int _min_time_low: int # App user inputs _main_power: str", "\"\"\" # Limit Values _max_peak: float _upper_limit: float _lower_limit: float", "self.ALERT_ON: data_msg = { \"title\": \"Alto consumo eléctrico!\", \"message\": (", "\"/service_call switch/turn_off switch.ac_dry_contact\", ), ], ] return data_msg def make_notification_message(", "False _current_peak = 0 def initialize(self): \"\"\"AppDaemon required method for", ") self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection PyUnusedLocal def peak_power_change(self,", "\"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL =", "now elif ( now - self._last_trigger ).total_seconds() > self._min_time_high: #", "data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, )", "make_notification_message( self, current_peak, last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, ) ->", "pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif, data) self._last_trigger = now else: self._last_trigger", "\"la sobrecarga eléctrica.\" ), } time_now = ( \"{:%H:%M:%S}\".format(last_trigger) if", "not self._turn_off_measure_taken and new > self._upper_limit * COEF_CRITICAL_LIMIT ): self.log(", "= type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, ) self.log( \"RESET ALARM MODE", "if devices_turning_off: # Notification of devices turned off self.log( f\"CRITICAL", "self._critical_alarm_state and new < self._upper_limit ): self.log( \"DISABLE CRITICAL ALARM", "type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, ) self.log( \"RESET ALARM MODE at", "OFF\", \"/lucesoff\")], [ (\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"), ],", "-*- coding: utf-8 -*- \"\"\" Automation task as a AppDaemon", "_instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\")) * 1000.0 # Listen for Main", "level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = True elif new < self._lower_limit:", "* 1000.0 # Listen for Main Power changes: self.listen_state(self.main_power_change, self._main_power)", "= True self._critical_alarm_state = False devices_turning_off = \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE)", "pass elif self._alarm_state: # Alarm state, waiting for reset if", "= \"INFO\" LOG_LEVEL_ALERT = \"WARNING\" LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT =", "= \"aire acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK", "= TypeNotif.ALERT_OFF data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, ) self.log(", "new, kwargs): \"\"\"Sustained Power ALARM logic control.\"\"\" try: new =", "kinds of power notifications. Used to centralize push message construction.", "as hass LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT = \"WARNING\" LOGGER =", "elif self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2", "**tlg_alarm_msg) # noinspection PyUnusedLocal def peak_power_change(self, entity, attribute, old, new,", "devices_turning_off = \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off = BIG_CONSUMER_1_LABEL", "str _target_sensor: str _alarm_state: bool = False _critical_alarm_state: bool =", "ON self._turn_off_measure_taken = True self._critical_alarm_state = False devices_turning_off = \"\"", "(now {} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = False elif", "self._last_trigger).total_seconds() > self._min_time_low ): # Normal operation, reset last trigger", "eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"), ], [ ( \"Calentador OFF\",", "\"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"), ], [ ( \"Calentador OFF\", \"/service_call", "# Limit Values _max_peak: float _upper_limit: float _lower_limit: float _min_time_high:", "int # App user inputs _main_power: str _main_power_peak: str _notifier:", "# Power limits self._upper_limit = float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit =", "except ValueError: return now = dt.datetime.now() if not self._alarm_state and", "make_telegram_push_data(self, data_msg: dict, target: int) -> dict: data_msg[\"target\"] = target", "with P={} W\".format(now, new), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = now", "_IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\" Handler for different kinds", "self.log( \"New power peak event at {} with P={} W\".format(now,", "\"title\": \"Consumo eléctrico: Normal\", \"message\": ( f\"Potencia normal desde {time_now},", "type_notif = TypeNotif.ALERT_ON data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak),", "Turn off AC if AC + heater are ON self._turn_off_measure_taken", "devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif, data) self._last_trigger = now else:", "para intentar evitar \" \"la sobrecarga eléctrica.\" ), } time_now", "> self._current_peak: self._current_peak = new # Pre-Alarm state, before trigger", "to trigger alarm) # pass elif self._alarm_state: # Alarm state,", "TRIGGER ALARM self._alarm_start = now self._turn_off_measure_taken = False type_notif =", "for Main Power changes: self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier Initialized. P={self._main_power},", "turned off self.log( f\"CRITICAL ACTION: Turn off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER,", "in min_time_lower self.log( \"RESET LAST TRIGGER (was in {})\".format(self._last_trigger), level=LOG_LEVEL,", "data_msg[\"data\"] = {\"push\": push_data} return data_msg def make_telegram_push_data(self, data_msg: dict,", "attribute, old, new, kwargs): \"\"\"Sustained Power ALARM logic control.\"\"\" try:", "self._last_trigger is None: # Start power peak event self.log( \"New", "f\"Pico de potencia: {current_peak} W. \" f\"Alerta iniciada hace {duration_min:.1f}", "pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log( f\"TRIGGER ALARM with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER,", "heater are ON self._turn_off_measure_taken = True self._critical_alarm_state = False devices_turning_off", "\"\"\" ALERT_OFF = 0 ALERT_ON = 1 ALERT_CRITICAL = 2", "Update peak if new > self._upper_limit and new > self._current_peak:", "_main_power_peak: str _notifier: str _target_sensor: str _alarm_state: bool = False", "dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), )", "_IOS_SOUND_POWER_PEAK, \"badge\": 0, } data_msg[\"data\"] = {\"push\": push_data} return data_msg", "power peak event at {} with P={} W\".format(now, new), level=LOG_LEVEL,", "level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = False elif ( not self._turn_off_measure_taken", "= target data_msg[\"disable_notification\"] = self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"] = [", "Main Power changes: self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier Initialized. P={self._main_power}, \"", "logic control.\"\"\" try: new = int(float(new)) except ValueError: return now", "= 60 # secs # Big power consumers BIG_CONSUMER_1_CLIMATE =", "are ON self._turn_off_measure_taken = True self._critical_alarm_state = False devices_turning_off =", "= {\"push\": push_data} return data_msg def make_telegram_push_data(self, data_msg: dict, target:", "= \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL", "- self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC ) ): # Turn off AC", "= int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\")) # TODO implement _max_peak over", "= TypeNotif.ALERT_ON data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new,", "} elif self.value == self.ALERT_ON: push_data = { \"category\": \"powerpeak\",", "construction. \"\"\" ALERT_OFF = 0 ALERT_ON = 1 ALERT_CRITICAL =", "self.notify_alert(type_notif, data) self._alarm_state = True self._critical_alarm_state = False self._last_trigger =", "en {time_now}. \" f\"Ahora {pow_instant} W ({pow_sustained} sostenidos)\" ), }", "\"DISABLE CRITICAL ALARM (now {} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state", "# -*- coding: utf-8 -*- \"\"\" Automation task as a", "self._last_trigger = now else: self._last_trigger = now elif (self._last_trigger is", "self.ALERT_CRITICAL: return { \"title\": \"¡El automático está a punto de", "power peaks (when they are greater than a certain limit),", "self._min_time_low = int(self.args.get(\"min_time_low\")) # TODO implement _max_peak over _instant_power self._max_peak", "ALARM with {} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = True", "self._last_trigger ).total_seconds() > self._min_time_low: # RESET ALARM type_notif = TypeNotif.ALERT_OFF", "reset last trigger if no more in min_time_lower self.log( \"RESET", "import datetime as dt from enum import IntEnum import appdaemon.plugins.hass.hassapi", "\"message\": ( f\"Potencia normal desde {time_now}, \" f\"Pico de potencia:", "eléctrico: Normal\", \"message\": ( f\"Potencia normal desde {time_now}, \" f\"Pico", "\"power-peak-group\", \"badge\": 1, \"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK, } else: push_data", "Handler for different kinds of power notifications. Used to centralize", "else: push_data = { \"category\": \"confirm\", \"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK,", "\"power-peak-group\", } elif self.value == self.ALERT_ON: push_data = { \"category\":", "pow_sustained ) else: duration_min = ( dt.datetime.now() - alarm_start ).total_seconds()", "W for {self._min_time_low} secs). \" f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER, )", "at {} with P={} W\".format(now, new), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger", "= self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor = self.config.get(\"chatid_sensor\") # Power limits self._upper_limit", "\"thread-id\": \"power-peak-group\", } elif self.value == self.ALERT_ON: push_data = {", "\"/lucesoff\")], [ (\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"), ], [", "= True self._critical_alarm_state = False self._last_trigger = now # else:", "return # Update peak if new > self._upper_limit and new", "entity, attribute, old, new, kwargs): \"\"\"Power Peak ALARM logic control.\"\"\"", "is None: # Start power peak event self.log( \"New power", ") -> dict: if self.value == self.ALERT_CRITICAL: return { \"title\":", "else: # wait some more time # (this is the", "event, # waiting min time to trigger alarm) # pass", "data_msg def make_notification_message( self, current_peak, last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0,", "self._turn_off_measure_taken = False self._current_peak = 0 elif ( not self._turn_off_measure_taken", "} time_now = ( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger is not None", "init.\"\"\" self._main_power = self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\",", "self._min_time_high: # TRIGGER ALARM self._alarm_start = now self._turn_off_measure_taken = False", "_target_sensor: str _alarm_state: bool = False _critical_alarm_state: bool = False", "P>{self._upper_limit} W for {self._min_time_high} secs, \" f\"(low={self._lower_limit} W for {self._min_time_low}", "push_data = { \"category\": \"powerpeak\", \"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\":", "noinspection PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\" App to notify power peaks", "saltar!\", \"message\": ( f\"Apagando {devices_off} para intentar evitar \" \"la", "_last_trigger = None _alarm_start = None _turn_off_measure_taken = False _current_peak", "): self.log( \"ENABLE CRITICAL ALARM with {} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER,", "implement _max_peak over _instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\")) * 1000.0 #", "= 0 elif ( not self._turn_off_measure_taken and self._critical_alarm_state and new", "self.log( f\"TRIGGER ALARM with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif, data)", "notifications \"\"\" import datetime as dt from enum import IntEnum", "acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\"", "msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = True self._critical_alarm_state", "\"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\": 1, \"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK, }", ") self._critical_alarm_state = False elif ( not self._turn_off_measure_taken and self._critical_alarm_state", "certain limit), and after that, notify when back to normal", "they are greater than a certain limit), and after that,", "Start power peak event self.log( \"New power peak event at", "False elif ( not self._turn_off_measure_taken and self._critical_alarm_state and ( (now", "for app init.\"\"\" self._main_power = self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\") self._notifier", "Assistant - current meter PEAK POWER notifications \"\"\" import datetime", "punto de saltar!\", \"message\": ( f\"Apagando {devices_off} para intentar evitar", "self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if devices_turning_off: # Notification of devices", "data_msg def make_telegram_push_data(self, data_msg: dict, target: int) -> dict: data_msg[\"target\"]", "new, kwargs): \"\"\"Power Peak ALARM logic control.\"\"\" try: new =", "task as a AppDaemon App for Home Assistant - current", "centralize push message construction. \"\"\" ALERT_OFF = 0 ALERT_ON =", "self.value == self.ALERT_CRITICAL: return { \"title\": \"¡El automático está a", "notify_alert(self, type_notif: TypeNotif, data: dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg =", "> self._min_time_low ): # Normal operation, reset last trigger if", "data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, ) self.log( \"RESET ALARM", "with {} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = True elif", "int _min_time_low: int # App user inputs _main_power: str _main_power_peak:", "_critical_alarm_state: bool = False _last_trigger = None _alarm_start = None", "last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, ) -> dict: if self.value", "{} with P={} W\".format(now, new), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger =", "+ heater are ON self._turn_off_measure_taken = True self._critical_alarm_state = False", "1, \"volume\": 1.0, \"thread-id\": \"power-peak-group\", } elif self.value == self.ALERT_ON:", "({pow_sustained} sostenidos)\" ), } data_msg[\"message\"] = data_msg[\"message\"].format( current_peak, time_now, pow_instant,", "( f\"Peak: {current_peak} W en {time_now}. \" f\"Ahora {pow_instant} W", "self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor = self.config.get(\"chatid_sensor\") # Power", "} return data_msg # noinspection PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\" App", "{ \"title\": \"Consumo eléctrico: Normal\", \"message\": ( f\"Potencia normal desde", "Initialized. P={self._main_power}, \" f\"with P>{self._upper_limit} W for {self._min_time_high} secs, \"", "POWER notifications \"\"\" import datetime as dt from enum import", "\"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0, } data_msg[\"data\"] = {\"push\":", "app init.\"\"\" self._main_power = self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\") self._notifier =", "self._upper_limit = float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) * 1000.0", "entity, attribute, old, new, kwargs): \"\"\"Sustained Power ALARM logic control.\"\"\"", "noinspection PyUnusedLocal def peak_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Power", "- alarm_start ).total_seconds() / 60.0 data_msg = { \"title\": \"Consumo", "ALARM type_notif = TypeNotif.ALERT_OFF data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start,", "= False _current_peak = 0 def initialize(self): \"\"\"AppDaemon required method", "= [ [(\"Luces ON\", \"/luceson\"), (\"Luces OFF\", \"/lucesoff\")], [ (\"Potencia", "push_data = { \"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\": 1, \"critical\":", "\" \"la sobrecarga eléctrica.\" ), } time_now = ( \"{:%H:%M:%S}\".format(last_trigger)", "is the same power peak event, # waiting min time", "self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif, data) self._last_trigger", "self.notify_alert(type_notif, data) self._last_trigger = now else: self._last_trigger = now elif", "power notifications. Used to centralize push message construction. \"\"\" ALERT_OFF", "OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\", ), ], ] return data_msg def", "ValueError: return # Update peak if new > self._upper_limit and", "data_msg[\"target\"] = target data_msg[\"disable_notification\"] = self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"] =", "= float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\"))", "secs, \" f\"(low={self._lower_limit} W for {self._min_time_low} secs). \" f\"Notify: {self._notifier}.\",", "> self._upper_limit * COEF_CRITICAL_LIMIT ): self.log( \"ENABLE CRITICAL ALARM with", "LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT = \"WARNING\" LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT", "that, notify when back to normal (< lower limit). \"\"\"", "off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, ) type_notif = TypeNotif.ALERT_CRITICAL data =", "App user inputs _main_power: str _main_power_peak: str _notifier: str _target_sensor:", "logic control.\"\"\" try: new = int(float(new)) except ValueError: return #", "ON\", \"/luceson\"), (\"Luces OFF\", \"/lucesoff\")], [ (\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs.", "self._current_peak: self._current_peak = new # noinspection PyUnusedLocal def main_power_change(self, entity,", ") if devices_turning_off: # Notification of devices turned off self.log(", "self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif, data) self._last_trigger =", "duration_min = ( dt.datetime.now() - alarm_start ).total_seconds() / 60.0 data_msg", "\"/luceson\"), (\"Luces OFF\", \"/lucesoff\")], [ (\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\",", "switch.calentador\", ), ( \"AC OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\", ), ],", "and after that, notify when back to normal (< lower", "return data_msg def make_notification_message( self, current_peak, last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0,", "None: # Start power peak event self.log( \"New power peak", "\"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\"", "MODE at {}\".format(now), level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state =", "Home Assistant - current meter PEAK POWER notifications \"\"\" import", "ALARM (now {} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = False", "devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if devices_turning_off: #", "False _critical_alarm_state: bool = False _last_trigger = None _alarm_start =", "self._alarm_start = now self._turn_off_measure_taken = False type_notif = TypeNotif.ALERT_ON data", "f\"TRIGGER ALARM with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state", "Power ALARM logic control.\"\"\" try: new = int(float(new)) except ValueError:", "2 def make_ios_push_data(self, data_msg: dict) -> dict: if self.value ==", "== self.ALERT_OFF data_msg[\"inline_keyboard\"] = [ [(\"Luces ON\", \"/luceson\"), (\"Luces OFF\",", "( now - self._last_trigger ).total_seconds() > self._min_time_high: # TRIGGER ALARM", "# RESET ALARM type_notif = TypeNotif.ALERT_OFF data = type_notif.make_notification_message( self._current_peak,", "= now else: self._last_trigger = now elif (self._last_trigger is not", "inputs _main_power: str _main_power_peak: str _notifier: str _target_sensor: str _alarm_state:", "current_peak, last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, ) -> dict: if", "if self.value == self.ALERT_CRITICAL: return { \"title\": \"¡El automático está", "= self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor = self.config.get(\"chatid_sensor\") #", "self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service(", "= self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"] = [ [(\"Luces ON\", \"/luceson\"),", "W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = True elif new <", "False _last_trigger = None _alarm_start = None _turn_off_measure_taken = False", "PEAK POWER notifications \"\"\" import datetime as dt from enum", "= self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor", "(now - self._last_trigger).total_seconds() > self._min_time_low ): # Normal operation, reset", "Notification of devices turned off self.log( f\"CRITICAL ACTION: Turn off", "if ( now - self._last_trigger ).total_seconds() > self._min_time_low: # RESET", "\"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0, } data_msg[\"data\"] = {\"push\": push_data} return", "attribute, old, new, kwargs): \"\"\"Power Peak ALARM logic control.\"\"\" try:", "old, new, kwargs): \"\"\"Power Peak ALARM logic control.\"\"\" try: new", "{self._notifier}.\", level=LOG_LEVEL, log=LOGGER, ) def notify_alert(self, type_notif: TypeNotif, data: dict):", "< self._lower_limit: if ( now - self._last_trigger ).total_seconds() > self._min_time_low:", "for different kinds of power notifications. Used to centralize push", "\" f\"Alerta iniciada hace {duration_min:.1f} min.\" ), } return data_msg", "log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = False self._critical_alarm_state = False", "\"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0, } data_msg[\"data\"] = {\"push\": push_data}", "new > self._current_peak: self._current_peak = new # Pre-Alarm state, before", "= TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak),", "P={self._main_power}, \" f\"with P>{self._upper_limit} W for {self._min_time_high} secs, \" f\"(low={self._lower_limit}", "TypeNotif, data: dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(),", "> self._min_time_low: # RESET ALARM type_notif = TypeNotif.ALERT_OFF data =", "Pre-Alarm state, before trigger if self._last_trigger is None: # Start", "pow_instant, pow_sustained ) else: duration_min = ( dt.datetime.now() - alarm_start", "new < self._upper_limit ): self.log( \"DISABLE CRITICAL ALARM (now {}", "initialize(self): \"\"\"AppDaemon required method for app init.\"\"\" self._main_power = self.args.get(\"sustained_power\")", "= False _last_trigger = None _alarm_start = None _turn_off_measure_taken =", "W en {time_now}. \" f\"Ahora {pow_instant} W ({pow_sustained} sostenidos)\" ),", "greater than a certain limit), and after that, notify when", "0 def initialize(self): \"\"\"AppDaemon required method for app init.\"\"\" self._main_power", "pow_sustained=0.0, ) -> dict: if self.value == self.ALERT_CRITICAL: return {", "TODO implement _max_peak over _instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\")) * 1000.0", "old, new, kwargs): \"\"\"Sustained Power ALARM logic control.\"\"\" try: new", "\"New power peak event at {} with P={} W\".format(now, new),", "f\"Ahora {pow_instant} W ({pow_sustained} sostenidos)\" ), } data_msg[\"message\"] = data_msg[\"message\"].format(", "True elif new < self._lower_limit: if ( now - self._last_trigger", "= False self._last_trigger = None self._alarm_start = None self._turn_off_measure_taken =", "(< lower limit). \"\"\" # Limit Values _max_peak: float _upper_limit:", "event at {} with P={} W\".format(now, new), level=LOG_LEVEL, log=LOGGER, )", "# Notification of devices turned off self.log( f\"CRITICAL ACTION: Turn", "self._last_trigger ).total_seconds() > self._min_time_high: # TRIGGER ALARM self._alarm_start = now", "time # (this is the same power peak event, #", "self._turn_off_measure_taken and self._critical_alarm_state and new < self._upper_limit ): self.log( \"DISABLE", "dict: data_msg[\"target\"] = target data_msg[\"disable_notification\"] = self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"]", "for reset if new > self._current_peak: self._current_peak = new if", "= { \"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\": 1, \"critical\": 1,", "1000.0 # Listen for Main Power changes: self.listen_state(self.main_power_change, self._main_power) self.log(", "= 1 ALERT_CRITICAL = 2 def make_ios_push_data(self, data_msg: dict) ->", "= type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg)", "data_msg[\"message\"].format( current_peak, time_now, pow_instant, pow_sustained ) else: duration_min = (", "type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\",", ") self._last_trigger = now elif ( now - self._last_trigger ).total_seconds()", "waiting min time to trigger alarm) # pass elif self._alarm_state:", "data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection PyUnusedLocal", "appdaemon.plugins.hass.hassapi as hass LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT = \"WARNING\" LOGGER", "to normal (< lower limit). \"\"\" # Limit Values _max_peak:", "some more time # (this is the same power peak", "noinspection PyUnusedLocal def main_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Sustained", "self.ALERT_OFF data_msg[\"inline_keyboard\"] = [ [(\"Luces ON\", \"/luceson\"), (\"Luces OFF\", \"/lucesoff\")],", "_main_power: str _main_power_peak: str _notifier: str _target_sensor: str _alarm_state: bool", "self._current_peak = new # noinspection PyUnusedLocal def main_power_change(self, entity, attribute,", "power peak event self.log( \"New power peak event at {}", "trigger if self._last_trigger is None: # Start power peak event", "target: int) -> dict: data_msg[\"target\"] = target data_msg[\"disable_notification\"] = self.value", "AppDaemon App for Home Assistant - current meter PEAK POWER", "\"volume\": 1.0, \"thread-id\": \"power-peak-group\", } elif self.value == self.ALERT_ON: push_data", "data_msg[\"disable_notification\"] = self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"] = [ [(\"Luces ON\",", "{duration_min:.1f} min.\" ), } return data_msg # noinspection PyClassHasNoInit class", "False type_notif = TypeNotif.ALERT_ON data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start,", "off self.log( f\"CRITICAL ACTION: Turn off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, )", "\"AC OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\", ), ], ] return data_msg", "\"Calentador OFF\", \"/service_call switch/turn_off switch.calentador\", ), ( \"AC OFF\", \"/service_call", "TypeNotif(IntEnum): \"\"\" Handler for different kinds of power notifications. Used", "\"message\": ( f\"Apagando {devices_off} para intentar evitar \" \"la sobrecarga", "entity_id=BIG_CONSUMER_2 ) if devices_turning_off: # Notification of devices turned off", "self._last_trigger = now elif (self._last_trigger is not None) and (", "_notifier: str _target_sensor: str _alarm_state: bool = False _critical_alarm_state: bool", "1.1 # 10% over limit MIN_TIME_TURN_OFF_AC = 60 # secs", "float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high =", "str _main_power_peak: str _notifier: str _target_sensor: str _alarm_state: bool =", "\"\"\"Sustained Power ALARM logic control.\"\"\" try: new = int(float(new)) except", "\"thread-id\": \"power-peak-group\", \"badge\": 1, \"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK, } else:", "= self.config.get(\"chatid_sensor\") # Power limits self._upper_limit = float(self.args.get(\"max_power_kw\")) * 1000.0", "{self._min_time_low} secs). \" f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER, ) def notify_alert(self,", "60 # secs # Big power consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\"", "- self._last_trigger ).total_seconds() > self._min_time_high: # TRIGGER ALARM self._alarm_start =", "and ( (now - self._last_trigger).total_seconds() > self._min_time_low ): # Normal", "a AppDaemon App for Home Assistant - current meter PEAK", "# wait some more time # (this is the same", "> self._current_peak: self._current_peak = new if ( not self._turn_off_measure_taken and", "control.\"\"\" try: new = int(float(new)) except ValueError: return # Update", "log=LOGGER, ) self._critical_alarm_state = False elif ( not self._turn_off_measure_taken and", "\"on\": devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) == \"on\":", "changes: self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier Initialized. P={self._main_power}, \" f\"with P>{self._upper_limit}", "0, } data_msg[\"data\"] = {\"push\": push_data} return data_msg def make_telegram_push_data(self,", "\"/\") self._target_sensor = self.config.get(\"chatid_sensor\") # Power limits self._upper_limit = float(self.args.get(\"max_power_kw\"))", "# Big power consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire", "same power peak event, # waiting min time to trigger", "def make_ios_push_data(self, data_msg: dict) -> dict: if self.value == self.ALERT_CRITICAL:", "f\"Potencia normal desde {time_now}, \" f\"Pico de potencia: {current_peak} W.", "self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor =", "AC + heater are ON self._turn_off_measure_taken = True self._critical_alarm_state =", "AC if AC + heater are ON self._turn_off_measure_taken = True", "self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor = self.config.get(\"chatid_sensor\") # Power limits self._upper_limit =", "type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log( f\"TRIGGER ALARM", "type_notif: TypeNotif, data: dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data(", "_IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\": 1.0, \"thread-id\": \"power-peak-group\", } elif self.value", "try: new = int(float(new)) except ValueError: return now = dt.datetime.now()", "= new if ( not self._turn_off_measure_taken and new > self._upper_limit", "int) -> dict: data_msg[\"target\"] = target data_msg[\"disable_notification\"] = self.value ==", "lower limit). \"\"\" # Limit Values _max_peak: float _upper_limit: float", "self.ALERT_ON: push_data = { \"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\": 1,", "self._alarm_start, ) self.log( \"RESET ALARM MODE at {}\".format(now), level=LOG_LEVEL, log=LOGGER,", "self._current_peak: self._current_peak = new # Pre-Alarm state, before trigger if", "is not None) and ( (now - self._last_trigger).total_seconds() > self._min_time_low", "data_msg[\"message\"] = data_msg[\"message\"].format( current_peak, time_now, pow_instant, pow_sustained ) else: duration_min", "peak event, # waiting min time to trigger alarm) #", "new < self._lower_limit: if ( now - self._last_trigger ).total_seconds() >", "\"/enerpitiles\"), ], [ ( \"Calentador OFF\", \"/service_call switch/turn_off switch.calentador\", ),", "PeakNotifier(hass.Hass): \"\"\" App to notify power peaks (when they are", "min_time_lower self.log( \"RESET LAST TRIGGER (was in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER,", "if self.value == self.ALERT_CRITICAL: push_data = { \"category\": \"powerpeak\", \"badge\":", "self.ALERT_CRITICAL: push_data = { \"category\": \"powerpeak\", \"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK,", "\"???\" ) if self.value == self.ALERT_ON: data_msg = { \"title\":", "= new # noinspection PyUnusedLocal def main_power_change(self, entity, attribute, old,", "\"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK, } else: push_data = { \"category\":", "f\"with P>{self._upper_limit} W for {self._min_time_high} secs, \" f\"(low={self._lower_limit} W for", "= { \"category\": \"confirm\", \"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0,", ") self.notify_alert(type_notif, data) self._alarm_state = True self._critical_alarm_state = False self._last_trigger", "not None) and ( (now - self._last_trigger).total_seconds() > self._min_time_low ):", "and new > self._upper_limit * COEF_CRITICAL_LIMIT ): self.log( \"ENABLE CRITICAL", "Power changes: self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier Initialized. P={self._main_power}, \" f\"with", "> self._upper_limit): if new > self._current_peak: self._current_peak = new #", "power peak event, # waiting min time to trigger alarm)", "(this is the same power peak event, # waiting min", "ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier,", "automático está a punto de saltar!\", \"message\": ( f\"Apagando {devices_off}", "data_msg = { \"title\": \"Consumo eléctrico: Normal\", \"message\": ( f\"Potencia", "evitar \" \"la sobrecarga eléctrica.\" ), } time_now = (", "self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low =", "[ ( \"Calentador OFF\", \"/service_call switch/turn_off switch.calentador\", ), ( \"AC", "more in min_time_lower self.log( \"RESET LAST TRIGGER (was in {})\".format(self._last_trigger),", "time_now, pow_instant, pow_sustained ) else: duration_min = ( dt.datetime.now() -", "before trigger if self._last_trigger is None: # Start power peak", "self._critical_alarm_state = False elif ( not self._turn_off_measure_taken and self._critical_alarm_state and", "): # Turn off AC if AC + heater are", "= data_msg[\"message\"].format( current_peak, time_now, pow_instant, pow_sustained ) else: duration_min =", "no more in min_time_lower self.log( \"RESET LAST TRIGGER (was in", "if new > self._current_peak: self._current_peak = new # Pre-Alarm state,", "IntEnum import appdaemon.plugins.hass.hassapi as hass LOG_LEVEL = \"INFO\" LOG_LEVEL_ALERT =", "tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg)", "and (new > self._upper_limit): if new > self._current_peak: self._current_peak =", "datetime as dt from enum import IntEnum import appdaemon.plugins.hass.hassapi as", "# waiting min time to trigger alarm) # pass elif", "( dt.datetime.now() - alarm_start ).total_seconds() / 60.0 data_msg = {", "self._current_peak: self._current_peak = new if ( not self._turn_off_measure_taken and new", "* 1000.0 self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\")) # TODO", ") else: duration_min = ( dt.datetime.now() - alarm_start ).total_seconds() /", "return { \"title\": \"¡El automático está a punto de saltar!\",", "{})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = None self._current_peak = 0", "1.0, \"thread-id\": \"power-peak-group\", } elif self.value == self.ALERT_ON: push_data =", "= new # Pre-Alarm state, before trigger if self._last_trigger is", "elif ( now - self._last_trigger ).total_seconds() > self._min_time_high: # TRIGGER", ").total_seconds() > self._min_time_low: # RESET ALARM type_notif = TypeNotif.ALERT_OFF data", "return data_msg # noinspection PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\" App to", "float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\")) #", "\"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\" Handler for different", "W. \" f\"Alerta iniciada hace {duration_min:.1f} min.\" ), } return", "- current meter PEAK POWER notifications \"\"\" import datetime as", "self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier Initialized. P={self._main_power}, \" f\"with P>{self._upper_limit} W", "MIN_TIME_TURN_OFF_AC = 60 # secs # Big power consumers BIG_CONSUMER_1_CLIMATE", "BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\" Handler", "level=LOG_LEVEL, log=LOGGER, ) def notify_alert(self, type_notif: TypeNotif, data: dict): ios_alarm_msg", "(new > self._upper_limit): if new > self._current_peak: self._current_peak = new", "= 1.1 # 10% over limit MIN_TIME_TURN_OFF_AC = 60 #", "eléctrico!\", \"message\": ( f\"Peak: {current_peak} W en {time_now}. \" f\"Ahora", "data_msg # noinspection PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\" App to notify", "and self._critical_alarm_state and new < self._upper_limit ): self.log( \"DISABLE CRITICAL", "of power notifications. Used to centralize push message construction. \"\"\"", "= int(float(new)) except ValueError: return now = dt.datetime.now() if not", "different kinds of power notifications. Used to centralize push message", "self._turn_off_measure_taken and self._critical_alarm_state and ( (now - self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC", ") self.log( \"RESET ALARM MODE at {}\".format(now), level=LOG_LEVEL, log=LOGGER, )", "not self._alarm_state and (new > self._upper_limit): if new > self._current_peak:", "(\"Luces OFF\", \"/lucesoff\")], [ (\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"),", "new > self._upper_limit and new > self._current_peak: self._current_peak = new", "\"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\": 1.0, \"thread-id\": \"power-peak-group\",", "bool = False _critical_alarm_state: bool = False _last_trigger = None", "\"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\")", "{current_peak} W en {time_now}. \" f\"Ahora {pow_instant} W ({pow_sustained} sostenidos)\"", "else \"???\" ) if self.value == self.ALERT_ON: data_msg = {", "over limit MIN_TIME_TURN_OFF_AC = 60 # secs # Big power", "# 10% over limit MIN_TIME_TURN_OFF_AC = 60 # secs #", "data) self._alarm_state = True self._critical_alarm_state = False self._last_trigger = now", "Values _max_peak: float _upper_limit: float _lower_limit: float _min_time_high: int _min_time_low:", "secs). \" f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER, ) def notify_alert(self, type_notif:", "limit), and after that, notify when back to normal (<", "(now - self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC ) ): # Turn off", "Listen for Main Power changes: self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier Initialized.", "self._upper_limit * COEF_CRITICAL_LIMIT ): self.log( \"ENABLE CRITICAL ALARM with {}", "\"INFO\" LOG_LEVEL_ALERT = \"WARNING\" LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT = 1.1", "# TODO implement _max_peak over _instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\")) *", "False self._last_trigger = None self._alarm_start = None self._turn_off_measure_taken = False", "= dt.datetime.now() if not self._alarm_state and (new > self._upper_limit): if", "\"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if devices_turning_off: # Notification of devices turned", "PyUnusedLocal def main_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Sustained Power", "{} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = True elif new", "devices_turning_off: # Notification of devices turned off self.log( f\"CRITICAL ACTION:", "new = int(float(new)) except ValueError: return now = dt.datetime.now() if", "# Alarm state, waiting for reset if new > self._current_peak:", "(\"Grafs. enerPI\", \"/enerpitiles\"), ], [ ( \"Calentador OFF\", \"/service_call switch/turn_off", "= \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\",", "P={} W\".format(now, new), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = now elif", "\"category\": \"powerpeak\", \"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\": 1.0,", "data: dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy()) tlg_alarm_msg = type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)),", "alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, ) -> dict: if self.value ==", "1000.0 self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\")) # TODO implement", "self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC ) ): # Turn off AC if", "[ [(\"Luces ON\", \"/luceson\"), (\"Luces OFF\", \"/lucesoff\")], [ (\"Potencia eléctrica\",", "1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low", "switch/turn_off switch.ac_dry_contact\", ), ], ] return data_msg def make_notification_message( self,", "kwargs): \"\"\"Power Peak ALARM logic control.\"\"\" try: new = int(float(new))", "ALARM MODE at {}\".format(now), level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state", "f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER, ) def notify_alert(self, type_notif: TypeNotif, data:", "current meter PEAK POWER notifications \"\"\" import datetime as dt", "> self._upper_limit and new > self._current_peak: self._current_peak = new #", "else: duration_min = ( dt.datetime.now() - alarm_start ).total_seconds() / 60.0", "\" f\"with P>{self._upper_limit} W for {self._min_time_high} secs, \" f\"(low={self._lower_limit} W", "except ValueError: return # Update peak if new > self._upper_limit", "> MIN_TIME_TURN_OFF_AC ) ): # Turn off AC if AC", "now self._turn_off_measure_taken = False type_notif = TypeNotif.ALERT_ON data = type_notif.make_notification_message(", "ALARM self._alarm_start = now self._turn_off_measure_taken = False type_notif = TypeNotif.ALERT_ON", "RESET ALARM type_notif = TypeNotif.ALERT_OFF data = type_notif.make_notification_message( self._current_peak, self._last_trigger,", "self.log( \"DISABLE CRITICAL ALARM (now {} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, )", "ValueError: return now = dt.datetime.now() if not self._alarm_state and (new", "log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = True self._critical_alarm_state = False", "switch/turn_off switch.calentador\", ), ( \"AC OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\", ),", "new if ( not self._turn_off_measure_taken and new > self._upper_limit *", "self._alarm_state: # Alarm state, waiting for reset if new >", "self._main_power) self.log( f\"PeakNotifier Initialized. P={self._main_power}, \" f\"with P>{self._upper_limit} W for", "bool = False _last_trigger = None _alarm_start = None _turn_off_measure_taken", "int(self.args.get(\"min_time_low\")) # TODO implement _max_peak over _instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\"))", "= 2 def make_ios_push_data(self, data_msg: dict) -> dict: if self.value", "data_msg: dict) -> dict: if self.value == self.ALERT_CRITICAL: push_data =", "of devices turned off self.log( f\"CRITICAL ACTION: Turn off '{devices_turning_off}'\",", "[(\"Luces ON\", \"/luceson\"), (\"Luces OFF\", \"/lucesoff\")], [ (\"Potencia eléctrica\", \"/enerpi\"),", "= float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) * 1000.0 self._min_time_high", "# secs # Big power consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL", "target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection PyUnusedLocal def", "self._current_peak = new # Pre-Alarm state, before trigger if self._last_trigger", "# else: # wait some more time # (this is", "self._min_time_low ): # Normal operation, reset last trigger if no", "_min_time_low: int # App user inputs _main_power: str _main_power_peak: str", "\" f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER, ) def notify_alert(self, type_notif: TypeNotif,", "= type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log( f\"TRIGGER", "data_msg: dict, target: int) -> dict: data_msg[\"target\"] = target data_msg[\"disable_notification\"]", "self._critical_alarm_state = True elif new < self._lower_limit: if ( now", "level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = False self._critical_alarm_state =", "{ \"title\": \"¡El automático está a punto de saltar!\", \"message\":", "peak_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Power Peak ALARM logic", "* COEF_CRITICAL_LIMIT ): self.log( \"ENABLE CRITICAL ALARM with {} W\".format(new),", "{ \"category\": \"confirm\", \"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0, }", "not None else \"???\" ) if self.value == self.ALERT_ON: data_msg", "self._critical_alarm_state = False self._last_trigger = now # else: # wait", "= \"WARNING\" LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT = 1.1 # 10%", "<filename>config/appdaemon/apps/power_alarm.py # -*- coding: utf-8 -*- \"\"\" Automation task as", "data) self._alarm_state = False self._critical_alarm_state = False self._last_trigger = None", "if self._last_trigger is None: # Start power peak event self.log(", "new > self._upper_limit * COEF_CRITICAL_LIMIT ): self.log( \"ENABLE CRITICAL ALARM", "now else: self._last_trigger = now elif (self._last_trigger is not None)", "] return data_msg def make_notification_message( self, current_peak, last_trigger, alarm_start, devices_off=\"\",", "0 ALERT_ON = 1 ALERT_CRITICAL = 2 def make_ios_push_data(self, data_msg:", "pow_instant=0.0, pow_sustained=0.0, ) -> dict: if self.value == self.ALERT_CRITICAL: return", "), ( \"AC OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\", ), ], ]", "None self._alarm_start = None self._turn_off_measure_taken = False self._current_peak = 0", "CRITICAL ALARM (now {} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state =", "type_notif = TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off,", "now elif (self._last_trigger is not None) and ( (now -", "-> dict: if self.value == self.ALERT_CRITICAL: return { \"title\": \"¡El", "{} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = False elif (", "ACTION: Turn off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, ) type_notif = TypeNotif.ALERT_CRITICAL", "W ({pow_sustained} sostenidos)\" ), } data_msg[\"message\"] = data_msg[\"message\"].format( current_peak, time_now,", "( f\"Potencia normal desde {time_now}, \" f\"Pico de potencia: {current_peak}", "= { \"title\": \"Alto consumo eléctrico!\", \"message\": ( f\"Peak: {current_peak}", "\"message\": ( f\"Peak: {current_peak} W en {time_now}. \" f\"Ahora {pow_instant}", "= ( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger is not None else \"???\"", "int(float(new)) except ValueError: return # Update peak if new >", "COEF_CRITICAL_LIMIT ): self.log( \"ENABLE CRITICAL ALARM with {} W\".format(new), level=LOG_LEVEL_ALERT,", "self.log( \"ENABLE CRITICAL ALARM with {} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, )", "= \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\" Handler for different kinds of", "), } time_now = ( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger is not", "after that, notify when back to normal (< lower limit).", "self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 )", "= float(self.args.get(\"max_power_peak_kw\")) * 1000.0 # Listen for Main Power changes:", "{time_now}. \" f\"Ahora {pow_instant} W ({pow_sustained} sostenidos)\" ), } data_msg[\"message\"]", "normal (< lower limit). \"\"\" # Limit Values _max_peak: float", "a punto de saltar!\", \"message\": ( f\"Apagando {devices_off} para intentar", "( now - self._last_trigger ).total_seconds() > self._min_time_low: # RESET ALARM", "{ \"category\": \"powerpeak\", \"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\":", "False devices_turning_off = \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off =", "state, before trigger if self._last_trigger is None: # Start power", "], [ ( \"Calentador OFF\", \"/service_call switch/turn_off switch.calentador\", ), (", "data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log(", "if no more in min_time_lower self.log( \"RESET LAST TRIGGER (was", "= ( dt.datetime.now() - alarm_start ).total_seconds() / 60.0 data_msg =", "{ \"title\": \"Alto consumo eléctrico!\", \"message\": ( f\"Peak: {current_peak} W", "False self._current_peak = 0 elif ( not self._turn_off_measure_taken and self._critical_alarm_state", "waiting for reset if new > self._current_peak: self._current_peak = new", ").total_seconds() > self._min_time_high: # TRIGGER ALARM self._alarm_start = now self._turn_off_measure_taken", "**ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection PyUnusedLocal def peak_power_change(self, entity, attribute,", "de potencia: {current_peak} W. \" f\"Alerta iniciada hace {duration_min:.1f} min.\"", "elif new < self._lower_limit: if ( now - self._last_trigger ).total_seconds()", "{current_peak} W. \" f\"Alerta iniciada hace {duration_min:.1f} min.\" ), }", "0 elif ( not self._turn_off_measure_taken and self._critical_alarm_state and new <", "state, waiting for reset if new > self._current_peak: self._current_peak =", "( \"Calentador OFF\", \"/service_call switch/turn_off switch.calentador\", ), ( \"AC OFF\",", "dict, target: int) -> dict: data_msg[\"target\"] = target data_msg[\"disable_notification\"] =", "CRITICAL ALARM with {} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state =", "self._critical_alarm_state = False devices_turning_off = \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\":", "alarm_start ).total_seconds() / 60.0 data_msg = { \"title\": \"Consumo eléctrico:", "None else \"???\" ) if self.value == self.ALERT_ON: data_msg =", "True self._critical_alarm_state = False self._last_trigger = now # else: #", "\"confirm\", \"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0, } data_msg[\"data\"] =", ") type_notif = TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start,", "{ \"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\": 1, \"critical\": 1, \"sound\":", "), ], ] return data_msg def make_notification_message( self, current_peak, last_trigger,", "to notify power peaks (when they are greater than a", "and new < self._upper_limit ): self.log( \"DISABLE CRITICAL ALARM (now", "type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection", "App to notify power peaks (when they are greater than", "} data_msg[\"message\"] = data_msg[\"message\"].format( current_peak, time_now, pow_instant, pow_sustained ) else:", "dict: if self.value == self.ALERT_CRITICAL: return { \"title\": \"¡El automático", "= False type_notif = TypeNotif.ALERT_ON data = type_notif.make_notification_message( self._current_peak, self._last_trigger,", "data_msg[\"inline_keyboard\"] = [ [(\"Luces ON\", \"/luceson\"), (\"Luces OFF\", \"/lucesoff\")], [", "self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2)", "= True elif new < self._lower_limit: if ( now -", "enerPI\", \"/enerpitiles\"), ], [ ( \"Calentador OFF\", \"/service_call switch/turn_off switch.calentador\",", "{}\".format(now), level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = False self._critical_alarm_state", "== \"on\": devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) ==", "a certain limit), and after that, notify when back to", "int(float(new)) except ValueError: return now = dt.datetime.now() if not self._alarm_state", "ALERT_ON = 1 ALERT_CRITICAL = 2 def make_ios_push_data(self, data_msg: dict)", "{devices_off} para intentar evitar \" \"la sobrecarga eléctrica.\" ), }", "( \"AC OFF\", \"/service_call switch/turn_off switch.ac_dry_contact\", ), ], ] return", "BIG_CONSUMER_1_LABEL = \"aire acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\"", "\"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum): \"\"\" Handler for different kinds of power", "): self.log( \"DISABLE CRITICAL ALARM (now {} W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER,", "f\"Apagando {devices_off} para intentar evitar \" \"la sobrecarga eléctrica.\" ),", "new = int(float(new)) except ValueError: return # Update peak if", "== \"on\": devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if", "off AC if AC + heater are ON self._turn_off_measure_taken =", "devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, ) -> dict: if self.value == self.ALERT_CRITICAL:", "> self._current_peak: self._current_peak = new # noinspection PyUnusedLocal def main_power_change(self,", "= type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif,", "- self._last_trigger).total_seconds() > self._min_time_low ): # Normal operation, reset last", "( not self._turn_off_measure_taken and self._critical_alarm_state and new < self._upper_limit ):", "sobrecarga eléctrica.\" ), } time_now = ( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger", ").total_seconds() / 60.0 data_msg = { \"title\": \"Consumo eléctrico: Normal\",", "# Pre-Alarm state, before trigger if self._last_trigger is None: #", "_alarm_state: bool = False _critical_alarm_state: bool = False _last_trigger =", "new > self._current_peak: self._current_peak = new if ( not self._turn_off_measure_taken", "level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = now elif ( now -", "last trigger if no more in min_time_lower self.log( \"RESET LAST", "\"category\": \"confirm\", \"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\": 0, } data_msg[\"data\"]", ") ): # Turn off AC if AC + heater", "10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\": 1.0, \"thread-id\": \"power-peak-group\", }", "not self._turn_off_measure_taken and self._critical_alarm_state and ( (now - self._alarm_start).total_seconds() >", "consumo eléctrico!\", \"message\": ( f\"Peak: {current_peak} W en {time_now}. \"", "ALERT_OFF = 0 ALERT_ON = 1 ALERT_CRITICAL = 2 def", "# App user inputs _main_power: str _main_power_peak: str _notifier: str", "Used to centralize push message construction. \"\"\" ALERT_OFF = 0", "(when they are greater than a certain limit), and after", "limits self._upper_limit = float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\")) *", "at {}\".format(now), level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = False", "current_peak, time_now, pow_instant, pow_sustained ) else: duration_min = ( dt.datetime.now()", ") self.notify_alert(type_notif, data) self._alarm_state = False self._critical_alarm_state = False self._last_trigger", ") self.notify_alert(type_notif, data) self._last_trigger = now else: self._last_trigger = now", "data) self._last_trigger = now else: self._last_trigger = now elif (self._last_trigger", "dict) -> dict: if self.value == self.ALERT_CRITICAL: push_data = {", "self.value == self.ALERT_ON: push_data = { \"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\",", "\"critical\": 1, \"volume\": 1.0, \"thread-id\": \"power-peak-group\", } elif self.value ==", "OFF\", \"/service_call switch/turn_off switch.calentador\", ), ( \"AC OFF\", \"/service_call switch/turn_off", "target data_msg[\"disable_notification\"] = self.value == self.ALERT_OFF data_msg[\"inline_keyboard\"] = [ [(\"Luces", "( not self._turn_off_measure_taken and new > self._upper_limit * COEF_CRITICAL_LIMIT ):", "now - self._last_trigger ).total_seconds() > self._min_time_high: # TRIGGER ALARM self._alarm_start", "entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\",", "self._current_peak = 0 elif ( not self._turn_off_measure_taken and self._critical_alarm_state and", "f\"PeakNotifier Initialized. P={self._main_power}, \" f\"with P>{self._upper_limit} W for {self._min_time_high} secs,", "self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor = self.config.get(\"chatid_sensor\") # Power limits", "class TypeNotif(IntEnum): \"\"\" Handler for different kinds of power notifications.", "int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\")) # TODO implement _max_peak over _instant_power", "self._critical_alarm_state and ( (now - self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC ) ):", "if ( not self._turn_off_measure_taken and new > self._upper_limit * COEF_CRITICAL_LIMIT", "and ( (now - self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC ) ): #", "from enum import IntEnum import appdaemon.plugins.hass.hassapi as hass LOG_LEVEL =", "False self._last_trigger = now # else: # wait some more", "time_now = ( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger is not None else", "self._alarm_state = False self._critical_alarm_state = False self._last_trigger = None self._alarm_start", "elif ( not self._turn_off_measure_taken and self._critical_alarm_state and ( (now -", "data_msg = { \"title\": \"Alto consumo eléctrico!\", \"message\": ( f\"Peak:", "self._turn_off_measure_taken and new > self._upper_limit * COEF_CRITICAL_LIMIT ): self.log( \"ENABLE", "], ] return data_msg def make_notification_message( self, current_peak, last_trigger, alarm_start,", "Peak ALARM logic control.\"\"\" try: new = int(float(new)) except ValueError:", "-> dict: if self.value == self.ALERT_CRITICAL: push_data = { \"category\":", "float(self.args.get(\"max_power_peak_kw\")) * 1000.0 # Listen for Main Power changes: self.listen_state(self.main_power_change,", "kwargs): \"\"\"Sustained Power ALARM logic control.\"\"\" try: new = int(float(new))", "peak if new > self._upper_limit and new > self._current_peak: self._current_peak", "dt.datetime.now() if not self._alarm_state and (new > self._upper_limit): if new", "= \"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class TypeNotif(IntEnum):", "_max_peak over _instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\")) * 1000.0 # Listen", "back to normal (< lower limit). \"\"\" # Limit Values", "alarm) # pass elif self._alarm_state: # Alarm state, waiting for", "= type_notif.make_telegram_push_data( data.copy(), target=int(self.get_state(self._target_sensor)), ) self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) #", "str _notifier: str _target_sensor: str _alarm_state: bool = False _critical_alarm_state:", "elif self.value == self.ALERT_ON: push_data = { \"category\": \"powerpeak\", \"thread-id\":", "with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state = True", "eléctrica.\" ), } time_now = ( \"{:%H:%M:%S}\".format(last_trigger) if last_trigger is", "== self.ALERT_ON: push_data = { \"category\": \"powerpeak\", \"thread-id\": \"power-peak-group\", \"badge\":", "= 0 def initialize(self): \"\"\"AppDaemon required method for app init.\"\"\"", "1 ALERT_CRITICAL = 2 def make_ios_push_data(self, data_msg: dict) -> dict:", "and self._critical_alarm_state and ( (now - self._alarm_start).total_seconds() > MIN_TIME_TURN_OFF_AC )", ") self._critical_alarm_state = True elif new < self._lower_limit: if (", "self._upper_limit ): self.log( \"DISABLE CRITICAL ALARM (now {} W)\".format(new), level=LOG_LEVEL_ALERT,", "def make_telegram_push_data(self, data_msg: dict, target: int) -> dict: data_msg[\"target\"] =", "True self._critical_alarm_state = False devices_turning_off = \"\" if self.get_state(BIG_CONSUMER_1_CLIMATE) ==", "new), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = now elif ( now", "wait some more time # (this is the same power", "# Turn off AC if AC + heater are ON", "event self.log( \"New power peak event at {} with P={}", "\"aire acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK =", "= 0 ALERT_ON = 1 ALERT_CRITICAL = 2 def make_ios_push_data(self,", "LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT = 1.1 # 10% over limit", "# Update peak if new > self._upper_limit and new >", "\"title\": \"¡El automático está a punto de saltar!\", \"message\": (", "= None self._alarm_start = None self._turn_off_measure_taken = False self._current_peak =", "( not self._turn_off_measure_taken and self._critical_alarm_state and ( (now - self._alarm_start).total_seconds()", "de saltar!\", \"message\": ( f\"Apagando {devices_off} para intentar evitar \"", "\"\"\" App to notify power peaks (when they are greater", "= BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off =", "if new > self._upper_limit and new > self._current_peak: self._current_peak =", "PyUnusedLocal def peak_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Power Peak", "self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log( f\"TRIGGER ALARM with msg={data}\", level=LOG_LEVEL_ALERT,", "self._upper_limit): if new > self._current_peak: self._current_peak = new # Pre-Alarm", "TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new,", "self._last_trigger = now # else: # wait some more time", "_max_peak: float _upper_limit: float _lower_limit: float _min_time_high: int _min_time_low: int", "str _alarm_state: bool = False _critical_alarm_state: bool = False _last_trigger", "f\"CRITICAL ACTION: Turn off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, ) type_notif =", "(\"Potencia eléctrica\", \"/enerpi\"), (\"Grafs. enerPI\", \"/enerpitiles\"), ], [ ( \"Calentador", "over _instant_power self._max_peak = float(self.args.get(\"max_power_peak_kw\")) * 1000.0 # Listen for", "secs # Big power consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL =", "new > self._current_peak: self._current_peak = new # noinspection PyUnusedLocal def", "return data_msg def make_telegram_push_data(self, data_msg: dict, target: int) -> dict:", "1, \"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK, } else: push_data = {", "self._min_time_high = int(self.args.get(\"min_time_high\")) self._min_time_low = int(self.args.get(\"min_time_low\")) # TODO implement _max_peak", "# noinspection PyUnusedLocal def peak_power_change(self, entity, attribute, old, new, kwargs):", "BIG_CONSUMER_2 = \"switch.calentador\" BIG_CONSUMER_2_LABEL = \"calentador\" _IOS_SOUND_POWER_PEAK = \"US-EN-Morgan-Freeman-Vacate-The-Premises.wav\" class", "\"{:%H:%M:%S}\".format(last_trigger) if last_trigger is not None else \"???\" ) if", "TypeNotif.ALERT_OFF data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, ) self.log( \"RESET", "MIN_TIME_TURN_OFF_AC ) ): # Turn off AC if AC +", "_current_peak = 0 def initialize(self): \"\"\"AppDaemon required method for app", "operation, reset last trigger if no more in min_time_lower self.log(", ") def notify_alert(self, type_notif: TypeNotif, data: dict): ios_alarm_msg = type_notif.make_ios_push_data(data.copy())", "\"\"\"Power Peak ALARM logic control.\"\"\" try: new = int(float(new)) except", "-*- \"\"\" Automation task as a AppDaemon App for Home", "= BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if devices_turning_off: # Notification", "hace {duration_min:.1f} min.\" ), } return data_msg # noinspection PyClassHasNoInit", "self._last_trigger = now elif ( now - self._last_trigger ).total_seconds() >", "limit MIN_TIME_TURN_OFF_AC = 60 # secs # Big power consumers", "\"on\": devices_turning_off = BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if devices_turning_off:", "== self.ALERT_CRITICAL: return { \"title\": \"¡El automático está a punto", "f\"(low={self._lower_limit} W for {self._min_time_low} secs). \" f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER,", "time to trigger alarm) # pass elif self._alarm_state: # Alarm", "log=LOGGER, ) self._last_trigger = now elif ( now - self._last_trigger", "self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection PyUnusedLocal def peak_power_change(self, entity, attribute, old,", "ALARM with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, ) self.notify_alert(type_notif, data) self._alarm_state =", "and new > self._current_peak: self._current_peak = new # noinspection PyUnusedLocal", "dt.datetime.now() - alarm_start ).total_seconds() / 60.0 data_msg = { \"title\":", "user inputs _main_power: str _main_power_peak: str _notifier: str _target_sensor: str", "W)\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state = False elif ( not", "Alarm state, waiting for reset if new > self._current_peak: self._current_peak", "\"badge\": 1, \"critical\": 1, \"sound\": _IOS_SOUND_POWER_PEAK, } else: push_data =", "\"\"\" Handler for different kinds of power notifications. Used to", "\"\"\"AppDaemon required method for app init.\"\"\" self._main_power = self.args.get(\"sustained_power\") self._main_power_peak", ") if self.value == self.ALERT_ON: data_msg = { \"title\": \"Alto", "type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, devices_off=devices_turning_off, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.notify_alert(type_notif, data)", "BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire acondicionado\" BIG_CONSUMER_2 = \"switch.calentador\"", "- self._last_trigger ).total_seconds() > self._min_time_low: # RESET ALARM type_notif =", "Turn off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, ) type_notif = TypeNotif.ALERT_CRITICAL data", "return now = dt.datetime.now() if not self._alarm_state and (new >", "} else: push_data = { \"category\": \"confirm\", \"thread-id\": \"power-peak-group\", \"sound\":", "when back to normal (< lower limit). \"\"\" # Limit", "iniciada hace {duration_min:.1f} min.\" ), } return data_msg # noinspection", "> self._min_time_high: # TRIGGER ALARM self._alarm_start = now self._turn_off_measure_taken =", "# Listen for Main Power changes: self.listen_state(self.main_power_change, self._main_power) self.log( f\"PeakNotifier", "self.log( f\"CRITICAL ACTION: Turn off '{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, ) type_notif", "Normal\", \"message\": ( f\"Potencia normal desde {time_now}, \" f\"Pico de", "_upper_limit: float _lower_limit: float _min_time_high: int _min_time_low: int # App", "log=LOGGER, ) def notify_alert(self, type_notif: TypeNotif, data: dict): ios_alarm_msg =", "desde {time_now}, \" f\"Pico de potencia: {current_peak} W. \" f\"Alerta", "Power limits self._upper_limit = float(self.args.get(\"max_power_kw\")) * 1000.0 self._lower_limit = float(self.args.get(\"max_power_kw_reset\"))", "float _lower_limit: float _min_time_high: int _min_time_low: int # App user", "LAST TRIGGER (was in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger =", "( (now - self._last_trigger).total_seconds() > self._min_time_low ): # Normal operation,", "\"\"\" Automation task as a AppDaemon App for Home Assistant", "{self._min_time_high} secs, \" f\"(low={self._lower_limit} W for {self._min_time_low} secs). \" f\"Notify:", "peak event self.log( \"New power peak event at {} with", "push_data = { \"category\": \"confirm\", \"thread-id\": \"power-peak-group\", \"sound\": _IOS_SOUND_POWER_PEAK, \"badge\":", "= False self._last_trigger = now # else: # wait some", "make_ios_push_data(self, data_msg: dict) -> dict: if self.value == self.ALERT_CRITICAL: push_data", "min.\" ), } return data_msg # noinspection PyClassHasNoInit class PeakNotifier(hass.Hass):", "type_notif = TypeNotif.ALERT_OFF data = type_notif.make_notification_message( self._current_peak, self._last_trigger, self._alarm_start, )", "self._min_time_low: # RESET ALARM type_notif = TypeNotif.ALERT_OFF data = type_notif.make_notification_message(", "power consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire acondicionado\" BIG_CONSUMER_2", "\"¡El automático está a punto de saltar!\", \"message\": ( f\"Apagando", "# noinspection PyUnusedLocal def main_power_change(self, entity, attribute, old, new, kwargs):", "), } data_msg[\"message\"] = data_msg[\"message\"].format( current_peak, time_now, pow_instant, pow_sustained )", "def peak_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Power Peak ALARM", "= now self._turn_off_measure_taken = False type_notif = TypeNotif.ALERT_ON data =", "self.call_service(self._notifier, **ios_alarm_msg) self.call_service(\"telegram_bot/send_message\", **tlg_alarm_msg) # noinspection PyUnusedLocal def peak_power_change(self, entity,", "self.log( f\"PeakNotifier Initialized. P={self._main_power}, \" f\"with P>{self._upper_limit} W for {self._min_time_high}", "self._lower_limit: if ( now - self._last_trigger ).total_seconds() > self._min_time_low: #", "{time_now}, \" f\"Pico de potencia: {current_peak} W. \" f\"Alerta iniciada", "Normal operation, reset last trigger if no more in min_time_lower", "LOG_LEVEL_ALERT = \"WARNING\" LOGGER = \"special_event_log\" COEF_CRITICAL_LIMIT = 1.1 #", "self.notify_alert(type_notif, data) self._alarm_state = False self._critical_alarm_state = False self._last_trigger =", "else: self._last_trigger = now elif (self._last_trigger is not None) and", "if not self._alarm_state and (new > self._upper_limit): if new >", "not self._turn_off_measure_taken and self._critical_alarm_state and new < self._upper_limit ): self.log(", "message construction. \"\"\" ALERT_OFF = 0 ALERT_ON = 1 ALERT_CRITICAL", "meter PEAK POWER notifications \"\"\" import datetime as dt from", "_lower_limit: float _min_time_high: int _min_time_low: int # App user inputs", "= { \"title\": \"Consumo eléctrico: Normal\", \"message\": ( f\"Potencia normal", "( f\"Apagando {devices_off} para intentar evitar \" \"la sobrecarga eléctrica.\"", "self._main_power = self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\")", "main_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Sustained Power ALARM logic", "\"title\": \"Alto consumo eléctrico!\", \"message\": ( f\"Peak: {current_peak} W en", "enum import IntEnum import appdaemon.plugins.hass.hassapi as hass LOG_LEVEL = \"INFO\"", "def make_notification_message( self, current_peak, last_trigger, alarm_start, devices_off=\"\", pow_instant=0.0, pow_sustained=0.0, )", "= False self._current_peak = 0 elif ( not self._turn_off_measure_taken and", "f\"Alerta iniciada hace {duration_min:.1f} min.\" ), } return data_msg #", "peak event at {} with P={} W\".format(now, new), level=LOG_LEVEL, log=LOGGER,", "= None _turn_off_measure_taken = False _current_peak = 0 def initialize(self):", "COEF_CRITICAL_LIMIT = 1.1 # 10% over limit MIN_TIME_TURN_OFF_AC = 60", "Big power consumers BIG_CONSUMER_1_CLIMATE = \"switch.ac_dry_contact\" BIG_CONSUMER_1_LABEL = \"aire acondicionado\"", "for {self._min_time_low} secs). \" f\"Notify: {self._notifier}.\", level=LOG_LEVEL, log=LOGGER, ) def", "self._turn_off_measure_taken = True self._critical_alarm_state = False devices_turning_off = \"\" if", "\" f\"Ahora {pow_instant} W ({pow_sustained} sostenidos)\" ), } data_msg[\"message\"] =", "intentar evitar \" \"la sobrecarga eléctrica.\" ), } time_now =", "new # noinspection PyUnusedLocal def main_power_change(self, entity, attribute, old, new,", "BIG_CONSUMER_2_LABEL self.call_service( \"switch/turn_off\", entity_id=BIG_CONSUMER_2 ) if devices_turning_off: # Notification of", "= now elif (self._last_trigger is not None) and ( (now", "\" f\"Pico de potencia: {current_peak} W. \" f\"Alerta iniciada hace", "PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\" App to notify power peaks (when", "\"sound\": _IOS_SOUND_POWER_PEAK, } else: push_data = { \"category\": \"confirm\", \"thread-id\":", "W\".format(now, new), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = now elif (", "to centralize push message construction. \"\"\" ALERT_OFF = 0 ALERT_ON", "\"special_event_log\" COEF_CRITICAL_LIMIT = 1.1 # 10% over limit MIN_TIME_TURN_OFF_AC =", "required method for app init.\"\"\" self._main_power = self.args.get(\"sustained_power\") self._main_power_peak =", "class PeakNotifier(hass.Hass): \"\"\" App to notify power peaks (when they", "potencia: {current_peak} W. \" f\"Alerta iniciada hace {duration_min:.1f} min.\" ),", "push_data} return data_msg def make_telegram_push_data(self, data_msg: dict, target: int) ->", "pow_sustained=new, ) self.log( f\"TRIGGER ALARM with msg={data}\", level=LOG_LEVEL_ALERT, log=LOGGER, )", "-> dict: data_msg[\"target\"] = target data_msg[\"disable_notification\"] = self.value == self.ALERT_OFF", "float _upper_limit: float _lower_limit: float _min_time_high: int _min_time_low: int #", "# Start power peak event self.log( \"New power peak event", "f\"Peak: {current_peak} W en {time_now}. \" f\"Ahora {pow_instant} W ({pow_sustained}", "if new > self._current_peak: self._current_peak = new if ( not", "trigger if no more in min_time_lower self.log( \"RESET LAST TRIGGER", "the same power peak event, # waiting min time to", "== self.ALERT_ON: data_msg = { \"title\": \"Alto consumo eléctrico!\", \"message\":", "def main_power_change(self, entity, attribute, old, new, kwargs): \"\"\"Sustained Power ALARM", "# (this is the same power peak event, # waiting", "\"RESET ALARM MODE at {}\".format(now), level=LOG_LEVEL, log=LOGGER, ) self.notify_alert(type_notif, data)", "pow_sustained=new, ) self.notify_alert(type_notif, data) self._last_trigger = now else: self._last_trigger =", "switch.ac_dry_contact\", ), ], ] return data_msg def make_notification_message( self, current_peak,", "= \"special_event_log\" COEF_CRITICAL_LIMIT = 1.1 # 10% over limit MIN_TIME_TURN_OFF_AC", "self._current_peak, self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log( f\"TRIGGER ALARM with", "\"RESET LAST TRIGGER (was in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger", "None) and ( (now - self._last_trigger).total_seconds() > self._min_time_low ): #", "if self.value == self.ALERT_ON: data_msg = { \"title\": \"Alto consumo", "devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif self.get_state(BIG_CONSUMER_2) == \"on\": devices_turning_off", "None _alarm_start = None _turn_off_measure_taken = False _current_peak = 0", "False self._critical_alarm_state = False self._last_trigger = None self._alarm_start = None", "\"powerpeak\", \"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1, \"volume\": 1.0, \"thread-id\":", "# Normal operation, reset last trigger if no more in", "# noinspection PyClassHasNoInit class PeakNotifier(hass.Hass): \"\"\" App to notify power", "self._current_peak, self._last_trigger, self._alarm_start, ) self.log( \"RESET ALARM MODE at {}\".format(now),", "is not None else \"???\" ) if self.value == self.ALERT_ON:", "\"ENABLE CRITICAL ALARM with {} W\".format(new), level=LOG_LEVEL_ALERT, log=LOGGER, ) self._critical_alarm_state", "# pass elif self._alarm_state: # Alarm state, waiting for reset", "_IOS_SOUND_POWER_PEAK, } else: push_data = { \"category\": \"confirm\", \"thread-id\": \"power-peak-group\",", "limit). \"\"\" # Limit Values _max_peak: float _upper_limit: float _lower_limit:", "self._last_trigger = None self._alarm_start = None self._turn_off_measure_taken = False self._current_peak", "self._last_trigger, self._alarm_start, pow_instant=self.get_state(self._main_power_peak), pow_sustained=new, ) self.log( f\"TRIGGER ALARM with msg={data}\",", "= { \"category\": \"powerpeak\", \"badge\": 10, \"sound\": _IOS_SOUND_POWER_PEAK, \"critical\": 1,", "normal desde {time_now}, \" f\"Pico de potencia: {current_peak} W. \"", "notifications. Used to centralize push message construction. \"\"\" ALERT_OFF =", "more time # (this is the same power peak event,", "self._main_power_peak = self.args.get(\"instant_power\") self._notifier = self.config.get(\"notifier\").replace(\".\", \"/\") self._target_sensor = self.config.get(\"chatid_sensor\")", "Automation task as a AppDaemon App for Home Assistant -", "now = dt.datetime.now() if not self._alarm_state and (new > self._upper_limit):", "= False elif ( not self._turn_off_measure_taken and self._critical_alarm_state and (", "elif ( not self._turn_off_measure_taken and self._critical_alarm_state and new < self._upper_limit", "/ 60.0 data_msg = { \"title\": \"Consumo eléctrico: Normal\", \"message\":", "App for Home Assistant - current meter PEAK POWER notifications", "_turn_off_measure_taken = False _current_peak = 0 def initialize(self): \"\"\"AppDaemon required", "self._turn_off_measure_taken = False type_notif = TypeNotif.ALERT_ON data = type_notif.make_notification_message( self._current_peak,", "min time to trigger alarm) # pass elif self._alarm_state: #", "(was in {})\".format(self._last_trigger), level=LOG_LEVEL, log=LOGGER, ) self._last_trigger = None self._current_peak", "method for app init.\"\"\" self._main_power = self.args.get(\"sustained_power\") self._main_power_peak = self.args.get(\"instant_power\")", "log=LOGGER, ) type_notif = TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message( self._current_peak, self._last_trigger,", "utf-8 -*- \"\"\" Automation task as a AppDaemon App for", "last_trigger is not None else \"???\" ) if self.value ==", "'{devices_turning_off}'\", level=\"ERROR\", log=LOGGER, ) type_notif = TypeNotif.ALERT_CRITICAL data = type_notif.make_notification_message(", "if self.get_state(BIG_CONSUMER_1_CLIMATE) == \"on\": devices_turning_off = BIG_CONSUMER_1_LABEL self.call_service(\"climate/turn_off\", entity_id=\"all\") elif", "ALARM logic control.\"\"\" try: new = int(float(new)) except ValueError: return", "self._alarm_state = True self._critical_alarm_state = False self._last_trigger = now #", "notify power peaks (when they are greater than a certain", "== self.ALERT_CRITICAL: push_data = { \"category\": \"powerpeak\", \"badge\": 10, \"sound\":", "): # Normal operation, reset last trigger if no more" ]
[ "iteration and mainloop functions didn't release # global interpreter lock,", "and signal support. if getattr(gobject, \"pygtk_version\", ()) >= (2, 3,", "that method # as the input source. The pygtk2 input_add", "given L{FileDescriptor} for writing. \"\"\" self._remove(writer, self._writes, self._reads, INFLAGS) doIterationTimer", "processes now in case a process # exited before the", "_gobject.io_add_watch, and # g_io_add_watch() takes different condition bitfields than #", "pygtk is probably # going to stomp on us so", "auto-remove def doIteration(self, delay): # flush some pending events, return", "of that method # as the input source. The pygtk2", "= main.CONNECTION_LOST else: try: if condition & gobject.IO_IN: why =", "# recent versions of python-gtk expose this. python-gtk=2.4.1 # (wrapping", "= True else: why = main.CONNECTION_LOST else: try: if condition", "primary.remove(source) if source in other: self._sources[source] = self.input_add( source, flags,", "whether to use the glib event loop or the GTK+", "source in other: self._sources[source] = self.input_add( source, flags, self.callback) else:", "crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if", "gtk.input_add to _gobject.io_add_watch, and # g_io_add_watch() takes different condition bitfields", "gtk self.__pending = gtk.events_pending self.__iteration = gtk.main_iteration self.__crash = _our_mainquit", "does. python-gtk=2.0.0 (wrapping # glib-2.2.3) does not. gobject.threads_init() # Twisted", "and reschedule callbacks. \"\"\" if self._simtag is not None: gobject.source_remove(self._simtag)", "glib iteration and mainloop functions didn't release # global interpreter", "replicates the pygtk1 functionality. # In addition, pygtk maps gtk.input_add", "gobject.timeout_add(int(timeout * 1010), self.simulate) def install(useGtk=True): \"\"\" Configure the twisted", "\"\"\" self._remove(writer, self._writes, self._reads, INFLAGS) doIterationTimer = None def doIterationTimeout(self,", "0.1) if timeout is None: timeout = 0.1 # grumble", "selectreactor POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL # glib's", "above were installed. _reapAllProcesses() # The input_add function in pygtk1", "IO, need to cancel the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None", "mapping L{FileDescriptor} instances to gtk watch handles. @ivar _reads: A", "\"\"\" Add the given L{FileDescriptor} for monitoring either for reading", "pygtk maps gtk.input_add to _gobject.io_add_watch, and # g_io_add_watch() takes different", "both reading and writing. \"\"\" if source in primary: return", "not do this. The # function below replicates the pygtk1", "other methods here are not intended to be called directly.", "which pygtk won't mess with. This would # be better", "gobject.IO_NVAL # glib's iochannel sources won't tell us about any", "case a process # exited before the handlers above were", "timeout handle for the next L{simulate} call. \"\"\" implements(IReactorFDSet) def", "None) is not None: signal.siginterrupt(signal.SIGCHLD, False) # Like the base,", "do, must delay if delay == 0: return # shouldn't", "if getattr(signal, \"siginterrupt\", None) is not None: signal.siginterrupt(signal.SIGCHLD, False) #", "# In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and #", "log.msg(channel='system', event='iteration', reactor=self) if self.__pending(): self.__iteration(0) return # nothing to", "# back to our extension module. See #4286. from twisted.internet.process", "there was something to do # don't use the usual", "reader): \"\"\" Add a L{FileDescriptor} for monitoring of data available", "twisted.internet.interfaces import IReactorFDSet from twisted.internet import main, base, posixbase, error,", "twisted.python.compat import set from twisted.internet.interfaces import IReactorFDSet from twisted.internet import", "only that operation. \"\"\" if source not in primary: return", "raises an exception if # gtk.main_level() == 0; however, all", "self.context = gobject.main_context_default() self.__pending = self.context.pending self.__iteration = self.context.iteration self.loop", "don't use the usual \"while self.context.pending(): self.context.iteration()\" # idiom because", "# maybe we're using pygtk before this hack existed. import", "# This will either wake up from IO or from", "# bug. def input_add(self, source, condition, callback): if hasattr(source, 'fileno'):", "currently monitored for reading. @ivar _writes: A set of L{FileDescriptor}", "inRead = True if not why and condition & gobject.IO_OUT:", "the glib/gtk2 mainloop. In order to use this support, simply", "be slightly faster but does not support GUI). \"\"\" reactor", "the given L{FileDescriptor} for monitoring either for reading or writing.", "to interact with the glib/gtk2 mainloop. In order to use", "reschedule callbacks. \"\"\" if self._simtag is not None: gobject.source_remove(self._simtag) self.runUntilCurrent()", "if we use this # function to stop the reactor.", "_SIGCHLDWaker to use. Then, at least, we could fall #", "LICENSE for details. \"\"\" This module provides support for Twisted", "self.__iteration = self.context.iteration self.loop = gobject.MainLoop() self.__crash = self.loop.quit self.__run", "extension module. See #4286. from twisted.internet.process import reapAllProcesses as _reapAllProcesses", "objects def wrapper(source, condition, real_s=source, real_cb=callback): return real_cb(real_s, condition) return", "reschedule callbacks. \"\"\" if self._simtag is not None: gobject.source_remove(self._simtag) self.iterate()", "with a # 'fileno' method and, if present, uses the", "self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) # mainloop is deprecated in newer versions", "us so go beyond that and set up some #", "to cancel the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None def crash(self):", "use twisted.internet APIs as usual. The other methods here are", "registration and re-register it for both reading and writing. \"\"\"", "if source in self._reads: why = main.CONNECTION_DONE inRead = True", "(wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping # glib-2.2.3) does not. gobject.threads_init()", "the gtk mainloop. \"\"\" reactor = PortableGtkReactor() from twisted.internet.main import", "below replicates the pygtk1 functionality. # In addition, pygtk maps", "usual \"while self.context.pending(): self.context.iteration()\" # idiom because lots of IO", "def getWriters(self): \"\"\" Retrieve the list of current L{FileDescriptor} monitored", "not why and condition & gobject.IO_OUT: # if doRead caused", "\"\"\" GTK+-2 event loop reactor. @ivar _sources: A dictionary mapping", "if self.__pending(): self.__iteration(0) return # nothing to do, must delay", "self.doIterationTimer = None def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def run(self, installSignalHandlers=1):", "events that we haven't # asked for, even if those", "support GUI). \"\"\" reactor = Gtk2Reactor(useGtk) from twisted.internet.main import installReactor", "or the GTK+ event loop which is based on it", "return reactor if runtime.platform.getType() != 'posix': install = portableInstall __all__", "condition, callback): if hasattr(source, 'fileno'): # handle python objects def", "condition & POLL_DISCONNECTED and not (condition & gobject.IO_IN): if source", "not source.disconnected: why = source.doWrite() except: why = sys.exc_info()[1] log.msg('Error", "to the poll() # call. INFLAGS = gobject.IO_IN | POLL_DISCONNECTED", "Add a L{FileDescriptor} for monitoring of data available to read.", "a timeout. self.__iteration(1) # block # note: with the .simulate", "\"\"\" This module provides support for Twisted to interact with", "present, uses the result of that method # as the", "_simtag: A gtk timeout handle for the next L{simulate} call.", "= None def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers)", "and condition & gobject.IO_OUT: # if doRead caused connectionLost, don't", "posixbase.PosixReactorBase.crash(self) self.__crash() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if self._started:", "from twisted.internet import gtk2reactor | gtk2reactor.install() Then use twisted.internet APIs", "from twisted.python.compat import set from twisted.internet.interfaces import IReactorFDSet from twisted.internet", "timeout. self.__iteration(1) # block # note: with the .simulate timer", "gtk.mainquit() def run(self, installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) #", "import gtk here... I will remove this # comment if", "if source in other: gobject.source_remove(self._sources[source]) flags |= otherFlag self._sources[source] =", "a # different implementation of installHandler for # _SIGCHLDWaker to", "and set up some # signal handling which pygtk won't", "asked for, even if those events aren't sensible inputs to", "handle python objects def wrapper(source, condition, real_s=source, real_cb=callback): return real_cb(real_s,", "however, all the tests freeze if we use this #", "woken up by the .simulate timer if self.doIterationTimer: # if", "None: timeout = 0.1 # grumble self._simtag = gobject.timeout_add(int(timeout *", "return list(self._writes) def removeAll(self): \"\"\" Remove monitoring for all registered", "self.iterate() timeout = min(self.timeout(), 0.1) if timeout is None: timeout", "to read. \"\"\" self._add(reader, self._reads, self._writes, INFLAGS, OUTFLAGS) def addWriter(self,", "bug. def input_add(self, source, condition, callback): if hasattr(source, 'fileno'): #", "be run inside the gtk mainloop. \"\"\" reactor = PortableGtkReactor()", "if getattr(gobject, \"pygtk_version\", ()) >= (2, 3, 91) and not", "not. gobject.threads_init() # Twisted Imports from twisted.python import log, runtime,", "is not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if", "or writing. If it's still monitored for the other operation,", "beyond that and set up some # signal handling which", "interpreter lock, thus breaking thread and signal support. if getattr(gobject,", "the pygtk1 functionality. # In addition, pygtk maps gtk.input_add to", "if condition & gobject.IO_IN: why = source.doRead() inRead = True", "the reactor. what gives? (I believe this may have been", "gobject.source_remove(self._sources[source]) flags |= otherFlag self._sources[source] = self.input_add(source, flags, self.callback) primary.add(source)", "condition, real_s=source, real_cb=callback): return real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(), condition, wrapper)", "other: gobject.source_remove(self._sources[source]) flags |= otherFlag self._sources[source] = self.input_add(source, flags, self.callback)", "woken by IO, need to cancel the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer", "# 'fileno' method and, if present, uses the result of", "not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if timeout", "other operation, we re-register the L{FileDescriptor} for only that operation.", "timeout is None: timeout = 0.1 # grumble self._simtag =", "import log, runtime, failure from twisted.python.compat import set from twisted.internet.interfaces", "True if not why and condition & gobject.IO_OUT: # if", "error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why = None inRead =", "not None: gobject.source_remove(self._simtag) self.iterate() timeout = min(self.timeout(), 0.1) if timeout", "removeReader(self, reader): \"\"\" Stop monitoring the given L{FileDescriptor} for reading.", "log.deferr() if why: self._disconnectSelectable(source, why, inRead) def callback(self, source, condition):", "self._simtag = None self._reads = set() self._writes = set() self._sources", "previous registration and re-register it for both reading and writing.", "and, if present, uses the result of that method #", "# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for", "timeout = 0.1 # grumble self._simtag = gobject.timeout_add(int(timeout * 1010),", "does not support GUI). \"\"\" reactor = Gtk2Reactor(useGtk) from twisted.internet.main", "0 # auto-remove def doIteration(self, delay): # flush some pending", "but adds GUI integration. \"\"\" # System Imports import sys,", "self._writes) def _remove(self, source, primary, other, flags): \"\"\" Remove monitoring", "A set of L{FileDescriptor} instances currently monitored for writing. @ivar", "# gtk.main_level() == 0; however, all the tests freeze if", "supported by GTK+'s input_add on Win32. \"\"\" _simtag = None", "primary: return gobject.source_remove(self._sources[source]) primary.remove(source) if source in other: self._sources[source] =", "The pygtk2 input_add does not do this. The # function", "self._reads, self._writes, INFLAGS, OUTFLAGS) def addWriter(self, writer): \"\"\" Add a", "is based on it but adds GUI integration. \"\"\" #", "otherFlag): \"\"\" Add the given L{FileDescriptor} for monitoring either for", "real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(), condition, wrapper) else: return gobject.io_add_watch(source, condition,", "just return self.doIterationTimer = gobject.timeout_add(int(delay * 1000), self.doIterationTimeout) # This", "source, primary, other, flags): \"\"\" Remove monitoring the given L{FileDescriptor}", "-*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE", "if self.doIterationTimer: # if woken by IO, need to cancel", "_sources: A dictionary mapping L{FileDescriptor} instances to gtk watch handles.", "monitored for the other operation, we delete the previous registration", "& gobject.IO_IN: why = source.doRead() inRead = True if not", "runtime.platformType == 'posix': def _handleSignals(self): # Let the base class", "for details. \"\"\" This module provides support for Twisted to", "GTK+'s input_add on Win32. \"\"\" _simtag = None def crash(self):", "operation, we re-register the L{FileDescriptor} for only that operation. \"\"\"", "iochannel sources won't tell us about any events that we", "is not None: signal.siginterrupt(signal.SIGCHLD, False) # Like the base, reap", "handle for the next L{simulate} call. \"\"\" implements(IReactorFDSet) def __init__(self,", "tests freeze if we use this # function to stop", "import set from twisted.internet.interfaces import IReactorFDSet from twisted.internet import main,", "inside the gtk mainloop. \"\"\" reactor = PortableGtkReactor() from twisted.internet.main", "= None def crash(self): selectreactor.SelectReactor.crash(self) import gtk # mainquit is", "usual. The other methods here are not intended to be", "This module provides support for Twisted to interact with the", "maybe we're using pygtk before this hack existed. import gobject", "before this hack existed. import gobject if hasattr(gobject, \"threads_init\"): #", "_reads: A set of L{FileDescriptor} instances currently monitored for reading.", "support, simply do the following:: | from twisted.internet import gtk2reactor", "posixbase, error, selectreactor POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL", "= None def doIterationTimeout(self, *args): self.doIterationTimer = None return 0", "list(self._writes) def removeAll(self): \"\"\" Remove monitoring for all registered L{FileDescriptor}s.", "gobject if hasattr(gobject, \"threads_init\"): # recent versions of python-gtk expose", "\"\"\" Retrieve the list of current L{FileDescriptor} monitored for writing.", "the usual \"while self.context.pending(): self.context.iteration()\" # idiom because lots of", "hack existed. import gobject if hasattr(gobject, \"threads_init\"): # recent versions", "self._sources[source] = self.input_add(source, flags, self.callback) primary.add(source) def addReader(self, reader): \"\"\"", "flags |= otherFlag self._sources[source] = self.input_add(source, flags, self.callback) primary.add(source) def", "simply do the following:: | from twisted.internet import gtk2reactor |", "source, condition) self.simulate() # fire Twisted timers return 1 #", "gobject.IO_IN): if source in self._reads: why = main.CONNECTION_DONE inRead =", "and mainloop functions didn't release # global interpreter lock, thus", "This will either wake up from IO or from a", "main, base, posixbase, error, selectreactor POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR", "python objects def wrapper(source, condition, real_s=source, real_cb=callback): return real_cb(real_s, condition)", "None def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0,", "on it but adds GUI integration. \"\"\" # System Imports", "L{FileDescriptor} for monitoring ability to write data. \"\"\" self._add(writer, self._writes,", "always be # woken up by the .simulate timer if", "again. if not source.disconnected: why = source.doWrite() except: why =", "where I forgot to import gtk here... I will remove", "= self.loop.quit self.__run = self.loop.run else: import gtk self.__pending =", "import gobject if hasattr(gobject, \"threads_init\"): # recent versions of python-gtk", "gtk2reactor.install() Then use twisted.internet APIs as usual. The other methods", "writer): \"\"\" Stop monitoring the given L{FileDescriptor} for writing. \"\"\"", "import reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses)) if", "monitored for the other operation, we re-register the L{FileDescriptor} for", "import sys, signal from zope.interface import implements try: if not", "\"\"\" Run simulation loops and reschedule callbacks. \"\"\" if self._simtag", "call. INFLAGS = gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT |", "None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if timeout is", "# The input_add function in pygtk1 checks for objects with", "self.simulate() # fire Twisted timers return 1 # 1=don't auto-remove", "== 0; however, all the tests freeze if we use", "_remove(self, source, primary, other, flags): \"\"\" Remove monitoring the given", "provides support for Twisted to interact with the glib/gtk2 mainloop.", "the source def simulate(self): \"\"\" Run simulation loops and reschedule", "def install(useGtk=True): \"\"\" Configure the twisted mainloop to be run", "flush some pending events, return if there was something to", "def _remove(self, source, primary, other, flags): \"\"\" Remove monitoring the", "if there was something to do # don't use the", "given L{FileDescriptor} for reading. \"\"\" self._remove(reader, self._reads, self._writes, OUTFLAGS) def", "def __init__(self, useGtk=True): self._simtag = None self._reads = set() self._writes", "If the file is already monitored for the other operation,", "lambda *a: self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\", None) is not None:", "and not (condition & gobject.IO_IN): if source in self._reads: why", "self._reads: why = main.CONNECTION_DONE inRead = True else: why =", "does not do this. The # function below replicates the", "it's still monitored for the other operation, we re-register the", "= gobject.IO_OUT | POLL_DISCONNECTED def _our_mainquit(): # XXX: gtk.main_quit() (which", "def removeWriter(self, writer): \"\"\" Stop monitoring the given L{FileDescriptor} for", "will always be # woken up by the .simulate timer", "gobject.timeout_add(0, self.simulate) # mainloop is deprecated in newer versions if", "go beyond that and set up some # signal handling", "}): why = None inRead = False if condition &", "writing. \"\"\" self._remove(writer, self._writes, self._reads, INFLAGS) doIterationTimer = None def", "handling which pygtk won't mess with. This would # be", "as usual. The other methods here are not intended to", "self._simtag is not None: gobject.source_remove(self._simtag) self.iterate() timeout = min(self.timeout(), 0.1)", "if source in primary: return flags = primaryFlag if source", "def wrapper(source, condition, real_s=source, real_cb=callback): return real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(),", "When installing the reactor, you can choose whether to use", "def _doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }):", "not useGtk: self.context = gobject.main_context_default() self.__pending = self.context.pending self.__iteration =", "'fileno'): # handle python objects def wrapper(source, condition, real_s=source, real_cb=callback):", "See #4286. from twisted.internet.process import reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD,", "gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event loop reactor. @ivar _sources:", "here are not intended to be called directly. When installing", "= False if condition & POLL_DISCONNECTED and not (condition &", "condition): log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate() # fire Twisted timers", "reap processes now in case a process # exited before", "gtk mainloop. @param useGtk: should glib rather than GTK+ event", "faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why = None inRead", "by letting this reactor select a # different implementation of", "= gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL # glib's iochannel sources", "the file is already monitored for the other operation, we", "# Let the base class do its thing, but pygtk", "Reactor that works on Windows. Sockets aren't supported by GTK+'s", "doIteration(self, delay): # flush some pending events, return if there", "gtk2reactor | gtk2reactor.install() Then use twisted.internet APIs as usual. The", "GTK+ event loop be used (this will be slightly faster", "of installHandler for # _SIGCHLDWaker to use. Then, at least,", "for writing. @ivar _simtag: A gtk timeout handle for the", "# grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) def install(useGtk=True):", "= gobject.MainLoop() self.__crash = self.loop.quit self.__run = self.loop.run else: import", "The # function below replicates the pygtk1 functionality. # In", "do # don't use the usual \"while self.context.pending(): self.context.iteration()\" #", "mainquit is deprecated in newer versions if gtk.main_level(): if hasattr(gtk,", "\"\"\" return list(self._reads) def getWriters(self): \"\"\" Retrieve the list of", "we delete the previous registration and re-register it for both", "slightly faster but does not support GUI). \"\"\" reactor =", "installReactor installReactor(reactor) return reactor if runtime.platform.getType() != 'posix': install =", "check this for py2exe import pygtk pygtk.require('2.0') except (ImportError, AttributeError):", "Retrieve the list of current L{FileDescriptor} monitored for writing. \"\"\"", "caused connectionLost, don't call doWrite # if doRead is doWrite,", "hasattr(sys, 'frozen'): # Don't want to check this for py2exe", "useGtk: should glib rather than GTK+ event loop be used", "import IReactorFDSet from twisted.internet import main, base, posixbase, error, selectreactor", "is used for crash()) raises an exception if # gtk.main_level()", "gtk.main_quit() (which is used for crash()) raises an exception if", "monitored for reading. \"\"\" return list(self._reads) def getWriters(self): \"\"\" Retrieve", "self.__iteration(0) return # nothing to do, must delay if delay", "log.msg('Error In %s' % source) log.deferr() if why: self._disconnectSelectable(source, why,", "Remove monitoring the given L{FileDescriptor} for either reading or writing.", "before the handlers above were installed. _reapAllProcesses() # The input_add", "(2, 3, 91) and not useGtk: self.context = gobject.main_context_default() self.__pending", "to be run inside the gtk mainloop. @param useGtk: should", "any events that we haven't # asked for, even if", "@param useGtk: should glib rather than GTK+ event loop be", "particular test_tcp's # ProperlyCloseFilesTestCase) can keep us from ever exiting.", "global interpreter lock, thus breaking thread and signal support. if", "pygtk pygtk.require('2.0') except (ImportError, AttributeError): pass # maybe we're using", "twisted.internet import main, base, posixbase, error, selectreactor POLL_DISCONNECTED = gobject.IO_HUP", "pygtk1 checks for objects with a # 'fileno' method and,", "gtk.main if runtime.platformType == 'posix': def _handleSignals(self): # Let the", "self._add(writer, self._writes, self._reads, OUTFLAGS, INFLAGS) def getReaders(self): \"\"\" Retrieve the", "based on it but adds GUI integration. \"\"\" # System", "def crash(self): selectreactor.SelectReactor.crash(self) import gtk # mainquit is deprecated in", "# XXX: gtk.main_quit() (which is used for crash()) raises an", "implementation of installHandler for # _SIGCHLDWaker to use. Then, at", "that works on Windows. Sockets aren't supported by GTK+'s input_add", "the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash()", "True else: why = main.CONNECTION_LOST else: try: if condition &", "INFLAGS = gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED", "to be called directly. When installing the reactor, you can", "crash(self): selectreactor.SelectReactor.crash(self) import gtk # mainquit is deprecated in newer", "probably # going to stomp on us so go beyond", "self.__run = gtk.main if runtime.platformType == 'posix': def _handleSignals(self): #", "can keep us from ever exiting. log.msg(channel='system', event='iteration', reactor=self) if", "self.doIterationTimer = gobject.timeout_add(int(delay * 1000), self.doIterationTimeout) # This will either", "self._started: self.__run() def _doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost:", "from twisted.internet.main import installReactor installReactor(reactor) return reactor if runtime.platform.getType() !=", "else: gtk.mainloop() def simulate(self): \"\"\" Run simulation loops and reschedule", "the twisted mainloop to be run inside the gtk mainloop.", "than # gtk_input_add(). We use g_io_add_watch() here in case pygtk", "if doRead is doWrite, don't call it again. if not", "this support, simply do the following:: | from twisted.internet import", "it for both reading and writing. \"\"\" if source in", "adds GUI integration. \"\"\" # System Imports import sys, signal", "gobject.source_remove(self._simtag) self.iterate() timeout = min(self.timeout(), 0.1) if timeout is None:", "# if woken by IO, need to cancel the timer", "don't call it again. if not source.disconnected: why = source.doWrite()", "This would # be better done by letting this reactor", "registered L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads, self._writes) def _remove(self, source, primary,", "grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\"", "pygtk1 functionality. # In addition, pygtk maps gtk.input_add to _gobject.io_add_watch,", "list of current L{FileDescriptor} monitored for writing. \"\"\" return list(self._writes)", "if not hasattr(sys, 'frozen'): # Don't want to check this", "implements(IReactorFDSet) def __init__(self, useGtk=True): self._simtag = None self._reads = set()", "if hasattr(gobject, \"threads_init\"): # recent versions of python-gtk expose this.", "else: why = main.CONNECTION_LOST else: try: if condition & gobject.IO_IN:", "(condition & gobject.IO_IN): if source in self._reads: why = main.CONNECTION_DONE", "self.__crash() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if self._started: self.__run()", "in self._reads: why = main.CONNECTION_DONE inRead = True else: why", "in other: gobject.source_remove(self._sources[source]) flags |= otherFlag self._sources[source] = self.input_add(source, flags,", "if gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event loop reactor.", "= set() self._writes = set() self._sources = {} posixbase.PosixReactorBase.__init__(self) #", "main.CONNECTION_DONE inRead = True else: why = main.CONNECTION_LOST else: try:", "Then, at least, we could fall # back to our", "\"\"\" self._add(reader, self._reads, self._writes, INFLAGS, OUTFLAGS) def addWriter(self, writer): \"\"\"", "from twisted.internet.main import installReactor installReactor(reactor) return reactor def portableInstall(useGtk=True): \"\"\"", "for Twisted to interact with the glib/gtk2 mainloop. In order", "self.context.pending(): self.context.iteration()\" # idiom because lots of IO (in particular", "next L{simulate} call. \"\"\" implements(IReactorFDSet) def __init__(self, useGtk=True): self._simtag =", "OUTFLAGS, INFLAGS) def getReaders(self): \"\"\" Retrieve the list of current", "already monitored for the other operation, we delete the previous", "run inside the gtk mainloop. @param useGtk: should glib rather", "doWrite # if doRead is doWrite, don't call it again.", "if why: self._disconnectSelectable(source, why, inRead) def callback(self, source, condition): log.callWithLogger(source,", "about any events that we haven't # asked for, even", "= sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr() if why:", "error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why = None inRead = False if", "Add a L{FileDescriptor} for monitoring ability to write data. \"\"\"", "gobject.IO_OUT: # if doRead caused connectionLost, don't call doWrite #", "Imports from twisted.python import log, runtime, failure from twisted.python.compat import", "primary.add(source) def addReader(self, reader): \"\"\" Add a L{FileDescriptor} for monitoring", "@ivar _writes: A set of L{FileDescriptor} instances currently monitored for", "try: if condition & gobject.IO_IN: why = source.doRead() inRead =", "return 1 # 1=don't auto-remove the source def simulate(self): \"\"\"", "events aren't sensible inputs to the poll() # call. INFLAGS", "to stop the reactor. what gives? (I believe this may", "read. \"\"\" self._add(reader, self._reads, self._writes, INFLAGS, OUTFLAGS) def addWriter(self, writer):", "self._writes, self._reads, OUTFLAGS, INFLAGS) def getReaders(self): \"\"\" Retrieve the list", "& gobject.IO_OUT: # if doRead caused connectionLost, don't call doWrite", "failure.Failure(error.ConnectionLost()), }): why = None inRead = False if condition", "the gtk mainloop. @param useGtk: should glib rather than GTK+", "*args): self.doIterationTimer = None return 0 # auto-remove def doIteration(self,", "def run(self, installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) # mainloop", "= self.context.iteration self.loop = gobject.MainLoop() self.__crash = self.loop.quit self.__run =", "__init__(self, useGtk=True): self._simtag = None self._reads = set() self._writes =", "set of L{FileDescriptor} instances currently monitored for writing. @ivar _simtag:", "self.callback) else: self._sources.pop(source) def removeReader(self, reader): \"\"\" Stop monitoring the", "1010), self.simulate) def install(useGtk=True): \"\"\" Configure the twisted mainloop to", "and writing. \"\"\" if source in primary: return flags =", "primary: return flags = primaryFlag if source in other: gobject.source_remove(self._sources[source])", "\"\"\" Configure the twisted mainloop to be run inside the", "PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that works on Windows. Sockets aren't supported", "cancel the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None def crash(self): posixbase.PosixReactorBase.crash(self)", "(which is used for crash()) raises an exception if #", "= Gtk2Reactor(useGtk) from twisted.internet.main import installReactor installReactor(reactor) return reactor def", "installReactor(reactor) return reactor def portableInstall(useGtk=True): \"\"\" Configure the twisted mainloop", "will remove this # comment if the tests pass) import", "call doWrite # if doRead is doWrite, don't call it", "primary, other, primaryFlag, otherFlag): \"\"\" Add the given L{FileDescriptor} for", "import gtk2reactor | gtk2reactor.install() Then use twisted.internet APIs as usual.", "versions of python-gtk expose this. python-gtk=2.4.1 # (wrapping glib-2.4.7) does.", "# signal handling which pygtk won't mess with. This would", "# idiom because lots of IO (in particular test_tcp's #", "to use this support, simply do the following:: | from", "back to our extension module. See #4286. from twisted.internet.process import", "better done by letting this reactor select a # different", "# (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping # glib-2.2.3) does not.", "deprecated in newer versions if hasattr(gtk, 'main'): gtk.main() else: gtk.mainloop()", "is probably # going to stomp on us so go", "of python-gtk expose this. python-gtk=2.4.1 # (wrapping glib-2.4.7) does. python-gtk=2.0.0", "self._add(reader, self._reads, self._writes, INFLAGS, OUTFLAGS) def addWriter(self, writer): \"\"\" Add", "\"\"\" if source in primary: return flags = primaryFlag if", "import main, base, posixbase, error, selectreactor POLL_DISCONNECTED = gobject.IO_HUP |", "this reactor select a # different implementation of installHandler for", "functions didn't release # global interpreter lock, thus breaking thread", "inside the gtk mainloop. @param useGtk: should glib rather than", "primary, other, flags): \"\"\" Remove monitoring the given L{FileDescriptor} for", "Imports import sys, signal from zope.interface import implements try: if", "_simtag = None def crash(self): selectreactor.SelectReactor.crash(self) import gtk # mainquit", "source not in primary: return gobject.source_remove(self._sources[source]) primary.remove(source) if source in", "0: return # shouldn't delay, so just return self.doIterationTimer =", "\"\"\" if self._simtag is not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout =", "'frozen'): # Don't want to check this for py2exe import", "to use. Then, at least, we could fall # back", "if doRead caused connectionLost, don't call doWrite # if doRead", "self.doIterationTimer: # if woken by IO, need to cancel the", "expose this. python-gtk=2.4.1 # (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping #", "does not. gobject.threads_init() # Twisted Imports from twisted.python import log,", "ability to write data. \"\"\" self._add(writer, self._writes, self._reads, OUTFLAGS, INFLAGS)", "thing, but pygtk is probably # going to stomp on", "haven't # asked for, even if those events aren't sensible", "or writing. If the file is already monitored for the", "from ever exiting. log.msg(channel='system', event='iteration', reactor=self) if self.__pending(): self.__iteration(0) return", "newer versions if hasattr(gtk, 'main'): gtk.main() else: gtk.mainloop() def simulate(self):", "# block # note: with the .simulate timer below, delays", "0.1 # grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) class", "twisted.internet import gtk2reactor | gtk2reactor.install() Then use twisted.internet APIs as", "pass) import gtk if gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2", "mainloop is deprecated in newer versions if hasattr(gtk, 'main'): gtk.main()", "def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if self._started: self.__run() def", "POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL # glib's iochannel", "Don't want to check this for py2exe import pygtk pygtk.require('2.0')", "= self.input_add( source, flags, self.callback) else: self._sources.pop(source) def removeReader(self, reader):", "this. python-gtk=2.4.1 # (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping # glib-2.2.3)", "glib's iochannel sources won't tell us about any events that", "note: with the .simulate timer below, delays > 0.1 will", "None return 0 # auto-remove def doIteration(self, delay): # flush", "AttributeError): pass # maybe we're using pygtk before this hack", "% source) log.deferr() if why: self._disconnectSelectable(source, why, inRead) def callback(self,", "# nothing to do, must delay if delay == 0:", "Twisted to interact with the glib/gtk2 mainloop. In order to", "pygtk fixes this # bug. def input_add(self, source, condition, callback):", "that operation. \"\"\" if source not in primary: return gobject.source_remove(self._sources[source])", "# pre 2.3.91 the glib iteration and mainloop functions didn't", "not in primary: return gobject.source_remove(self._sources[source]) primary.remove(source) if source in other:", "function in pygtk1 checks for objects with a # 'fileno'", "GTK+ event loop which is based on it but adds", "you can choose whether to use the glib event loop", "faster but does not support GUI). \"\"\" reactor = Gtk2Reactor(useGtk)", "return # shouldn't delay, so just return self.doIterationTimer = gobject.timeout_add(int(delay", "list(self._reads) def getWriters(self): \"\"\" Retrieve the list of current L{FileDescriptor}", "this # comment if the tests pass) import gtk if", "\"pygtk_version\", ()) >= (2, 3, 91) and not useGtk: self.context", "Retrieve the list of current L{FileDescriptor} monitored for reading. \"\"\"", "gobject.main_context_default() self.__pending = self.context.pending self.__iteration = self.context.iteration self.loop = gobject.MainLoop()", "for reading. @ivar _writes: A set of L{FileDescriptor} instances currently", "Laboratories. # See LICENSE for details. \"\"\" This module provides", "installed. _reapAllProcesses() # The input_add function in pygtk1 checks for", "= True if not why and condition & gobject.IO_OUT: #", "self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) def install(useGtk=True): \"\"\" Configure", "fixes this # bug. def input_add(self, source, condition, callback): if", "getReaders(self): \"\"\" Retrieve the list of current L{FileDescriptor} monitored for", "now in case a process # exited before the handlers", "# as the input source. The pygtk2 input_add does not", "reactor select a # different implementation of installHandler for #", "= gtk.main_iteration self.__crash = _our_mainquit self.__run = gtk.main if runtime.platformType", "POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED def _our_mainquit(): # XXX:", "to gtk watch handles. @ivar _reads: A set of L{FileDescriptor}", "= gtk.events_pending self.__iteration = gtk.main_iteration self.__crash = _our_mainquit self.__run =", "removeAll(self): \"\"\" Remove monitoring for all registered L{FileDescriptor}s. \"\"\" return", "sources won't tell us about any events that we haven't", "remove this # comment if the tests pass) import gtk", "getattr(gobject, \"pygtk_version\", ()) >= (2, 3, 91) and not useGtk:", "currently monitored for writing. @ivar _simtag: A gtk timeout handle", "here in case pygtk fixes this # bug. def input_add(self,", "Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" This", "on Win32. \"\"\" _simtag = None def crash(self): selectreactor.SelectReactor.crash(self) import", "gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event loop reactor. @ivar", "if self._simtag is not None: gobject.source_remove(self._simtag) self.iterate() timeout = min(self.timeout(),", "using pygtk before this hack existed. import gobject if hasattr(gobject,", "use the glib event loop or the GTK+ event loop", "the .simulate timer below, delays > 0.1 will always be", "if gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit() def run(self,", "flags): \"\"\" Remove monitoring the given L{FileDescriptor} for either reading", "source, condition, callback): if hasattr(source, 'fileno'): # handle python objects", "= gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED def", "if runtime.platformType == 'posix': def _handleSignals(self): # Let the base", "import implements try: if not hasattr(sys, 'frozen'): # Don't want", "portableInstall(useGtk=True): \"\"\" Configure the twisted mainloop to be run inside", "INFLAGS, OUTFLAGS) def addWriter(self, writer): \"\"\" Add a L{FileDescriptor} for", "inRead) def callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate()", "python-gtk=2.0.0 (wrapping # glib-2.2.3) does not. gobject.threads_init() # Twisted Imports", "self._sources.pop(source) def removeReader(self, reader): \"\"\" Stop monitoring the given L{FileDescriptor}", "below, delays > 0.1 will always be # woken up", "current L{FileDescriptor} monitored for reading. \"\"\" return list(self._reads) def getWriters(self):", "the handlers above were installed. _reapAllProcesses() # The input_add function", "gtk.main_iteration self.__crash = _our_mainquit self.__run = gtk.main if runtime.platformType ==", "even if those events aren't sensible inputs to the poll()", "timer if self.doIterationTimer: # if woken by IO, need to", "= gobject.main_context_default() self.__pending = self.context.pending self.__iteration = self.context.iteration self.loop =", "case pygtk fixes this # bug. def input_add(self, source, condition,", "ProperlyCloseFilesTestCase) can keep us from ever exiting. log.msg(channel='system', event='iteration', reactor=self)", "gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this", "2.3.91 the glib iteration and mainloop functions didn't release #", "self._reads, OUTFLAGS, INFLAGS) def getReaders(self): \"\"\" Retrieve the list of", "| from twisted.internet import gtk2reactor | gtk2reactor.install() Then use twisted.internet", "may have been # a stupid mistake where I forgot", "use the usual \"while self.context.pending(): self.context.iteration()\" # idiom because lots", "twisted mainloop to be run inside the gtk mainloop. @param", "which is based on it but adds GUI integration. \"\"\"", "else: import gtk self.__pending = gtk.events_pending self.__iteration = gtk.main_iteration self.__crash", "lots of IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can keep", "gtk # mainquit is deprecated in newer versions if gtk.main_level():", "The other methods here are not intended to be called", "# different implementation of installHandler for # _SIGCHLDWaker to use.", "| gobject.IO_ERR | gobject.IO_NVAL # glib's iochannel sources won't tell", "L{FileDescriptor} for either reading or writing. If it's still monitored", "(ImportError, AttributeError): pass # maybe we're using pygtk before this", "set() self._sources = {} posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the glib", "idiom because lots of IO (in particular test_tcp's # ProperlyCloseFilesTestCase)", "L{FileDescriptor} monitored for writing. \"\"\" return list(self._writes) def removeAll(self): \"\"\"", "file is already monitored for the other operation, we delete", "# if doRead is doWrite, don't call it again. if", "# don't use the usual \"while self.context.pending(): self.context.iteration()\" # idiom", "Twisted Imports from twisted.python import log, runtime, failure from twisted.python.compat", "to write data. \"\"\" self._add(writer, self._writes, self._reads, OUTFLAGS, INFLAGS) def", "if hasattr(gtk, 'main'): gtk.main() else: gtk.mainloop() def simulate(self): \"\"\" Run", "either for reading or writing. If the file is already", "for reading or writing. If the file is already monitored", "self._disconnectSelectable(source, why, inRead) def callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite, source,", "return gobject.source_remove(self._sources[source]) primary.remove(source) if source in other: self._sources[source] = self.input_add(", "objects with a # 'fileno' method and, if present, uses", "source, condition): log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate() # fire Twisted", "won't tell us about any events that we haven't #", "installHandler for # _SIGCHLDWaker to use. Then, at least, we", "# be better done by letting this reactor select a", "monitoring either for reading or writing. If the file is", "of L{FileDescriptor} instances currently monitored for writing. @ivar _simtag: A", "doWrite, don't call it again. if not source.disconnected: why =", "doRead caused connectionLost, don't call doWrite # if doRead is", "| gobject.IO_NVAL # glib's iochannel sources won't tell us about", "is doWrite, don't call it again. if not source.disconnected: why", "A set of L{FileDescriptor} instances currently monitored for reading. @ivar", "were installed. _reapAllProcesses() # The input_add function in pygtk1 checks", "self.__iteration = gtk.main_iteration self.__crash = _our_mainquit self.__run = gtk.main if", "# _SIGCHLDWaker to use. Then, at least, we could fall", "self.__pending = self.context.pending self.__iteration = self.context.iteration self.loop = gobject.MainLoop() self.__crash", "the glib iteration and mainloop functions didn't release # global", "handles. @ivar _reads: A set of L{FileDescriptor} instances currently monitored", "mainloop. \"\"\" reactor = PortableGtkReactor() from twisted.internet.main import installReactor installReactor(reactor)", "stomp on us so go beyond that and set up", "= None inRead = False if condition & POLL_DISCONNECTED and", "return # nothing to do, must delay if delay ==", "None: gobject.source_remove(self._simtag) self.iterate() timeout = min(self.timeout(), 0.1) if timeout is", "reactor def portableInstall(useGtk=True): \"\"\" Configure the twisted mainloop to be", "condition bitfields than # gtk_input_add(). We use g_io_add_watch() here in", "source.doRead() inRead = True if not why and condition &", "def doIterationTimeout(self, *args): self.doIterationTimer = None return 0 # auto-remove", "the input source. The pygtk2 input_add does not do this.", "an exception if # gtk.main_level() == 0; however, all the", "that and set up some # signal handling which pygtk", "self._removeAll(self._reads, self._writes) def _remove(self, source, primary, other, flags): \"\"\" Remove", "POLL_DISCONNECTED def _our_mainquit(): # XXX: gtk.main_quit() (which is used for", "primaryFlag if source in other: gobject.source_remove(self._sources[source]) flags |= otherFlag self._sources[source]", "twisted mainloop to be run inside the gtk mainloop. \"\"\"", "# function to stop the reactor. what gives? (I believe", "used (this will be slightly faster but does not support", "the .simulate timer if self.doIterationTimer: # if woken by IO,", "self.loop.run else: import gtk self.__pending = gtk.events_pending self.__iteration = gtk.main_iteration", "the reactor, you can choose whether to use the glib", "def input_add(self, source, condition, callback): if hasattr(source, 'fileno'): # handle", "it again. if not source.disconnected: why = source.doWrite() except: why", "from twisted.internet.process import reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a:", "directly. When installing the reactor, you can choose whether to", "other, flags): \"\"\" Remove monitoring the given L{FileDescriptor} for either", "not None: signal.siginterrupt(signal.SIGCHLD, False) # Like the base, reap processes", "mistake where I forgot to import gtk here... I will", "gobject.source_remove(self._sources[source]) primary.remove(source) if source in other: self._sources[source] = self.input_add( source,", "addReader(self, reader): \"\"\" Add a L{FileDescriptor} for monitoring of data", "L{FileDescriptor} for writing. \"\"\" self._remove(writer, self._writes, self._reads, INFLAGS) doIterationTimer =", "up by the .simulate timer if self.doIterationTimer: # if woken", "events, return if there was something to do # don't", "= primaryFlag if source in other: gobject.source_remove(self._sources[source]) flags |= otherFlag", "# gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes", "def simulate(self): \"\"\" Run simulation loops and reschedule callbacks. \"\"\"", "with the .simulate timer below, delays > 0.1 will always", "if delay == 0: return # shouldn't delay, so just", "log, runtime, failure from twisted.python.compat import set from twisted.internet.interfaces import", "given L{FileDescriptor} for either reading or writing. If it's still", "gobject.IO_OUT | POLL_DISCONNECTED def _our_mainquit(): # XXX: gtk.main_quit() (which is", "# -*- test-case-name: twisted.internet.test -*- # Copyright (c) Twisted Matrix", "current L{FileDescriptor} monitored for writing. \"\"\" return list(self._writes) def removeAll(self):", "= set() self._sources = {} posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the", "L{FileDescriptor} for reading. \"\"\" self._remove(reader, self._reads, self._writes, OUTFLAGS) def removeWriter(self,", "if hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit() def run(self, installSignalHandlers=1): import", "@ivar _reads: A set of L{FileDescriptor} instances currently monitored for", "self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if self._started: self.__run() def _doReadOrWrite(self, source, condition,", "# Like the base, reap processes now in case a", "L{FileDescriptor} instances to gtk watch handles. @ivar _reads: A set", "& POLL_DISCONNECTED and not (condition & gobject.IO_IN): if source in", "= gobject.timeout_add(int(timeout * 1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that", "can choose whether to use the glib event loop or", "self.__run() def _doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()),", "select a # different implementation of installHandler for # _SIGCHLDWaker", "inRead = False if condition & POLL_DISCONNECTED and not (condition", "for, even if those events aren't sensible inputs to the", "reactor = Gtk2Reactor(useGtk) from twisted.internet.main import installReactor installReactor(reactor) return reactor", "self.context.iteration()\" # idiom because lots of IO (in particular test_tcp's", "return reactor def portableInstall(useGtk=True): \"\"\" Configure the twisted mainloop to", "# fire Twisted timers return 1 # 1=don't auto-remove the", "delay): # flush some pending events, return if there was", "didn't release # global interpreter lock, thus breaking thread and", "(in particular test_tcp's # ProperlyCloseFilesTestCase) can keep us from ever", "monitoring ability to write data. \"\"\" self._add(writer, self._writes, self._reads, OUTFLAGS,", "sensible inputs to the poll() # call. INFLAGS = gobject.IO_IN", "if not why and condition & gobject.IO_OUT: # if doRead", "mainloop. @param useGtk: should glib rather than GTK+ event loop", "function to stop the reactor. what gives? (I believe this", "\"\"\" Retrieve the list of current L{FileDescriptor} monitored for reading.", "0.1 # grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) def", "# call. INFLAGS = gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT", "handlers above were installed. _reapAllProcesses() # The input_add function in", "support for Twisted to interact with the glib/gtk2 mainloop. In", "class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event loop reactor. @ivar _sources: A", "a stupid mistake where I forgot to import gtk here...", "glib rather than GTK+ event loop be used (this will", "In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and # g_io_add_watch()", "callback): if hasattr(source, 'fileno'): # handle python objects def wrapper(source,", "def doIteration(self, delay): # flush some pending events, return if", "callbacks. \"\"\" if self._simtag is not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout", "the given L{FileDescriptor} for either reading or writing. If it's", "L{FileDescriptor} for monitoring of data available to read. \"\"\" self._add(reader,", "monitoring of data available to read. \"\"\" self._add(reader, self._reads, self._writes,", "writing. If it's still monitored for the other operation, we", "_add(self, source, primary, other, primaryFlag, otherFlag): \"\"\" Add the given", "writer): \"\"\" Add a L{FileDescriptor} for monitoring ability to write", "\"\"\" reactor = Gtk2Reactor(useGtk) from twisted.internet.main import installReactor installReactor(reactor) return", "import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) # mainloop is deprecated in", "\"\"\" Add a L{FileDescriptor} for monitoring ability to write data.", "reading and writing. \"\"\" if source in primary: return flags", "use. Then, at least, we could fall # back to", "base class do its thing, but pygtk is probably #", "self._simtag is not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1)", "self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor", "import gtk if gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event", "System Imports import sys, signal from zope.interface import implements try:", "details. \"\"\" This module provides support for Twisted to interact", "input source. The pygtk2 input_add does not do this. The", "than GTK+ event loop be used (this will be slightly", "be used (this will be slightly faster but does not", "to import gtk here... I will remove this # comment", "91) and not useGtk: self.context = gobject.main_context_default() self.__pending = self.context.pending", "except (ImportError, AttributeError): pass # maybe we're using pygtk before", "crash()) raises an exception if # gtk.main_level() == 0; however,", "twisted.internet.test -*- # Copyright (c) Twisted Matrix Laboratories. # See", "delay if delay == 0: return # shouldn't delay, so", "run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if self._started: self.__run() def _doReadOrWrite(self,", "lock, thus breaking thread and signal support. if getattr(gobject, \"pygtk_version\",", "checks for objects with a # 'fileno' method and, if", "else: return gobject.io_add_watch(source, condition, callback) def _add(self, source, primary, other,", "the next L{simulate} call. \"\"\" implements(IReactorFDSet) def __init__(self, useGtk=True): self._simtag", "False) # Like the base, reap processes now in case", "self.input_add(source, flags, self.callback) primary.add(source) def addReader(self, reader): \"\"\" Add a", "from a timeout. self.__iteration(1) # block # note: with the", "self._reads, self._writes, OUTFLAGS) def removeWriter(self, writer): \"\"\" Stop monitoring the", "reactor. what gives? (I believe this may have been #", "a L{FileDescriptor} for monitoring ability to write data. \"\"\" self._add(writer,", "for both reading and writing. \"\"\" if source in primary:", "auto-remove the source def simulate(self): \"\"\" Run simulation loops and", "us about any events that we haven't # asked for,", "self._sources[source] = self.input_add( source, flags, self.callback) else: self._sources.pop(source) def removeReader(self,", "*a: self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\", None) is not None: signal.siginterrupt(signal.SIGCHLD,", "is not None: gobject.source_remove(self._simtag) self.iterate() timeout = min(self.timeout(), 0.1) if", "else: try: if condition & gobject.IO_IN: why = source.doRead() inRead", "use g_io_add_watch() here in case pygtk fixes this # bug.", "# comment if the tests pass) import gtk if gtk.main_level():", "used for crash()) raises an exception if # gtk.main_level() ==", "twisted.internet.main import installReactor installReactor(reactor) return reactor if runtime.platform.getType() != 'posix':", "gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL # glib's iochannel sources won't", "exiting. log.msg(channel='system', event='iteration', reactor=self) if self.__pending(): self.__iteration(0) return # nothing", "%s' % source) log.deferr() if why: self._disconnectSelectable(source, why, inRead) def", "keep us from ever exiting. log.msg(channel='system', event='iteration', reactor=self) if self.__pending():", "# Don't want to check this for py2exe import pygtk", "on Windows. Sockets aren't supported by GTK+'s input_add on Win32.", "None def doIterationTimeout(self, *args): self.doIterationTimer = None return 0 #", "glib-2.4.7) does. python-gtk=2.0.0 (wrapping # glib-2.2.3) does not. gobject.threads_init() #", "implements try: if not hasattr(sys, 'frozen'): # Don't want to", "= None return 0 # auto-remove def doIteration(self, delay): #", "gobject.IO_IN: why = source.doRead() inRead = True if not why", "other operation, we delete the previous registration and re-register it", "what gives? (I believe this may have been # a", "will be slightly faster but does not support GUI). \"\"\"", "do this. The # function below replicates the pygtk1 functionality.", "is deprecated in newer versions if hasattr(gtk, 'main'): gtk.main() else:", "the tests pass) import gtk if gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase):", "for only that operation. \"\"\" if source not in primary:", "class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that works on Windows. Sockets aren't", "it but adds GUI integration. \"\"\" # System Imports import", "input_add on Win32. \"\"\" _simtag = None def crash(self): selectreactor.SelectReactor.crash(self)", "inputs to the poll() # call. INFLAGS = gobject.IO_IN |", "signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\", None) is not", "\"\"\" Stop monitoring the given L{FileDescriptor} for writing. \"\"\" self._remove(writer,", "None inRead = False if condition & POLL_DISCONNECTED and not", "Matrix Laboratories. # See LICENSE for details. \"\"\" This module", "Stop monitoring the given L{FileDescriptor} for reading. \"\"\" self._remove(reader, self._reads,", "works on Windows. Sockets aren't supported by GTK+'s input_add on", "\"siginterrupt\", None) is not None: signal.siginterrupt(signal.SIGCHLD, False) # Like the", "of L{FileDescriptor} instances currently monitored for reading. @ivar _writes: A", "tell us about any events that we haven't # asked", "the list of current L{FileDescriptor} monitored for reading. \"\"\" return", "in pygtk1 checks for objects with a # 'fileno' method", "condition, callback) def _add(self, source, primary, other, primaryFlag, otherFlag): \"\"\"", "other, primaryFlag, otherFlag): \"\"\" Add the given L{FileDescriptor} for monitoring", "POLL_DISCONNECTED and not (condition & gobject.IO_IN): if source in self._reads:", "\"\"\" Add a L{FileDescriptor} for monitoring of data available to", "python-gtk expose this. python-gtk=2.4.1 # (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping", "error, selectreactor POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL #", "def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate)", "not hasattr(sys, 'frozen'): # Don't want to check this for", "# mainquit is deprecated in newer versions if gtk.main_level(): if", "* 1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that works on", "def removeReader(self, reader): \"\"\" Stop monitoring the given L{FileDescriptor} for", "different condition bitfields than # gtk_input_add(). We use g_io_add_watch() here", "monitoring the given L{FileDescriptor} for reading. \"\"\" self._remove(reader, self._reads, self._writes,", "self.__pending = gtk.events_pending self.__iteration = gtk.main_iteration self.__crash = _our_mainquit self.__run", "thus breaking thread and signal support. if getattr(gobject, \"pygtk_version\", ())", "in newer versions if gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit() else:", "installReactor installReactor(reactor) return reactor def portableInstall(useGtk=True): \"\"\" Configure the twisted", "\"\"\" self._remove(reader, self._reads, self._writes, OUTFLAGS) def removeWriter(self, writer): \"\"\" Stop", "0.1 will always be # woken up by the .simulate", "reading or writing. If the file is already monitored for", "data available to read. \"\"\" self._add(reader, self._reads, self._writes, INFLAGS, OUTFLAGS)", "monitoring for all registered L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads, self._writes) def", "input_add(self, source, condition, callback): if hasattr(source, 'fileno'): # handle python", "release # global interpreter lock, thus breaking thread and signal", "IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can keep us from", "signal support. if getattr(gobject, \"pygtk_version\", ()) >= (2, 3, 91)", "uses the result of that method # as the input", "if # gtk.main_level() == 0; however, all the tests freeze", "if source not in primary: return gobject.source_remove(self._sources[source]) primary.remove(source) if source", "to use the glib event loop or the GTK+ event", "import pygtk pygtk.require('2.0') except (ImportError, AttributeError): pass # maybe we're", "the list of current L{FileDescriptor} monitored for writing. \"\"\" return", "L{FileDescriptor} for monitoring either for reading or writing. If the", "pygtk2 input_add does not do this. The # function below", "return if there was something to do # don't use", "addWriter(self, writer): \"\"\" Add a L{FileDescriptor} for monitoring ability to", "= None self._reads = set() self._writes = set() self._sources =", "IO or from a timeout. self.__iteration(1) # block # note:", "to _gobject.io_add_watch, and # g_io_add_watch() takes different condition bitfields than", "|= otherFlag self._sources[source] = self.input_add(source, flags, self.callback) primary.add(source) def addReader(self,", "glib/gtk2 mainloop. In order to use this support, simply do", "installing the reactor, you can choose whether to use the", "the result of that method # as the input source.", "a process # exited before the handlers above were installed.", "real_cb=callback): return real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(), condition, wrapper) else: return", "to stomp on us so go beyond that and set", "grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) def install(useGtk=True): \"\"\"", "\"\"\" Remove monitoring for all registered L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads,", "operation. \"\"\" if source not in primary: return gobject.source_remove(self._sources[source]) primary.remove(source)", "list of current L{FileDescriptor} monitored for reading. \"\"\" return list(self._reads)", "comment if the tests pass) import gtk if gtk.main_level(): gtk.main_quit()", "# glib-2.2.3) does not. gobject.threads_init() # Twisted Imports from twisted.python", "in newer versions if hasattr(gtk, 'main'): gtk.main() else: gtk.mainloop() def", "self.doIterationTimeout) # This will either wake up from IO or", "event loop which is based on it but adds GUI", "Like the base, reap processes now in case a process", "gobject.timeout_add(int(delay * 1000), self.doIterationTimeout) # This will either wake up", "could fall # back to our extension module. See #4286.", "data. \"\"\" self._add(writer, self._writes, self._reads, OUTFLAGS, INFLAGS) def getReaders(self): \"\"\"", "OUTFLAGS) def addWriter(self, writer): \"\"\" Add a L{FileDescriptor} for monitoring", "for the other operation, we re-register the L{FileDescriptor} for only", "the previous registration and re-register it for both reading and", "a # 'fileno' method and, if present, uses the result", "_handleSignals(self): # Let the base class do its thing, but", "# shouldn't delay, so just return self.doIterationTimer = gobject.timeout_add(int(delay *", "given L{FileDescriptor} for monitoring either for reading or writing. If", "result of that method # as the input source. The", "simulate(self): \"\"\" Run simulation loops and reschedule callbacks. \"\"\" if", "tests pass) import gtk if gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\"", "stop the reactor. what gives? (I believe this may have", "bitfields than # gtk_input_add(). We use g_io_add_watch() here in case", "callbacks. \"\"\" if self._simtag is not None: gobject.source_remove(self._simtag) self.iterate() timeout", "# a stupid mistake where I forgot to import gtk", "flags, self.callback) else: self._sources.pop(source) def removeReader(self, reader): \"\"\" Stop monitoring", "why and condition & gobject.IO_OUT: # if doRead caused connectionLost,", "we could fall # back to our extension module. See", "_doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why", "mess with. This would # be better done by letting", "return gobject.io_add_watch(source.fileno(), condition, wrapper) else: return gobject.io_add_watch(source, condition, callback) def", "self.__pending(): self.__iteration(0) return # nothing to do, must delay if", "We use g_io_add_watch() here in case pygtk fixes this #", "instances to gtk watch handles. @ivar _reads: A set of", "gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def run(self,", "# grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor):", "()) >= (2, 3, 91) and not useGtk: self.context =", "_our_mainquit self.__run = gtk.main if runtime.platformType == 'posix': def _handleSignals(self):", "for py2exe import pygtk pygtk.require('2.0') except (ImportError, AttributeError): pass #", "in case pygtk fixes this # bug. def input_add(self, source,", "inRead = True else: why = main.CONNECTION_LOST else: try: if", "# global interpreter lock, thus breaking thread and signal support.", "\"\"\" return list(self._writes) def removeAll(self): \"\"\" Remove monitoring for all", "to our extension module. See #4286. from twisted.internet.process import reapAllProcesses", "self.__crash = _our_mainquit self.__run = gtk.main if runtime.platformType == 'posix':", "self.doIterationTimer = None return 0 # auto-remove def doIteration(self, delay):", "# ProperlyCloseFilesTestCase) can keep us from ever exiting. log.msg(channel='system', event='iteration',", "use this support, simply do the following:: | from twisted.internet", "OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED def _our_mainquit(): # XXX: gtk.main_quit()", "I forgot to import gtk here... I will remove this", "doIterationTimer = None def doIterationTimeout(self, *args): self.doIterationTimer = None return", "been # a stupid mistake where I forgot to import", "pygtk.require('2.0') except (ImportError, AttributeError): pass # maybe we're using pygtk", "pass # maybe we're using pygtk before this hack existed.", "delay == 0: return # shouldn't delay, so just return", "def _handleSignals(self): # Let the base class do its thing,", "if source in other: self._sources[source] = self.input_add( source, flags, self.callback)", "(wrapping # glib-2.2.3) does not. gobject.threads_init() # Twisted Imports from", "simulation loops and reschedule callbacks. \"\"\" if self._simtag is not", "self.__crash = self.loop.quit self.__run = self.loop.run else: import gtk self.__pending", "should glib rather than GTK+ event loop be used (this", "addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and # g_io_add_watch() takes", "gobject.IO_ERR | gobject.IO_NVAL # glib's iochannel sources won't tell us", "The input_add function in pygtk1 checks for objects with a", "for monitoring of data available to read. \"\"\" self._add(reader, self._reads,", "GTK+-2 event loop reactor. @ivar _sources: A dictionary mapping L{FileDescriptor}", "try: if not hasattr(sys, 'frozen'): # Don't want to check", "do the following:: | from twisted.internet import gtk2reactor | gtk2reactor.install()", "monitoring the given L{FileDescriptor} for either reading or writing. If", "= gobject.timeout_add(int(timeout * 1010), self.simulate) def install(useGtk=True): \"\"\" Configure the", "must delay if delay == 0: return # shouldn't delay,", "input_add does not do this. The # function below replicates", "self.input_add( source, flags, self.callback) else: self._sources.pop(source) def removeReader(self, reader): \"\"\"", "\"threads_init\"): # recent versions of python-gtk expose this. python-gtk=2.4.1 #", "event loop reactor. @ivar _sources: A dictionary mapping L{FileDescriptor} instances", "called directly. When installing the reactor, you can choose whether", "GUI integration. \"\"\" # System Imports import sys, signal from", "getattr(signal, \"siginterrupt\", None) is not None: signal.siginterrupt(signal.SIGCHLD, False) # Like", "this hack existed. import gobject if hasattr(gobject, \"threads_init\"): # recent", "L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads, self._writes) def _remove(self, source, primary, other,", "loop or the GTK+ event loop which is based on", "callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate() # fire", "reactor, you can choose whether to use the glib event", "gobject.MainLoop() self.__crash = self.loop.quit self.__run = self.loop.run else: import gtk", "delay, so just return self.doIterationTimer = gobject.timeout_add(int(delay * 1000), self.doIterationTimeout)", "Remove monitoring for all registered L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads, self._writes)", "1 # 1=don't auto-remove the source def simulate(self): \"\"\" Run", "operation, we delete the previous registration and re-register it for", "for # _SIGCHLDWaker to use. Then, at least, we could", "different implementation of installHandler for # _SIGCHLDWaker to use. Then,", "need to cancel the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None def", "gtk mainloop. \"\"\" reactor = PortableGtkReactor() from twisted.internet.main import installReactor", "== 'posix': def _handleSignals(self): # Let the base class do", "this # bug. def input_add(self, source, condition, callback): if hasattr(source,", "gobject.timeout_add(0, self.simulate) if self._started: self.__run() def _doReadOrWrite(self, source, condition, faildict={", "_our_mainquit(): # XXX: gtk.main_quit() (which is used for crash()) raises", "twisted.internet.process import reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses))", "method and, if present, uses the result of that method", "other: self._sources[source] = self.input_add( source, flags, self.callback) else: self._sources.pop(source) def", "module. See #4286. from twisted.internet.process import reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self)", "reactor. @ivar _sources: A dictionary mapping L{FileDescriptor} instances to gtk", "aren't sensible inputs to the poll() # call. INFLAGS =", "for writing. \"\"\" return list(self._writes) def removeAll(self): \"\"\" Remove monitoring", "= 0.1 # grumble self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate)", "for the other operation, we delete the previous registration and", "not support GUI). \"\"\" reactor = Gtk2Reactor(useGtk) from twisted.internet.main import", "if timeout is None: timeout = 0.1 # grumble self._simtag", "loop reactor. @ivar _sources: A dictionary mapping L{FileDescriptor} instances to", "why = source.doWrite() except: why = sys.exc_info()[1] log.msg('Error In %s'", "test-case-name: twisted.internet.test -*- # Copyright (c) Twisted Matrix Laboratories. #", "= gobject.timeout_add(int(delay * 1000), self.doIterationTimeout) # This will either wake", "why, inRead) def callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite, source, condition)", "the L{FileDescriptor} for only that operation. \"\"\" if source not", "self._writes = set() self._sources = {} posixbase.PosixReactorBase.__init__(self) # pre 2.3.91", "loop which is based on it but adds GUI integration.", "mainloop. In order to use this support, simply do the", "None def crash(self): selectreactor.SelectReactor.crash(self) import gtk # mainquit is deprecated", "for all registered L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads, self._writes) def _remove(self,", "posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the glib iteration and mainloop functions", "0; however, all the tests freeze if we use this", "False if condition & POLL_DISCONNECTED and not (condition & gobject.IO_IN):", "why = None inRead = False if condition & POLL_DISCONNECTED", "self.simulate) # mainloop is deprecated in newer versions if hasattr(gtk,", "# note: with the .simulate timer below, delays > 0.1", "from twisted.internet import main, base, posixbase, error, selectreactor POLL_DISCONNECTED =", "If it's still monitored for the other operation, we re-register", "us from ever exiting. log.msg(channel='system', event='iteration', reactor=self) if self.__pending(): self.__iteration(0)", "condition, wrapper) else: return gobject.io_add_watch(source, condition, callback) def _add(self, source,", "some # signal handling which pygtk won't mess with. This", "newer versions if gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit()", "except: why = sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr()", "base, reap processes now in case a process # exited", "function below replicates the pygtk1 functionality. # In addition, pygtk", "pygtk won't mess with. This would # be better done", "def _add(self, source, primary, other, primaryFlag, otherFlag): \"\"\" Add the", "self._remove(writer, self._writes, self._reads, INFLAGS) doIterationTimer = None def doIterationTimeout(self, *args):", "Sockets aren't supported by GTK+'s input_add on Win32. \"\"\" _simtag", "timers return 1 # 1=don't auto-remove the source def simulate(self):", "loop be used (this will be slightly faster but does", "(c) Twisted Matrix Laboratories. # See LICENSE for details. \"\"\"", "intended to be called directly. When installing the reactor, you", "condition & gobject.IO_IN: why = source.doRead() inRead = True if", "for writing. \"\"\" self._remove(writer, self._writes, self._reads, INFLAGS) doIterationTimer = None", "won't mess with. This would # be better done by", "if not source.disconnected: why = source.doWrite() except: why = sys.exc_info()[1]", "method # as the input source. The pygtk2 input_add does", "call it again. if not source.disconnected: why = source.doWrite() except:", "\"\"\" implements(IReactorFDSet) def __init__(self, useGtk=True): self._simtag = None self._reads =", "Let the base class do its thing, but pygtk is", "primaryFlag, otherFlag): \"\"\" Add the given L{FileDescriptor} for monitoring either", "self._writes, OUTFLAGS) def removeWriter(self, writer): \"\"\" Stop monitoring the given", "the tests freeze if we use this # function to", "# glib's iochannel sources won't tell us about any events", "A gtk timeout handle for the next L{simulate} call. \"\"\"", "exception if # gtk.main_level() == 0; however, all the tests", "import installReactor installReactor(reactor) return reactor def portableInstall(useGtk=True): \"\"\" Configure the", "recent versions of python-gtk expose this. python-gtk=2.4.1 # (wrapping glib-2.4.7)", "callback) def _add(self, source, primary, other, primaryFlag, otherFlag): \"\"\" Add", "def portableInstall(useGtk=True): \"\"\" Configure the twisted mainloop to be run", "# exited before the handlers above were installed. _reapAllProcesses() #", "hasattr(gtk, 'main'): gtk.main() else: gtk.mainloop() def simulate(self): \"\"\" Run simulation", "condition) self.simulate() # fire Twisted timers return 1 # 1=don't", "set up some # signal handling which pygtk won't mess", "APIs as usual. The other methods here are not intended", "_reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\", None)", "instances currently monitored for reading. @ivar _writes: A set of", "signal handling which pygtk won't mess with. This would #", "def getReaders(self): \"\"\" Retrieve the list of current L{FileDescriptor} monitored", "believe this may have been # a stupid mistake where", "base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\", None) is", "all the tests freeze if we use this # function", "stupid mistake where I forgot to import gtk here... I", "pygtk before this hack existed. import gobject if hasattr(gobject, \"threads_init\"):", "versions if gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit() def", "be # woken up by the .simulate timer if self.doIterationTimer:", "so go beyond that and set up some # signal", "because lots of IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can", "of data available to read. \"\"\" self._add(reader, self._reads, self._writes, INFLAGS,", "of IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can keep us", "loops and reschedule callbacks. \"\"\" if self._simtag is not None:", "In order to use this support, simply do the following::", "gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit() def run(self, installSignalHandlers=1):", "gobject.io_add_watch(source.fileno(), condition, wrapper) else: return gobject.io_add_watch(source, condition, callback) def _add(self,", "getWriters(self): \"\"\" Retrieve the list of current L{FileDescriptor} monitored for", "Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details.", "Run simulation loops and reschedule callbacks. \"\"\" if self._simtag is", "self._sources = {} posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the glib iteration", "writing. @ivar _simtag: A gtk timeout handle for the next", "by IO, need to cancel the timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer =", "we use this # function to stop the reactor. what", "L{FileDescriptor} instances currently monitored for reading. @ivar _writes: A set", "install(useGtk=True): \"\"\" Configure the twisted mainloop to be run inside", "self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\", None) is not None: signal.siginterrupt(signal.SIGCHLD, False)", "functionality. # In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and", ".simulate timer if self.doIterationTimer: # if woken by IO, need", "Gtk2Reactor(useGtk) from twisted.internet.main import installReactor installReactor(reactor) return reactor def portableInstall(useGtk=True):", "See LICENSE for details. \"\"\" This module provides support for", "maps gtk.input_add to _gobject.io_add_watch, and # g_io_add_watch() takes different condition", "pending events, return if there was something to do #", "the other operation, we delete the previous registration and re-register", "# System Imports import sys, signal from zope.interface import implements", "do its thing, but pygtk is probably # going to", "as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses)) if getattr(signal, \"siginterrupt\",", "Add the given L{FileDescriptor} for monitoring either for reading or", "gtk.events_pending self.__iteration = gtk.main_iteration self.__crash = _our_mainquit self.__run = gtk.main", "in case a process # exited before the handlers above", "the glib event loop or the GTK+ event loop which", "set of L{FileDescriptor} instances currently monitored for reading. @ivar _writes:", "be better done by letting this reactor select a #", "glib event loop or the GTK+ event loop which is", "\"while self.context.pending(): self.context.iteration()\" # idiom because lots of IO (in", "re-register the L{FileDescriptor} for only that operation. \"\"\" if source", "flags, self.callback) primary.add(source) def addReader(self, reader): \"\"\" Add a L{FileDescriptor}", "g_io_add_watch() here in case pygtk fixes this # bug. def", "self.callback) primary.add(source) def addReader(self, reader): \"\"\" Add a L{FileDescriptor} for", "OUTFLAGS) def removeWriter(self, writer): \"\"\" Stop monitoring the given L{FileDescriptor}", "* 1010), self.simulate) def install(useGtk=True): \"\"\" Configure the twisted mainloop", "source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why =", "integration. \"\"\" # System Imports import sys, signal from zope.interface", "source def simulate(self): \"\"\" Run simulation loops and reschedule callbacks.", "input_add function in pygtk1 checks for objects with a #", "reading. \"\"\" self._remove(reader, self._reads, self._writes, OUTFLAGS) def removeWriter(self, writer): \"\"\"", "g_io_add_watch() takes different condition bitfields than # gtk_input_add(). We use", "why = main.CONNECTION_LOST else: try: if condition & gobject.IO_IN: why", "is already monitored for the other operation, we delete the", "else: self._sources.pop(source) def removeReader(self, reader): \"\"\" Stop monitoring the given", "event='iteration', reactor=self) if self.__pending(): self.__iteration(0) return # nothing to do,", "why = source.doRead() inRead = True if not why and", "test_tcp's # ProperlyCloseFilesTestCase) can keep us from ever exiting. log.msg(channel='system',", "\"\"\" # System Imports import sys, signal from zope.interface import", "return self.doIterationTimer = gobject.timeout_add(int(delay * 1000), self.doIterationTimeout) # This will", "from IO or from a timeout. self.__iteration(1) # block #", "main.CONNECTION_LOST else: try: if condition & gobject.IO_IN: why = source.doRead()", "gtk timeout handle for the next L{simulate} call. \"\"\" implements(IReactorFDSet)", "be called directly. When installing the reactor, you can choose", "event loop be used (this will be slightly faster but", "XXX: gtk.main_quit() (which is used for crash()) raises an exception", "mainloop to be run inside the gtk mainloop. @param useGtk:", "* 1000), self.doIterationTimeout) # This will either wake up from", "A dictionary mapping L{FileDescriptor} instances to gtk watch handles. @ivar", "choose whether to use the glib event loop or the", "this. The # function below replicates the pygtk1 functionality. #", "1000), self.doIterationTimeout) # This will either wake up from IO", "def _our_mainquit(): # XXX: gtk.main_quit() (which is used for crash())", "as the input source. The pygtk2 input_add does not do", "source.doWrite() except: why = sys.exc_info()[1] log.msg('Error In %s' % source)", "done by letting this reactor select a # different implementation", "this for py2exe import pygtk pygtk.require('2.0') except (ImportError, AttributeError): pass", "from twisted.python import log, runtime, failure from twisted.python.compat import set", "to be run inside the gtk mainloop. \"\"\" reactor =", "hasattr(source, 'fileno'): # handle python objects def wrapper(source, condition, real_s=source,", "source) log.deferr() if why: self._disconnectSelectable(source, why, inRead) def callback(self, source,", "min(self.timeout(), 0.1) if timeout is None: timeout = 0.1 #", "& gobject.IO_IN): if source in self._reads: why = main.CONNECTION_DONE inRead", "Windows. Sockets aren't supported by GTK+'s input_add on Win32. \"\"\"", "return flags = primaryFlag if source in other: gobject.source_remove(self._sources[source]) flags", "at least, we could fall # back to our extension", "== 0: return # shouldn't delay, so just return self.doIterationTimer", "self._reads = set() self._writes = set() self._sources = {} posixbase.PosixReactorBase.__init__(self)", "return 0 # auto-remove def doIteration(self, delay): # flush some", "PortableGtkReactor() from twisted.internet.main import installReactor installReactor(reactor) return reactor if runtime.platform.getType()", "this # function to stop the reactor. what gives? (I", "return self._removeAll(self._reads, self._writes) def _remove(self, source, primary, other, flags): \"\"\"", "is None: timeout = 0.1 # grumble self._simtag = gobject.timeout_add(int(timeout", "we're using pygtk before this hack existed. import gobject if", "writing. \"\"\" return list(self._writes) def removeAll(self): \"\"\" Remove monitoring for", "dictionary mapping L{FileDescriptor} instances to gtk watch handles. @ivar _reads:", "INFLAGS) doIterationTimer = None def doIterationTimeout(self, *args): self.doIterationTimer = None", "Twisted timers return 1 # 1=don't auto-remove the source def", "Configure the twisted mainloop to be run inside the gtk", "= self.loop.run else: import gtk self.__pending = gtk.events_pending self.__iteration =", "nothing to do, must delay if delay == 0: return", "# if doRead caused connectionLost, don't call doWrite # if", "= min(self.timeout(), 0.1) if timeout is None: timeout = 0.1", "instances currently monitored for writing. @ivar _simtag: A gtk timeout", "return gobject.io_add_watch(source, condition, callback) def _add(self, source, primary, other, primaryFlag,", "'fileno' method and, if present, uses the result of that", "set() self._writes = set() self._sources = {} posixbase.PosixReactorBase.__init__(self) # pre", "the other operation, we re-register the L{FileDescriptor} for only that", "the poll() # call. INFLAGS = gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS", "takes different condition bitfields than # gtk_input_add(). We use g_io_add_watch()", "for crash()) raises an exception if # gtk.main_level() == 0;", "twisted.internet.main import installReactor installReactor(reactor) return reactor def portableInstall(useGtk=True): \"\"\" Configure", "# function below replicates the pygtk1 functionality. # In addition,", "in other: self._sources[source] = self.input_add( source, flags, self.callback) else: self._sources.pop(source)", "# woken up by the .simulate timer if self.doIterationTimer: #", "# See LICENSE for details. \"\"\" This module provides support", "use this # function to stop the reactor. what gives?", "# Twisted Imports from twisted.python import log, runtime, failure from", "shouldn't delay, so just return self.doIterationTimer = gobject.timeout_add(int(delay * 1000),", "if woken by IO, need to cancel the timer gobject.source_remove(self.doIterationTimer)", "self.__run = self.loop.run else: import gtk self.__pending = gtk.events_pending self.__iteration", "# mainloop is deprecated in newer versions if hasattr(gtk, 'main'):", "for either reading or writing. If it's still monitored for", "self._doReadOrWrite, source, condition) self.simulate() # fire Twisted timers return 1", "deprecated in newer versions if gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit()", "to do, must delay if delay == 0: return #", "up some # signal handling which pygtk won't mess with.", "if those events aren't sensible inputs to the poll() #", ">= (2, 3, 91) and not useGtk: self.context = gobject.main_context_default()", "GUI). \"\"\" reactor = Gtk2Reactor(useGtk) from twisted.internet.main import installReactor installReactor(reactor)", "3, 91) and not useGtk: self.context = gobject.main_context_default() self.__pending =", "order to use this support, simply do the following:: |", "source in other: gobject.source_remove(self._sources[source]) flags |= otherFlag self._sources[source] = self.input_add(source,", "will either wake up from IO or from a timeout.", "was something to do # don't use the usual \"while", "(I believe this may have been # a stupid mistake", "@ivar _sources: A dictionary mapping L{FileDescriptor} instances to gtk watch", "following:: | from twisted.internet import gtk2reactor | gtk2reactor.install() Then use", "self._writes, INFLAGS, OUTFLAGS) def addWriter(self, writer): \"\"\" Add a L{FileDescriptor}", "= source.doWrite() except: why = sys.exc_info()[1] log.msg('Error In %s' %", "In %s' % source) log.deferr() if why: self._disconnectSelectable(source, why, inRead)", "hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit() def run(self, installSignalHandlers=1): import gtk", "to do # don't use the usual \"while self.context.pending(): self.context.iteration()\"", "\"\"\" Stop monitoring the given L{FileDescriptor} for reading. \"\"\" self._remove(reader,", "base, posixbase, error, selectreactor POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR |", "'main'): gtk.main() else: gtk.mainloop() def simulate(self): \"\"\" Run simulation loops", "would # be better done by letting this reactor select", "if hasattr(source, 'fileno'): # handle python objects def wrapper(source, condition,", "source, primary, other, primaryFlag, otherFlag): \"\"\" Add the given L{FileDescriptor}", "-*- test-case-name: twisted.internet.test -*- # Copyright (c) Twisted Matrix Laboratories.", "gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if timeout is None:", "Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event loop reactor. @ivar _sources: A dictionary", "hasattr(gobject, \"threads_init\"): # recent versions of python-gtk expose this. python-gtk=2.4.1", "breaking thread and signal support. if getattr(gobject, \"pygtk_version\", ()) >=", "signal from zope.interface import implements try: if not hasattr(sys, 'frozen'):", "signal.siginterrupt(signal.SIGCHLD, False) # Like the base, reap processes now in", "> 0.1 will always be # woken up by the", "reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda *a: self.callFromThread(_reapAllProcesses)) if getattr(signal,", "\"\"\" if source not in primary: return gobject.source_remove(self._sources[source]) primary.remove(source) if", "self._remove(reader, self._reads, self._writes, OUTFLAGS) def removeWriter(self, writer): \"\"\" Stop monitoring", "if runtime.platform.getType() != 'posix': install = portableInstall __all__ = ['install']", "but does not support GUI). \"\"\" reactor = Gtk2Reactor(useGtk) from", "gtk.main() else: gtk.mainloop() def simulate(self): \"\"\" Run simulation loops and", "not (condition & gobject.IO_IN): if source in self._reads: why =", "monitored for writing. @ivar _simtag: A gtk timeout handle for", "source, flags, self.callback) else: self._sources.pop(source) def removeReader(self, reader): \"\"\" Stop", "doRead is doWrite, don't call it again. if not source.disconnected:", "def addWriter(self, writer): \"\"\" Add a L{FileDescriptor} for monitoring ability", "monitoring the given L{FileDescriptor} for writing. \"\"\" self._remove(writer, self._writes, self._reads,", "but pygtk is probably # going to stomp on us", "\"\"\" _simtag = None def crash(self): selectreactor.SelectReactor.crash(self) import gtk #", "'posix': def _handleSignals(self): # Let the base class do its", "# asked for, even if those events aren't sensible inputs", "why = main.CONNECTION_DONE inRead = True else: why = main.CONNECTION_LOST", "= source.doRead() inRead = True if not why and condition", "those events aren't sensible inputs to the poll() # call.", "self._reads, INFLAGS) doIterationTimer = None def doIterationTimeout(self, *args): self.doIterationTimer =", "self.loop.quit self.__run = self.loop.run else: import gtk self.__pending = gtk.events_pending", "source.disconnected: why = source.doWrite() except: why = sys.exc_info()[1] log.msg('Error In", "self.simulate) def install(useGtk=True): \"\"\" Configure the twisted mainloop to be", "I will remove this # comment if the tests pass)", "reader): \"\"\" Stop monitoring the given L{FileDescriptor} for reading. \"\"\"", "(this will be slightly faster but does not support GUI).", "twisted.internet APIs as usual. The other methods here are not", "thread and signal support. if getattr(gobject, \"pygtk_version\", ()) >= (2,", "timer below, delays > 0.1 will always be # woken", "event loop or the GTK+ event loop which is based", "L{FileDescriptor} monitored for reading. \"\"\" return list(self._reads) def getWriters(self): \"\"\"", "either reading or writing. If it's still monitored for the", "gives? (I believe this may have been # a stupid", "twisted.python import log, runtime, failure from twisted.python.compat import set from", "@ivar _simtag: A gtk timeout handle for the next L{simulate}", "with. This would # be better done by letting this", "reactor = PortableGtkReactor() from twisted.internet.main import installReactor installReactor(reactor) return reactor", "we re-register the L{FileDescriptor} for only that operation. \"\"\" if", "self.__iteration(1) # block # note: with the .simulate timer below,", "sys, signal from zope.interface import implements try: if not hasattr(sys,", "we haven't # asked for, even if those events aren't", "gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED def _our_mainquit():", "L{simulate} call. \"\"\" implements(IReactorFDSet) def __init__(self, useGtk=True): self._simtag = None", "INFLAGS) def getReaders(self): \"\"\" Retrieve the list of current L{FileDescriptor}", "process # exited before the handlers above were installed. _reapAllProcesses()", "by GTK+'s input_add on Win32. \"\"\" _simtag = None def", "freeze if we use this # function to stop the", "for reading. \"\"\" return list(self._reads) def getWriters(self): \"\"\" Retrieve the", "why = sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr() if", "self.loop = gobject.MainLoop() self.__crash = self.loop.quit self.__run = self.loop.run else:", "\"\"\" Remove monitoring the given L{FileDescriptor} for either reading or", "gobject.io_add_watch(source, condition, callback) def _add(self, source, primary, other, primaryFlag, otherFlag):", "want to check this for py2exe import pygtk pygtk.require('2.0') except", "| POLL_DISCONNECTED OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED def _our_mainquit(): #", "gtk.main_level() == 0; however, all the tests freeze if we", "1=don't auto-remove the source def simulate(self): \"\"\" Run simulation loops", "poll() # call. INFLAGS = gobject.IO_IN | POLL_DISCONNECTED OUTFLAGS =", "rather than GTK+ event loop be used (this will be", "gtk if gtk.main_level(): gtk.main_quit() class Gtk2Reactor(posixbase.PosixReactorBase): \"\"\" GTK+-2 event loop", "installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) if self._started: self.__run() def _doReadOrWrite(self, source,", "that we haven't # asked for, even if those events", "self._writes, self._reads, INFLAGS) doIterationTimer = None def doIterationTimeout(self, *args): self.doIterationTimer", "be run inside the gtk mainloop. @param useGtk: should glib", "up from IO or from a timeout. self.__iteration(1) # block", "have been # a stupid mistake where I forgot to", "writing. \"\"\" if source in primary: return flags = primaryFlag", "aren't supported by GTK+'s input_add on Win32. \"\"\" _simtag =", "# handle python objects def wrapper(source, condition, real_s=source, real_cb=callback): return", "# flush some pending events, return if there was something", "'main_quit'): gtk.main_quit() else: gtk.mainquit() def run(self, installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers)", "from zope.interface import implements try: if not hasattr(sys, 'frozen'): #", "re-register it for both reading and writing. \"\"\" if source", "doIterationTimeout(self, *args): self.doIterationTimer = None return 0 # auto-remove def", "don't call doWrite # if doRead is doWrite, don't call", "with the glib/gtk2 mainloop. In order to use this support,", "its thing, but pygtk is probably # going to stomp", "else: gtk.mainquit() def run(self, installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate)", "_writes: A set of L{FileDescriptor} instances currently monitored for writing.", "import gtk # mainquit is deprecated in newer versions if", "this may have been # a stupid mistake where I", "of current L{FileDescriptor} monitored for reading. \"\"\" return list(self._reads) def", "IReactorFDSet from twisted.internet import main, base, posixbase, error, selectreactor POLL_DISCONNECTED", "fall # back to our extension module. See #4286. from", "self.context.pending self.__iteration = self.context.iteration self.loop = gobject.MainLoop() self.__crash = self.loop.quit", "versions if hasattr(gtk, 'main'): gtk.main() else: gtk.mainloop() def simulate(self): \"\"\"", "watch handles. @ivar _reads: A set of L{FileDescriptor} instances currently", "log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate() # fire Twisted timers return", "methods here are not intended to be called directly. When", "= main.CONNECTION_DONE inRead = True else: why = main.CONNECTION_LOST else:", "reactor if runtime.platform.getType() != 'posix': install = portableInstall __all__ =", "fire Twisted timers return 1 # 1=don't auto-remove the source", "exited before the handlers above were installed. _reapAllProcesses() # The", "= self.context.pending self.__iteration = self.context.iteration self.loop = gobject.MainLoop() self.__crash =", "the GTK+ event loop which is based on it but", "not intended to be called directly. When installing the reactor,", "L{FileDescriptor} for only that operation. \"\"\" if source not in", "#4286. from twisted.internet.process import reapAllProcesses as _reapAllProcesses base._SignalReactorMixin._handleSignals(self) signal.signal(signal.SIGCHLD, lambda", "import gtk self.__pending = gtk.events_pending self.__iteration = gtk.main_iteration self.__crash =", "# auto-remove def doIteration(self, delay): # flush some pending events,", "in primary: return gobject.source_remove(self._sources[source]) primary.remove(source) if source in other: self._sources[source]", "condition) return gobject.io_add_watch(source.fileno(), condition, wrapper) else: return gobject.io_add_watch(source, condition, callback)", "call. \"\"\" implements(IReactorFDSet) def __init__(self, useGtk=True): self._simtag = None self._reads", "= _our_mainquit self.__run = gtk.main if runtime.platformType == 'posix': def", "and not useGtk: self.context = gobject.main_context_default() self.__pending = self.context.pending self.__iteration", "if self._started: self.__run() def _doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()),", "installReactor(reactor) return reactor if runtime.platform.getType() != 'posix': install = portableInstall", "self.context.iteration self.loop = gobject.MainLoop() self.__crash = self.loop.quit self.__run = self.loop.run", "for objects with a # 'fileno' method and, if present,", "wake up from IO or from a timeout. self.__iteration(1) #", "class do its thing, but pygtk is probably # going", "for the next L{simulate} call. \"\"\" implements(IReactorFDSet) def __init__(self, useGtk=True):", "installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) # mainloop is deprecated", "wrapper(source, condition, real_s=source, real_cb=callback): return real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(), condition,", "self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that works on Windows. Sockets", "real_s=source, real_cb=callback): return real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(), condition, wrapper) else:", "in primary: return flags = primaryFlag if source in other:", "to check this for py2exe import pygtk pygtk.require('2.0') except (ImportError,", "= self.input_add(source, flags, self.callback) primary.add(source) def addReader(self, reader): \"\"\" Add", "on us so go beyond that and set up some", "Then use twisted.internet APIs as usual. The other methods here", "py2exe import pygtk pygtk.require('2.0') except (ImportError, AttributeError): pass # maybe", "connectionLost, don't call doWrite # if doRead is doWrite, don't", "# 1=don't auto-remove the source def simulate(self): \"\"\" Run simulation", "gtk here... I will remove this # comment if the", "either wake up from IO or from a timeout. self.__iteration(1)", "why: self._disconnectSelectable(source, why, inRead) def callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite,", "gtk.main_quit() else: gtk.mainquit() def run(self, installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0,", "# g_io_add_watch() takes different condition bitfields than # gtk_input_add(). We", "gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) # mainloop is deprecated in newer", "interact with the glib/gtk2 mainloop. In order to use this", "going to stomp on us so go beyond that and", "def callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate() #", "def addReader(self, reader): \"\"\" Add a L{FileDescriptor} for monitoring of", "runtime, failure from twisted.python.compat import set from twisted.internet.interfaces import IReactorFDSet", "module provides support for Twisted to interact with the glib/gtk2", "reading. \"\"\" return list(self._reads) def getWriters(self): \"\"\" Retrieve the list", "useGtk: self.context = gobject.main_context_default() self.__pending = self.context.pending self.__iteration = self.context.iteration", "all registered L{FileDescriptor}s. \"\"\" return self._removeAll(self._reads, self._writes) def _remove(self, source,", "import installReactor installReactor(reactor) return reactor if runtime.platform.getType() != 'posix': install", "| gtk2reactor.install() Then use twisted.internet APIs as usual. The other", "least, we could fall # back to our extension module.", "reactor=self) if self.__pending(): self.__iteration(0) return # nothing to do, must", "\"\"\" return self._removeAll(self._reads, self._writes) def _remove(self, source, primary, other, flags):", "our extension module. See #4286. from twisted.internet.process import reapAllProcesses as", "the base class do its thing, but pygtk is probably", "and # g_io_add_watch() takes different condition bitfields than # gtk_input_add().", "self.simulate) if self._started: self.__run() def _doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone:", "ever exiting. log.msg(channel='system', event='iteration', reactor=self) if self.__pending(): self.__iteration(0) return #", "delete the previous registration and re-register it for both reading", "so just return self.doIterationTimer = gobject.timeout_add(int(delay * 1000), self.doIterationTimeout) #", "Stop monitoring the given L{FileDescriptor} for writing. \"\"\" self._remove(writer, self._writes,", "run(self, installSignalHandlers=1): import gtk self.startRunning(installSignalHandlers=installSignalHandlers) gobject.timeout_add(0, self.simulate) # mainloop is", "for monitoring ability to write data. \"\"\" self._add(writer, self._writes, self._reads,", "timer gobject.source_remove(self.doIterationTimer) self.doIterationTimer = None def crash(self): posixbase.PosixReactorBase.crash(self) self.__crash() def", "selectreactor.SelectReactor.crash(self) import gtk # mainquit is deprecated in newer versions", "existed. import gobject if hasattr(gobject, \"threads_init\"): # recent versions of", "= gtk.main if runtime.platformType == 'posix': def _handleSignals(self): # Let", "source in self._reads: why = main.CONNECTION_DONE inRead = True else:", "the given L{FileDescriptor} for writing. \"\"\" self._remove(writer, self._writes, self._reads, INFLAGS)", "removeWriter(self, writer): \"\"\" Stop monitoring the given L{FileDescriptor} for writing.", "write data. \"\"\" self._add(writer, self._writes, self._reads, OUTFLAGS, INFLAGS) def getReaders(self):", "the base, reap processes now in case a process #", "some pending events, return if there was something to do", "condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why = None", "mainloop functions didn't release # global interpreter lock, thus breaking", "for monitoring either for reading or writing. If the file", "1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that works on Windows.", "block # note: with the .simulate timer below, delays >", "gtk.mainloop() def simulate(self): \"\"\" Run simulation loops and reschedule callbacks.", "if self._simtag is not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(),", "are not intended to be called directly. When installing the", "writing. If the file is already monitored for the other", "condition & gobject.IO_OUT: # if doRead caused connectionLost, don't call", "Win32. \"\"\" _simtag = None def crash(self): selectreactor.SelectReactor.crash(self) import gtk", "| POLL_DISCONNECTED def _our_mainquit(): # XXX: gtk.main_quit() (which is used", "the given L{FileDescriptor} for reading. \"\"\" self._remove(reader, self._reads, self._writes, OUTFLAGS)", "mainloop to be run inside the gtk mainloop. \"\"\" reactor", "still monitored for the other operation, we re-register the L{FileDescriptor}", "something to do # don't use the usual \"while self.context.pending():", "support. if getattr(gobject, \"pygtk_version\", ()) >= (2, 3, 91) and", "timeout = min(self.timeout(), 0.1) if timeout is None: timeout =", "source. The pygtk2 input_add does not do this. The #", ".simulate timer below, delays > 0.1 will always be #", "by the .simulate timer if self.doIterationTimer: # if woken by", "\"\"\" Reactor that works on Windows. Sockets aren't supported by", "available to read. \"\"\" self._add(reader, self._reads, self._writes, INFLAGS, OUTFLAGS) def", "return list(self._reads) def getWriters(self): \"\"\" Retrieve the list of current", "for reading. \"\"\" self._remove(reader, self._reads, self._writes, OUTFLAGS) def removeWriter(self, writer):", "reading or writing. If it's still monitored for the other", "zope.interface import implements try: if not hasattr(sys, 'frozen'): # Don't", "None: signal.siginterrupt(signal.SIGCHLD, False) # Like the base, reap processes now", "def removeAll(self): \"\"\" Remove monitoring for all registered L{FileDescriptor}s. \"\"\"", "and re-register it for both reading and writing. \"\"\" if", "if condition & POLL_DISCONNECTED and not (condition & gobject.IO_IN): if", "set from twisted.internet.interfaces import IReactorFDSet from twisted.internet import main, base,", "reading. @ivar _writes: A set of L{FileDescriptor} instances currently monitored", "from twisted.internet.interfaces import IReactorFDSet from twisted.internet import main, base, posixbase,", "L{FileDescriptor} instances currently monitored for writing. @ivar _simtag: A gtk", "a L{FileDescriptor} for monitoring of data available to read. \"\"\"", "return real_cb(real_s, condition) return gobject.io_add_watch(source.fileno(), condition, wrapper) else: return gobject.io_add_watch(source,", "\"\"\" if self._simtag is not None: gobject.source_remove(self._simtag) self.iterate() timeout =", "monitored for writing. \"\"\" return list(self._writes) def removeAll(self): \"\"\" Remove", "# going to stomp on us so go beyond that", "failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why = None inRead = False", "gtk watch handles. @ivar _reads: A set of L{FileDescriptor} instances", "monitored for reading. @ivar _writes: A set of L{FileDescriptor} instances", "source in primary: return flags = primaryFlag if source in", "forgot to import gtk here... I will remove this #", "letting this reactor select a # different implementation of installHandler", "= PortableGtkReactor() from twisted.internet.main import installReactor installReactor(reactor) return reactor if", "self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if timeout is None: timeout", "wrapper) else: return gobject.io_add_watch(source, condition, callback) def _add(self, source, primary,", "sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr() if why: self._disconnectSelectable(source,", "the following:: | from twisted.internet import gtk2reactor | gtk2reactor.install() Then", "pre 2.3.91 the glib iteration and mainloop functions didn't release", "gobject.timeout_add(int(timeout * 1010), self.simulate) class PortableGtkReactor(selectreactor.SelectReactor): \"\"\" Reactor that works", "if present, uses the result of that method # as", "gobject.threads_init() # Twisted Imports from twisted.python import log, runtime, failure", "= {} posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the glib iteration and", "or from a timeout. self.__iteration(1) # block # note: with", "\"\"\" reactor = PortableGtkReactor() from twisted.internet.main import installReactor installReactor(reactor) return", "run inside the gtk mainloop. \"\"\" reactor = PortableGtkReactor() from", "if the tests pass) import gtk if gtk.main_level(): gtk.main_quit() class", "{} posixbase.PosixReactorBase.__init__(self) # pre 2.3.91 the glib iteration and mainloop", "python-gtk=2.4.1 # (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping # glib-2.2.3) does", "flags = primaryFlag if source in other: gobject.source_remove(self._sources[source]) flags |=", "here... I will remove this # comment if the tests", "of current L{FileDescriptor} monitored for writing. \"\"\" return list(self._writes) def", "glib-2.2.3) does not. gobject.threads_init() # Twisted Imports from twisted.python import", "\"\"\" self._add(writer, self._writes, self._reads, OUTFLAGS, INFLAGS) def getReaders(self): \"\"\" Retrieve", "None self._reads = set() self._writes = set() self._sources = {}", "useGtk=True): self._simtag = None self._reads = set() self._writes = set()", "otherFlag self._sources[source] = self.input_add(source, flags, self.callback) primary.add(source) def addReader(self, reader):", "failure from twisted.python.compat import set from twisted.internet.interfaces import IReactorFDSet from", "delays > 0.1 will always be # woken up by", "_reapAllProcesses() # The input_add function in pygtk1 checks for objects", "is deprecated in newer versions if gtk.main_level(): if hasattr(gtk, 'main_quit'):" ]
[ "models \"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes i =", "list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes i = np.select( [ (wide_close.index >=", "cores - Import Data \"\"\" import pandas as pd import", "f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random Forest \"\"\" rf = RandomForestRegressor(n_jobs=-1)", "in assets: print(\"Asset\", a) x_steps, y_steps = 60, [1, 16]", "and store in array \"\"\" # Production \"\"\" Steps: -", "test and test indices. Importantly, this needs to cover all", "\"model_files\" mkdir \"model_files/linear_regression\" for a in assets: print(\"Asset\", a) x_steps,", "[1, 15] col_in, col_out = \"1\", \"1\" train_x, test_x, train_y,", "as pd import numpy as np import tensorflow as tf", "tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM, ConvLSTM2D, Flatten", "from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.ensemble", "import multiprocessing import random import os from tensorflow.keras.models import Sequential", "Dense, LSTM, ConvLSTM2D, Flatten from sklearn.preprocessing import StandardScaler from sklearn.linear_model", "default = \"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a in", "mod.eval import evaluate_regression, evaluate_up_down cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder =", "train_x, test_x, train_y, test_y, time_d = preprocess(data_in = wide_close, col_in,", "\"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder + \"/asset_details.csv\") assets = [str(i) for", "assets = [str(i) for i in asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\"", "\"\\n\\n\") indexes_d = {} for s in indexes[\"set\"].unique(): indexes_d[s] =", "log_return, log_return_np, preprocess from mod.model import return_pred from mod.eval import", "i in asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\" close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"]", "\"\"\" Steps: - Get train, val test and test indices.", "dump, load from mod.prep import log_return, log_return_np, preprocess from mod.model", "= pd.read_csv(root_folder + \"/asset_details.csv\") assets = [str(i) for i in", "step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred", "= return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model 16 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true,", "RandomForestRegressor from joblib import dump, load from mod.prep import log_return,", "sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor from joblib import", "Setup tf on multiple cores - Import Data \"\"\" import", "wide_target = pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder + \"/asset_details.csv\")", "{} for s in indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"] == s]", "dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random Forest \"\"\" rf =", "true, pred = return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred)", "sns from time import time import multiprocessing import random import", "= 60, [1, 15] col_in, col_out = \"1\", \"1\" train_x,", "though not all assets exist) for the whole time period.", "= a, a train_x, test_x, train_y, test_y, time_d = preprocess(wide_close,", "log_return_np, preprocess from mod.model import return_pred from mod.eval import evaluate_regression,", "evaluate_regression(true, pred) evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\")", "tf import seaborn as sns from time import time import", "store components seperately process: - first, get rolling values for", "then, predict 1 and 15 gaps and store in array", "ConvLSTM2D, Flatten from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression", "16 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\")", "for each timestamp - then, predict 1 and 15 gaps", "Production \"\"\" Steps: - Get train, val test and test", "# 15 step lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1))", "in assets: print(\"asset\", a) filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts()", "true, pred = return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model 16 Metrics\") evaluate_regression(true,", "time import time import multiprocessing import random import os from", "\"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d = {} for s in indexes[\"set\"].unique():", "= return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) # 15", "y_steps = 60, [1, 16] cols_in, cols_out = a, a", "- Build models \"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes", "= filt.value_counts() df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d =", "import evaluate_regression, evaluate_up_down cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\"", "\"\"\" Linear Regression \"\"\" x_steps, y_steps = 60, [1, 15]", "= pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d = {} for s", "test_x, train_y, test_y, time_d = preprocess(data_in = wide_close, col_in, col_out,", "and 15 gaps and store in array \"\"\" # Production", "indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a in assets: print(\"asset\", a)", "(even though not all assets exist) for the whole time", "<= (len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7)) & (wide_close.index <= (len(wide_close)*0.8)) ],", "\"\"\" close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan)", "whole time period. - Build models \"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str))", "get rolling values for each timestamp - then, predict 1", "wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression", "\"\"\" calculate and store components seperately process: - first, get", "store in array \"\"\" # Production \"\"\" Steps: - Get", "col_out = \"1\", \"1\" train_x, test_x, train_y, test_y, time_d =", "pred = return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) #", "multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\" wide_close = pd.read_csv(root_folder + \"/working/wide_close.csv\")", "exist) for the whole time period. - Build models \"\"\"", "= preprocess(data_in = wide_close, col_in, col_out, time_col=\"time\", x_steps, y_steps) #", "train_x, test_x, train_y, test_y, time_d = preprocess(wide_close, cols_in, cols_out, \"time\",", "Get train, val test and test indices. Importantly, this needs", "s] mkdir \"model_files\" mkdir \"model_files/linear_regression\" for a in assets: print(\"Asset\",", "as np import tensorflow as tf import seaborn as sns", "StandardScaler from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor from", "evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random", "time_col=\"time\", x_steps, y_steps) # 1 step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1,", "from joblib import dump, load from mod.prep import log_return, log_return_np,", "= RandomForestRegressor(n_jobs=-1) # start = time.time() rf.fit(train_x.reshape(-1, x_steps), train_y.reshape(-1)) #", "], [\"train\", \"val\"], default = \"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i})", "LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,0,:],", "= indexes[\"time\"][indexes[\"set\"] == s] mkdir \"model_files\" mkdir \"model_files/linear_regression\" for a", "x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true,", "Regression \"\"\" x_steps, y_steps = 60, [1, 15] col_in, col_out", "process: - first, get rolling values for each timestamp -", "all assets (even though not all assets exist) for the", "the whole time period. - Build models \"\"\" assets =", "as sns from time import time import multiprocessing import random", "wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression \"\"\" x_steps, y_steps", "15 gaps and store in array \"\"\" # Production \"\"\"", "time period. - Build models \"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str)) #", "test_y[:,1,:], lr_16) print(\"Model 16 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) dump(lr_1,", "mkdir \"model_files\" mkdir \"model_files/linear_regression\" for a in assets: print(\"Asset\", a)", "\"\"\" Setup: - Import Libraries - Setup tf on multiple", "Data \"\"\" import pandas as pd import numpy as np", "seaborn as sns from time import time import multiprocessing import", "each timestamp - then, predict 1 and 15 gaps and", "+ \"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder", "lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred =", "timestamp - then, predict 1 and 15 gaps and store", "# Get indexes i = np.select( [ (wide_close.index >= 0)", "\"val\"], default = \"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a", "lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) \"\"\" calculate and store components", "from mod.prep import log_return, log_return_np, preprocess from mod.model import return_pred", "\"data\" wide_close = pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder +", "import Dense, LSTM, ConvLSTM2D, Flatten from sklearn.preprocessing import StandardScaler from", "Steps: - Get train, val test and test indices. Importantly,", "pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random Forest", "1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model 1 Metrics\")", "# 16 step lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1))", "pred) \"\"\" calculate and store components seperately process: - first,", "as tf import seaborn as sns from time import time", "return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) # 15 step", "in asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\" close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"] =", "test_y[:,0,:], lr_1) print(\"Model 1 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) #", "col_in, col_out, time_col=\"time\", x_steps, y_steps) # 1 step lr_1 =", "& (wide_close.index <= (len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7)) & (wide_close.index <=", "df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d = {} for", "time import multiprocessing import random import os from tensorflow.keras.models import", "<= (len(wide_close)*0.8)) ], [\"train\", \"val\"], default = \"test\") indexes =", "for a in assets: print(\"Asset\", a) x_steps, y_steps = 60,", "1 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) # 16 step lr_16", "# start = time.time() rf.fit(train_x.reshape(-1, x_steps), train_y.reshape(-1)) # print(\"Took:\", round(start-time.time()))", "\"model_files/linear_regression\" for a in assets: print(\"Asset\", a) x_steps, y_steps =", "dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random Forest \"\"\"", "= indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts() df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df,", "in array \"\"\" # Production \"\"\" Steps: - Get train,", "(wide_close.index > (len(wide_close)*0.7)) & (wide_close.index <= (len(wide_close)*0.8)) ], [\"train\", \"val\"],", "evaluate_up_down(true, pred) # 16 step lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps),", "gaps and store in array \"\"\" # Production \"\"\" Steps:", "pred = return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model 16 Metrics\") evaluate_regression(true, pred)", "in indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"] == s] mkdir \"model_files\" mkdir", "components seperately process: - first, get rolling values for each", "test_y[:,0,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) # 15 step lr_15", "= wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression \"\"\" x_steps,", "(len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7)) & (wide_close.index <= (len(wide_close)*0.8)) ], [\"train\",", "assets: print(\"asset\", a) filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts() df", "Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d,", "\"\"\" Random Forest \"\"\" rf = RandomForestRegressor(n_jobs=-1) # start =", "- Setup tf on multiple cores - Import Data \"\"\"", "= [str(i) for i in asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\" close_returns", "(wide_close.index <= (len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7)) & (wide_close.index <= (len(wide_close)*0.8))", "= return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model 1 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true,", "[ (wide_close.index >= 0) & (wide_close.index <= (len(wide_close)*0.7)), (wide_close.index >", "test_x, train_y, test_y, time_d = preprocess(wide_close, cols_in, cols_out, \"time\", x_steps,", "train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model 1", "[str(i) for i in asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\" close_returns =", "values for each timestamp - then, predict 1 and 15", "sklearn.ensemble import RandomForestRegressor from joblib import dump, load from mod.prep", "root_folder = \"data\" wide_close = pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target =", "print(df, \"\\n\\n\") indexes_d = {} for s in indexes[\"set\"].unique(): indexes_d[s]", "lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_1)", "= pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a in assets: print(\"asset\", a) filt", "1 and 15 gaps and store in array \"\"\" #", "indexes i = np.select( [ (wide_close.index >= 0) & (wide_close.index", "= \"data\" wide_close = pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder", "preprocess(data_in = wide_close, col_in, col_out, time_col=\"time\", x_steps, y_steps) # 1", "i = np.select( [ (wide_close.index >= 0) & (wide_close.index <=", "\"1\", \"1\" train_x, test_x, train_y, test_y, time_d = preprocess(data_in =", "from mod.eval import evaluate_regression, evaluate_up_down cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder", "evaluate_regression(true, pred) evaluate_up_down(true, pred) \"\"\" calculate and store components seperately", "Importantly, this needs to cover all assets (even though not", "= 60, [1, 16] cols_in, cols_out = a, a train_x,", "16] cols_in, cols_out = a, a train_x, test_x, train_y, test_y,", "0) & (wide_close.index <= (len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7)) & (wide_close.index", "+ \"/asset_details.csv\") assets = [str(i) for i in asset_details[\"Asset_ID\"]] \"\"\"", "pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a in assets: print(\"asset\", a) filt =", "train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true, pred)", "pandas as pd import numpy as np import tensorflow as", "evaluate_regression(true, pred) evaluate_up_down(true, pred) # 15 step lr_15 = LinearRegression()", "indexes_d = {} for s in indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"]", "= LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x,", "> (len(wide_close)*0.7)) & (wide_close.index <= (len(wide_close)*0.8)) ], [\"train\", \"val\"], default", "multiprocessing import random import os from tensorflow.keras.models import Sequential from", "\"/asset_details.csv\") assets = [str(i) for i in asset_details[\"Asset_ID\"]] \"\"\" Preprocess", "cover all assets (even though not all assets exist) for", "return_pred from mod.eval import evaluate_regression, evaluate_up_down cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1)", "import numpy as np import tensorflow as tf import seaborn", "Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) # 16 step lr_16 =", "print(\"Asset\", a) x_steps, y_steps = 60, [1, 16] cols_in, cols_out", "indexes_d[s] = indexes[\"time\"][indexes[\"set\"] == s] mkdir \"model_files\" mkdir \"model_files/linear_regression\" for", "cols_out = a, a train_x, test_x, train_y, test_y, time_d =", "mod.prep import log_return, log_return_np, preprocess from mod.model import return_pred from", "1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true,", "from tensorflow.keras.layers import Dense, LSTM, ConvLSTM2D, Flatten from sklearn.preprocessing import", "numpy as np import tensorflow as tf import seaborn as", "random import os from tensorflow.keras.models import Sequential from tensorflow.keras.layers import", "import LinearRegression from sklearn.ensemble import RandomForestRegressor from joblib import dump,", "a in assets: print(\"Asset\", a) x_steps, y_steps = 60, [1,", "from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM, ConvLSTM2D,", "evaluate_regression(true, pred) evaluate_up_down(true, pred) # 16 step lr_16 = LinearRegression()", "pred) # 15 step lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1,", "train_y, test_y, time_d = preprocess(data_in = wide_close, col_in, col_out, time_col=\"time\",", "Linear Regression \"\"\" x_steps, y_steps = 60, [1, 15] col_in,", "LSTM, ConvLSTM2D, Flatten from sklearn.preprocessing import StandardScaler from sklearn.linear_model import", "pred = return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model 1 Metrics\") evaluate_regression(true, pred)", "train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model 16", "np import tensorflow as tf import seaborn as sns from", "== s] mkdir \"model_files\" mkdir \"model_files/linear_regression\" for a in assets:", "print(\"Model 1 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) # 16 step", "s in indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"] == s] mkdir \"model_files\"", "predict 1 and 15 gaps and store in array \"\"\"", "Flatten from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from", "mod.model import return_pred from mod.eval import evaluate_regression, evaluate_up_down cores =", "a, a train_x, test_x, train_y, test_y, time_d = preprocess(wide_close, cols_in,", "close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression \"\"\" x_steps, y_steps = 60, [1,", "= \"1\", \"1\" train_x, test_x, train_y, test_y, time_d = preprocess(data_in", "y_steps) # 1 step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1,", "\"set\":i}) for a in assets: print(\"asset\", a) filt = indexes[\"set\"][~pd.isna(wide_close[a])]", "train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true, pred)", "lr_1) print(\"Model 1 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) # 16", "= pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details", "preprocess(wide_close, cols_in, cols_out, \"time\", x_steps, y_steps) # 1 step lr_1", "calculate and store components seperately process: - first, get rolling", "Forest \"\"\" rf = RandomForestRegressor(n_jobs=-1) # start = time.time() rf.fit(train_x.reshape(-1,", "dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random Forest \"\"\" rf = RandomForestRegressor(n_jobs=-1) #", "\"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes i = np.select(", "\"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a in assets: print(\"asset\",", "import dump, load from mod.prep import log_return, log_return_np, preprocess from", "= LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x,", "[1, 16] cols_in, cols_out = a, a train_x, test_x, train_y,", "from sklearn.ensemble import RandomForestRegressor from joblib import dump, load from", "array \"\"\" # Production \"\"\" Steps: - Get train, val", "lr_16) print(\"Model 16 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\")", "pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d = {} for s in", "# Production \"\"\" Steps: - Get train, val test and", "import tensorflow as tf import seaborn as sns from time", "a) filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts() df = pd.DataFrame({\"counts\":counts,", "Get indexes i = np.select( [ (wide_close.index >= 0) &", "= np.select( [ (wide_close.index >= 0) & (wide_close.index <= (len(wide_close)*0.7)),", "evaluate_regression, evaluate_up_down cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\" wide_close", "tensorflow.keras.layers import Dense, LSTM, ConvLSTM2D, Flatten from sklearn.preprocessing import StandardScaler", "import os from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense,", "\"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder +", "x_steps, y_steps) # 1 step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps),", "needs to cover all assets (even though not all assets", "filt.value_counts() df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d = {}", "wide_close = pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder + \"/working/wide_target.csv\")", "15] col_in, col_out = \"1\", \"1\" train_x, test_x, train_y, test_y,", "evaluate_up_down(true, pred) # 15 step lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps),", "rolling values for each timestamp - then, predict 1 and", "cols_out, \"time\", x_steps, y_steps) # 1 step lr_1 = LinearRegression()", "indices. Importantly, this needs to cover all assets (even though", "print(\"asset\", a) filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts() df =", "1 step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1)) true,", "seperately process: - first, get rolling values for each timestamp", "\"\"\" import pandas as pd import numpy as np import", "(wide_close.index >= 0) & (wide_close.index <= (len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7))", "& (wide_close.index <= (len(wide_close)*0.8)) ], [\"train\", \"val\"], default = \"test\")", "- Get train, val test and test indices. Importantly, this", "\"model_files/linear_regression/lr_times\") \"\"\" Random Forest \"\"\" rf = RandomForestRegressor(n_jobs=-1) # start", "lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1)", "pred) evaluate_up_down(true, pred) # 15 step lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1,", "60, [1, 16] cols_in, cols_out = a, a train_x, test_x,", "a) x_steps, y_steps = 60, [1, 16] cols_in, cols_out =", "(wide_close.index <= (len(wide_close)*0.8)) ], [\"train\", \"val\"], default = \"test\") indexes", "import Sequential from tensorflow.keras.layers import Dense, LSTM, ConvLSTM2D, Flatten from", "test_y[:,1,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) \"\"\" calculate and store", "= multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\" wide_close = pd.read_csv(root_folder +", "\"time\", x_steps, y_steps) # 1 step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1,", "asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\" close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"]", "import time import multiprocessing import random import os from tensorflow.keras.models", "lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred =", "for s in indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"] == s] mkdir", "import pandas as pd import numpy as np import tensorflow", "+ \"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder + \"/asset_details.csv\") assets = [str(i)", "1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model 16 Metrics\")", "= LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x,", "asset_details = pd.read_csv(root_folder + \"/asset_details.csv\") assets = [str(i) for i", "import log_return, log_return_np, preprocess from mod.model import return_pred from mod.eval", "import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor", "a train_x, test_x, train_y, test_y, time_d = preprocess(wide_close, cols_in, cols_out,", "on multiple cores - Import Data \"\"\" import pandas as", "train, val test and test indices. Importantly, this needs to", "pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target = pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details =", "evaluate_up_down cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\" wide_close =", "col_in, col_out = \"1\", \"1\" train_x, test_x, train_y, test_y, time_d", "y_steps = 60, [1, 15] col_in, col_out = \"1\", \"1\"", "- Import Data \"\"\" import pandas as pd import numpy", "all assets exist) for the whole time period. - Build", "pred) evaluate_up_down(true, pred) # 16 step lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1,", "- Import Libraries - Setup tf on multiple cores -", "Setup: - Import Libraries - Setup tf on multiple cores", "lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_16)", "= pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder + \"/asset_details.csv\") assets", "first, get rolling values for each timestamp - then, predict", "for a in assets: print(\"asset\", a) filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts", "a in assets: print(\"asset\", a) filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts =", "= close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression \"\"\" x_steps, y_steps = 60,", "val test and test indices. Importantly, this needs to cover", "= wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear", "x_steps, y_steps = 60, [1, 15] col_in, col_out = \"1\",", "Random Forest \"\"\" rf = RandomForestRegressor(n_jobs=-1) # start = time.time()", "- then, predict 1 and 15 gaps and store in", "for i in asset_details[\"Asset_ID\"]] \"\"\" Preprocess \"\"\" close_returns = wide_close[assets].apply(log_return)", "step lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred", "import random import os from tensorflow.keras.models import Sequential from tensorflow.keras.layers", "np.select( [ (wide_close.index >= 0) & (wide_close.index <= (len(wide_close)*0.7)), (wide_close.index", "lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred =", "indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"] == s] mkdir \"model_files\" mkdir \"model_files/linear_regression\"", "preprocess from mod.model import return_pred from mod.eval import evaluate_regression, evaluate_up_down", "rf = RandomForestRegressor(n_jobs=-1) # start = time.time() rf.fit(train_x.reshape(-1, x_steps), train_y.reshape(-1))", "os from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM,", "import RandomForestRegressor from joblib import dump, load from mod.prep import", "import return_pred from mod.eval import evaluate_regression, evaluate_up_down cores = multiprocessing.cpu_count()", "tensorflow as tf import seaborn as sns from time import", "Sequential from tensorflow.keras.layers import Dense, LSTM, ConvLSTM2D, Flatten from sklearn.preprocessing", "15 step lr_15 = LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true,", "- first, get rolling values for each timestamp - then,", "assets (even though not all assets exist) for the whole", "x_steps, y_steps = 60, [1, 16] cols_in, cols_out = a,", "x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true,", "step lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred", "and store components seperately process: - first, get rolling values", "<reponame>fpl-analytics/gr_crypto \"\"\" Setup: - Import Libraries - Setup tf on", "from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor from joblib", "from time import time import multiprocessing import random import os", ">= 0) & (wide_close.index <= (len(wide_close)*0.7)), (wide_close.index > (len(wide_close)*0.7)) &", "assets: print(\"Asset\", a) x_steps, y_steps = 60, [1, 16] cols_in,", "60, [1, 15] col_in, col_out = \"1\", \"1\" train_x, test_x,", "time_d = preprocess(wide_close, cols_in, cols_out, \"time\", x_steps, y_steps) # 1", "multiple cores - Import Data \"\"\" import pandas as pd", "= wide_close, col_in, col_out, time_col=\"time\", x_steps, y_steps) # 1 step", "Import Libraries - Setup tf on multiple cores - Import", "LinearRegression() lr_15.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:],", "for the whole time period. - Build models \"\"\" assets", "cols_in, cols_out, \"time\", x_steps, y_steps) # 1 step lr_1 =", "\"\"\" # Production \"\"\" Steps: - Get train, val test", "RandomForestRegressor(n_jobs=-1) # start = time.time() rf.fit(train_x.reshape(-1, x_steps), train_y.reshape(-1)) # print(\"Took:\",", "evaluate_up_down(true, pred) \"\"\" calculate and store components seperately process: -", "x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model", "(len(wide_close)*0.7)) & (wide_close.index <= (len(wide_close)*0.8)) ], [\"train\", \"val\"], default =", "from mod.model import return_pred from mod.eval import evaluate_regression, evaluate_up_down cores", "= preprocess(wide_close, cols_in, cols_out, \"time\", x_steps, y_steps) # 1 step", "pred) evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\"", "tf on multiple cores - Import Data \"\"\" import pandas", "close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression \"\"\"", "= \"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for a in assets:", "not all assets exist) for the whole time period. -", "pd import numpy as np import tensorflow as tf import", "assets exist) for the whole time period. - Build models", "= list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes i = np.select( [ (wide_close.index", "return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) \"\"\" calculate and", "1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true,", "test indices. Importantly, this needs to cover all assets (even", "Import Data \"\"\" import pandas as pd import numpy as", "16 step lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true,", "return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model 1 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred)", "LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,1,:],", "pred) # 16 step lr_16 = LinearRegression() lr_16.fit(train_x.reshape(-1, x_steps), train_y[:,1,:].reshape(-1,", "col_out, time_col=\"time\", x_steps, y_steps) # 1 step lr_1 = LinearRegression()", "train_y, test_y, time_d = preprocess(wide_close, cols_in, cols_out, \"time\", x_steps, y_steps)", "LinearRegression from sklearn.ensemble import RandomForestRegressor from joblib import dump, load", "period. - Build models \"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str)) # Get", "to cover all assets (even though not all assets exist)", "return_pred(test_x, test_y[:,1,:], lr_16) print(\"Model 16 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred)", "filt = indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts() df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)})", "\"\"\" Preprocess \"\"\" close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets]", "load from mod.prep import log_return, log_return_np, preprocess from mod.model import", "counts = filt.value_counts() df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\") indexes_d", "\"1\" train_x, test_x, train_y, test_y, time_d = preprocess(data_in = wide_close,", "and test indices. Importantly, this needs to cover all assets", "tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\" wide_close = pd.read_csv(root_folder + \"/working/wide_close.csv\") wide_target", "cores = multiprocessing.cpu_count() tf.config.threading.set_inter_op_parallelism_threads(cores-1) root_folder = \"data\" wide_close = pd.read_csv(root_folder", "indexes[\"set\"][~pd.isna(wide_close[a])] counts = filt.value_counts() df = pd.DataFrame({\"counts\":counts, \"pct\":counts/np.sum(counts)}) print(df, \"\\n\\n\")", "pd.read_csv(root_folder + \"/asset_details.csv\") assets = [str(i) for i in asset_details[\"Asset_ID\"]]", "sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.ensemble import", "Libraries - Setup tf on multiple cores - Import Data", "wide_close, col_in, col_out, time_col=\"time\", x_steps, y_steps) # 1 step lr_1", "lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) # 15 step lr_15 =", "print(\"Model 16 Metrics\") evaluate_regression(true, pred) evaluate_up_down(true, pred) dump(lr_1, f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16,", "close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\"", "= return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) \"\"\" calculate", "\"\"\" x_steps, y_steps = 60, [1, 15] col_in, col_out =", "test_y, time_d = preprocess(wide_close, cols_in, cols_out, \"time\", x_steps, y_steps) #", "time_d = preprocess(data_in = wide_close, col_in, col_out, time_col=\"time\", x_steps, y_steps)", "Preprocess \"\"\" close_returns = wide_close[assets].apply(log_return) close_returns[\"time\"] = wide_close[\"time\"] close_returns[assets] =", "Build models \"\"\" assets = list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes i", "pd.read_csv(root_folder + \"/working/wide_target.csv\") asset_details = pd.read_csv(root_folder + \"/asset_details.csv\") assets =", "# 1 step lr_1 = LinearRegression() lr_1.fit(train_x.reshape(-1, x_steps), train_y[:,0,:].reshape(-1, 1))", "mkdir \"model_files/linear_regression\" for a in assets: print(\"Asset\", a) x_steps, y_steps", "(len(wide_close)*0.8)) ], [\"train\", \"val\"], default = \"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"],", "import seaborn as sns from time import time import multiprocessing", "pred) evaluate_up_down(true, pred) \"\"\" calculate and store components seperately process:", "test_y, time_d = preprocess(data_in = wide_close, col_in, col_out, time_col=\"time\", x_steps,", "= {} for s in indexes[\"set\"].unique(): indexes_d[s] = indexes[\"time\"][indexes[\"set\"] ==", "indexes[\"time\"][indexes[\"set\"] == s] mkdir \"model_files\" mkdir \"model_files/linear_regression\" for a in", "cols_in, cols_out = a, a train_x, test_x, train_y, test_y, time_d", "f\"model_files/linear_regression/lr_{a}_1\") dump(lr_16, f\"model_files/linear_regression/lr_{a}_16\") dump(time_d, \"model_files/linear_regression/lr_times\") \"\"\" Random Forest \"\"\" rf", "x_steps), train_y[:,0,:].reshape(-1, 1)) true, pred = return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model", "true, pred = return_pred(test_x, test_y[:,0,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred)", "\"\"\" rf = RandomForestRegressor(n_jobs=-1) # start = time.time() rf.fit(train_x.reshape(-1, x_steps),", "this needs to cover all assets (even though not all", "[\"train\", \"val\"], default = \"test\") indexes = pd.DataFrame({\"time\":wide_close[\"time\"], \"set\":i}) for", "close_returns[assets] = close_returns[assets].replace([np.inf,-np.inf],np.nan) \"\"\" Linear Regression \"\"\" x_steps, y_steps =", "pred = return_pred(test_x, test_y[:,1,:], lr_1) evaluate_regression(true, pred) evaluate_up_down(true, pred) \"\"\"", "assets = list(asset_details[\"Asset_ID\"].astype(str)) # Get indexes i = np.select( [", "joblib import dump, load from mod.prep import log_return, log_return_np, preprocess", "true, pred = return_pred(test_x, test_y[:,0,:], lr_1) print(\"Model 1 Metrics\") evaluate_regression(true," ]
[ "if us == 'member': msg = bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!,", "process button presses import telebot import time from telebot.types import", "<reponame>menlen/one # This example show how to use inline keyboards", "message.text myfile = TextToImg(name) photoSend = open(f'{myfile}.png', 'rb') caption =", "# draw text, half opacity d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255), anchor='mb')", "'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ] try: img = random.choice(IMAGES) except:", "telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326 user_dict = {} def TextToImg(ext): IMAGES", "text, half opacity d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255), anchor='mb') out =", "getUserFromChannel(userId): u = bot.get_chat_member(channelId, userId) return u.status @bot.callback_query_handler(func=lambda call: True)", "\\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption) except Exception as e: bot.reply_to(message, 'oooops')", "as e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message: True) def message_handler(message): us", "us == 'member': msg = bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!, Ismingizni", "soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name},", "'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg',", "u = bot.get_chat_member(channelId, userId) return u.status @bot.callback_query_handler(func=lambda call: True) def", "blank image for the text, initialized to transparent text color", "text, font=fnt, fill=(255,0,0,255), anchor='mb') out = Image.alpha_composite(base, txt) filename =", "This example show how to use inline keyboards and process", "Image.alpha_composite(base, txt) filename = random.randint(1,35) g = out.save(f'{filename}.png') return filename", "\"cb_no\": u = getUserFromChannel(call.from_user.id) if u == 'member': msg =", "message_handler(message): us = getUserFromChannel(message.chat.id) if us == 'member': msg =", "make a blank image for the text, initialized to transparent", "= bot.get_chat_member(channelId, userId) return u.status @bot.callback_query_handler(func=lambda call: True) def callback_query(call):", "Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id, f\"Salom", "d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255), anchor='mb') out = Image.alpha_composite(base, txt) filename", "call: True) def callback_query(call): if call.data == \"cb_yes\": bot.answer_callback_query(call.id, \"Answer", "== 'member': msg = bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing", "'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg',", "'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg',", "\\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption) except Exception as e: bot.reply_to(message,", "'member': msg = bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\")", "def message_handler(message): us = getUserFromChannel(message.chat.id) if us == 'member': msg", "font=fnt, fill=(255,0,0,255), anchor='mb') out = Image.alpha_composite(base, txt) filename = random.randint(1,35)", "telebot import time from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import os,", "'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg',", "except Exception as e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message: True) def", "InlineKeyboardButton import os, sys from PIL import Image, ImageDraw, ImageFont", "base = Image.open(img).convert(\"RGBA\") ext = ext.upper() text = ext #", "channelId = -1001390673326 user_dict = {} def TextToImg(ext): IMAGES =", "fill=(255,0,0,255), anchor='mb') out = Image.alpha_composite(base, txt) filename = random.randint(1,35) g", "= '<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326 user_dict =", "@bot.callback_query_handler(func=lambda call: True) def callback_query(call): if call.data == \"cb_yes\": bot.answer_callback_query(call.id,", "PIL import Image, ImageDraw, ImageFont import random TELEGRAM_TOKEN = '<KEY>'", "'<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326 user_dict = {}", "ImageDraw, ImageFont import random TELEGRAM_TOKEN = '<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN)", "a drawing context d = ImageDraw.Draw(txt) # draw text, half", "# This example show how to use inline keyboards and", "return markup def getUserFromChannel(userId): u = bot.get_chat_member(channelId, userId) return u.status", "== \"cb_yes\": bot.answer_callback_query(call.id, \"Answer is Yes\") elif call.data == \"cb_no\":", "'member': msg = bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\")", "text = ext # make a blank image for the", "= Image.alpha_composite(base, txt) filename = random.randint(1,35) g = out.save(f'{filename}.png') return", "= open(f'{myfile}.png', 'rb') caption = f'{name} : ismiga sovga @onideal", "'rb') caption = f'{name} : ismiga sovga @onideal \\n@giftmerobot \\n@mygiftrobot'", "'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg',", "'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg',", "'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg'", "callback_query(call): if call.data == \"cb_yes\": bot.answer_callback_query(call.id, \"Answer is Yes\") elif", "an image base = Image.open(img).convert(\"RGBA\") ext = ext.upper() text =", "caption=caption) except Exception as e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message: True)", "markup = InlineKeyboardMarkup() markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'),", "A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) def process_name_step(message): try: name =", "'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg',", "ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get a drawing context d = ImageDraw.Draw(txt)", "== 'member': msg = bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing", "to use inline keyboards and process button presses import telebot", "text color txt = Image.new(\"RGBA\", base.size, (255,255,255,0)) # get a", "txt) filename = random.randint(1,35) g = out.save(f'{filename}.png') return filename def", "g = out.save(f'{filename}.png') return filename def gen_markup(): markup = InlineKeyboardMarkup()", "return u.status @bot.callback_query_handler(func=lambda call: True) def callback_query(call): if call.data ==", "bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga a'zo bo'ling va", "# make a blank image for the text, initialized to", "msg = bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg,", "'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ] try: img = random.choice(IMAGES) except: time.sleep(2)", "'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg',", "'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg',", "show how to use inline keyboards and process button presses", "get a font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get a", "'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg',", "out.save(f'{filename}.png') return filename def gen_markup(): markup = InlineKeyboardMarkup() markup.row_width =", "\"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga a'zo bo'ling", "base.size, (255,255,255,0)) # get a font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40)", "import random TELEGRAM_TOKEN = '<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId =", "telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import os, sys from PIL import", "txt = Image.new(\"RGBA\", base.size, (255,255,255,0)) # get a font fnt", "a blank image for the text, initialized to transparent text", "= telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326 user_dict = {} def TextToImg(ext):", "getUserFromChannel(call.from_user.id) if u == 'member': msg = bot.send_message(call.from_user.id, \"\"\"\\ Juda", "u.status @bot.callback_query_handler(func=lambda call: True) def callback_query(call): if call.data == \"cb_yes\":", "tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) def process_name_step(message): try: name = message.text", "bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini", "'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg',", "= bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step)", "= 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup", "u = getUserFromChannel(call.from_user.id) if u == 'member': msg = bot.send_message(call.from_user.id,", "yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga a'zo", "caption = f'{name} : ismiga sovga @onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id,", ": ismiga sovga @onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption) except", "'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg',", "True) def callback_query(call): if call.data == \"cb_yes\": bot.answer_callback_query(call.id, \"Answer is", "example show how to use inline keyboards and process button", "transparent text color txt = Image.new(\"RGBA\", base.size, (255,255,255,0)) # get", "call.data == \"cb_yes\": bot.answer_callback_query(call.id, \"Answer is Yes\") elif call.data ==", "get a drawing context d = ImageDraw.Draw(txt) # draw text,", "\"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id,", "ismiga sovga @onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption) except Exception", "= ImageDraw.Draw(txt) # draw text, half opacity d.text(((800)/2,(1136)/2), text, font=fnt,", "def getUserFromChannel(userId): u = bot.get_chat_member(channelId, userId) return u.status @bot.callback_query_handler(func=lambda call:", "photoSend, caption=caption) except Exception as e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message:", "import InlineKeyboardMarkup, InlineKeyboardButton import os, sys from PIL import Image,", "import Image, ImageDraw, ImageFont import random TELEGRAM_TOKEN = '<KEY>' bot", "time.sleep(2) img = random.choice(IMAGES) # get an image base =", "InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup def getUserFromChannel(userId): u = bot.get_chat_member(channelId, userId)", "\"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga a'zo bo'ling", "va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) def process_name_step(message): try: name", "= random.choice(IMAGES) # get an image base = Image.open(img).convert(\"RGBA\") ext", "keyboards and process button presses import telebot import time from", "a font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get a drawing", "text, initialized to transparent text color txt = Image.new(\"RGBA\", base.size,", "from PIL import Image, ImageDraw, ImageFont import random TELEGRAM_TOKEN =", "f'{name} : ismiga sovga @onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption)", "= Image.new(\"RGBA\", base.size, (255,255,255,0)) # get a font fnt =", "userId) return u.status @bot.callback_query_handler(func=lambda call: True) def callback_query(call): if call.data", "half opacity d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255), anchor='mb') out = Image.alpha_composite(base,", "def callback_query(call): if call.data == \"cb_yes\": bot.answer_callback_query(call.id, \"Answer is Yes\")", "= ext.upper() text = ext # make a blank image", "myfile = TextToImg(name) photoSend = open(f'{myfile}.png', 'rb') caption = f'{name}", "filename def gen_markup(): markup = InlineKeyboardMarkup() markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo", "us = getUserFromChannel(message.chat.id) if us == 'member': msg = bot.send_message(message.chat.id,", "else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish", "image base = Image.open(img).convert(\"RGBA\") ext = ext.upper() text = ext", "drawing context d = ImageDraw.Draw(txt) # draw text, half opacity", "= ext # make a blank image for the text,", "= message.text myfile = TextToImg(name) photoSend = open(f'{myfile}.png', 'rb') caption", "= bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step)", "Exception as e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message: True) def message_handler(message):", "'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ] try:", "random.randint(1,35) g = out.save(f'{filename}.png') return filename def gen_markup(): markup =", "'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ] try: img =", "callback_data=\"cb_no\")) return markup def getUserFromChannel(userId): u = bot.get_chat_member(channelId, userId) return", "bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else:", "= random.randint(1,35) g = out.save(f'{filename}.png') return filename def gen_markup(): markup", "img = random.choice(IMAGES) except: time.sleep(2) img = random.choice(IMAGES) # get", "@onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption) except Exception as e:", "'ZAMBARAK.jpg' ] try: img = random.choice(IMAGES) except: time.sleep(2) img =", "random TELEGRAM_TOKEN = '<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326", "'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg',", "if u == 'member': msg = bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!,", "bot.send_photo(message.chat.id, photoSend, caption=caption) except Exception as e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda", "'oooops') @bot.message_handler(func=lambda message: True) def message_handler(message): us = getUserFromChannel(message.chat.id) if", "'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ] try: img", "url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup def getUserFromChannel(userId): u = bot.get_chat_member(channelId,", "photoSend = open(f'{myfile}.png', 'rb') caption = f'{name} : ismiga sovga", "open(f'{myfile}.png', 'rb') caption = f'{name} : ismiga sovga @onideal \\n@giftmerobot", "return filename def gen_markup(): markup = InlineKeyboardMarkup() markup.row_width = 1", "TextToImg(ext): IMAGES = [ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg',", "ext # make a blank image for the text, initialized", "msg = bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg,", "import time from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import os, sys", "presses import telebot import time from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton", "ImageFont import random TELEGRAM_TOKEN = '<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId", "try: img = random.choice(IMAGES) except: time.sleep(2) img = random.choice(IMAGES) #", "opacity d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255), anchor='mb') out = Image.alpha_composite(base, txt)", "use inline keyboards and process button presses import telebot import", "time from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import os, sys from", "def gen_markup(): markup = InlineKeyboardMarkup() markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\",", "bot.get_chat_member(channelId, userId) return u.status @bot.callback_query_handler(func=lambda call: True) def callback_query(call): if", "fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get a drawing context d", "anchor='mb') out = Image.alpha_composite(base, txt) filename = random.randint(1,35) g =", "bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup def getUserFromChannel(userId): u", "Image, ImageDraw, ImageFont import random TELEGRAM_TOKEN = '<KEY>' bot =", "'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg',", "'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg',", "'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg',", "= random.choice(IMAGES) except: time.sleep(2) img = random.choice(IMAGES) # get an", "bot.answer_callback_query(call.id, \"Answer is Yes\") elif call.data == \"cb_no\": u =", "buyrug'ini tanlang\", reply_markup=gen_markup()) def process_name_step(message): try: name = message.text myfile", "[ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg',", "ext = ext.upper() text = ext # make a blank", "{call.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup())", "yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga a'zo", "f\"Salom {message.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\",", "'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg',", "= getUserFromChannel(message.chat.id) if us == 'member': msg = bot.send_message(message.chat.id, \"\"\"\\", "= Image.open(img).convert(\"RGBA\") ext = ext.upper() text = ext # make", "getUserFromChannel(message.chat.id) if us == 'member': msg = bot.send_message(message.chat.id, \"\"\"\\ Juda", "'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg',", "ext.upper() text = ext # make a blank image for", "= -1001390673326 user_dict = {} def TextToImg(ext): IMAGES = [", "IMAGES = [ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg',", "'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg',", "{} def TextToImg(ext): IMAGES = [ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg',", "img = random.choice(IMAGES) # get an image base = Image.open(img).convert(\"RGBA\")", "] try: img = random.choice(IMAGES) except: time.sleep(2) img = random.choice(IMAGES)", "is Yes\") elif call.data == \"cb_no\": u = getUserFromChannel(call.from_user.id) if", "os, sys from PIL import Image, ImageDraw, ImageFont import random", "sovga @onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend, caption=caption) except Exception as", "'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg',", "TELEGRAM_TOKEN = '<KEY>' bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326 user_dict", "= f'{name} : ismiga sovga @onideal \\n@giftmerobot \\n@mygiftrobot' bot.send_photo(message.chat.id, photoSend,", "process_name_step) else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni", "bo'ling va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) def process_name_step(message): try:", "'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ]", "how to use inline keyboards and process button presses import", "if call.data == \"cb_yes\": bot.answer_callback_query(call.id, \"Answer is Yes\") elif call.data", "from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import os, sys from PIL", "{message.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup())", "kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) bot.polling(none_stop=True)", "call.data == \"cb_no\": u = getUserFromChannel(call.from_user.id) if u == 'member':", "= [ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg',", "import telebot import time from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import", "== \"cb_no\": u = getUserFromChannel(call.from_user.id) if u == 'member': msg", "# get a drawing context d = ImageDraw.Draw(txt) # draw", "process_name_step(message): try: name = message.text myfile = TextToImg(name) photoSend =", "'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg', 'NOTEBOOK.jpg', 'OMAD.jpg',", "= InlineKeyboardMarkup() markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\",", "name = message.text myfile = TextToImg(name) photoSend = open(f'{myfile}.png', 'rb')", "= out.save(f'{filename}.png') return filename def gen_markup(): markup = InlineKeyboardMarkup() markup.row_width", "-1001390673326 user_dict = {} def TextToImg(ext): IMAGES = [ 'AROQ.jpg',", "e: bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message: True) def message_handler(message): us =", "draw text, half opacity d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255), anchor='mb') out", "u == 'member': msg = bot.send_message(call.from_user.id, \"\"\"\\ Juda soz!!!, Ismingizni", "markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup def getUserFromChannel(userId):", "font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get a drawing context", "and process button presses import telebot import time from telebot.types", "@bot.message_handler(func=lambda message: True) def message_handler(message): us = getUserFromChannel(message.chat.id) if us", "# get an image base = Image.open(img).convert(\"RGBA\") ext = ext.upper()", "bot = telebot.TeleBot(TELEGRAM_TOKEN) channelId = -1001390673326 user_dict = {} def", "'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg', 'DOST.jpg', 'ER.jpg', 'ETIK.jpg', 'FUTBOL.jpg', 'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg',", "d = ImageDraw.Draw(txt) # draw text, half opacity d.text(((800)/2,(1136)/2), text,", "\"Answer is Yes\") elif call.data == \"cb_no\": u = getUserFromChannel(call.from_user.id)", "Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga", "= getUserFromChannel(call.from_user.id) if u == 'member': msg = bot.send_message(call.from_user.id, \"\"\"\\", "tanlang\", reply_markup=gen_markup()) def process_name_step(message): try: name = message.text myfile =", "filename = random.randint(1,35) g = out.save(f'{filename}.png') return filename def gen_markup():", "def process_name_step(message): try: name = message.text myfile = TextToImg(name) photoSend", "random.choice(IMAGES) # get an image base = Image.open(img).convert(\"RGBA\") ext =", "kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) def", "process_name_step) else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni", "'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg', 'TOK.jpg', 'TORSHIM.jpg',", "= ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get a drawing context d =", "markup def getUserFromChannel(userId): u = bot.get_chat_member(channelId, userId) return u.status @bot.callback_query_handler(func=lambda", "'OMAD.jpg', 'OYINCHOQ.jpg', 'PAYPQO.jpg', 'BAXT.jpg', 'PUL.jpg', 'PULTUG.jpg', 'QORQIZ.jpg', 'SOSISKA.jpg', 'TELEFON.jpg', 'TELEFONZ.jpg',", "elif call.data == \"cb_no\": u = getUserFromChannel(call.from_user.id) if u ==", "soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name},", "try: name = message.text myfile = TextToImg(name) photoSend = open(f'{myfile}.png',", "import os, sys from PIL import Image, ImageDraw, ImageFont import", "a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\", reply_markup=gen_markup()) def process_name_step(message):", "1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup def", "sys from PIL import Image, ImageDraw, ImageFont import random TELEGRAM_TOKEN", "reply_markup=gen_markup()) def process_name_step(message): try: name = message.text myfile = TextToImg(name)", "= {} def TextToImg(ext): IMAGES = [ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg',", "= TextToImg(name) photoSend = open(f'{myfile}.png', 'rb') caption = f'{name} :", "Image.new(\"RGBA\", base.size, (255,255,255,0)) # get a font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\",", "40) # get a drawing context d = ImageDraw.Draw(txt) #", "f\"Salom {call.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini tanlang\",", "TextToImg(name) photoSend = open(f'{myfile}.png', 'rb') caption = f'{name} : ismiga", "random.choice(IMAGES) except: time.sleep(2) img = random.choice(IMAGES) # get an image", "True) def message_handler(message): us = getUserFromChannel(message.chat.id) if us == 'member':", "else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish", "except: time.sleep(2) img = random.choice(IMAGES) # get an image base", "Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id, f\"Salom", "user_dict = {} def TextToImg(ext): IMAGES = [ 'AROQ.jpg', 'AK47.jpg',", "InlineKeyboardMarkup() markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\"))", "image for the text, initialized to transparent text color txt", "Image.open(img).convert(\"RGBA\") ext = ext.upper() text = ext # make a", "gen_markup(): markup = InlineKeyboardMarkup() markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\",", "bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga a'zo bo'ling va", "button presses import telebot import time from telebot.types import InlineKeyboardMarkup,", "to transparent text color txt = Image.new(\"RGBA\", base.size, (255,255,255,0)) #", "\"cb_yes\": bot.answer_callback_query(call.id, \"Answer is Yes\") elif call.data == \"cb_no\": u", "get an image base = Image.open(img).convert(\"RGBA\") ext = ext.upper() text", "'UY.jpg', 'ZAMBARAK.jpg' ] try: img = random.choice(IMAGES) except: time.sleep(2) img", "initialized to transparent text color txt = Image.new(\"RGBA\", base.size, (255,255,255,0))", "callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return markup def getUserFromChannel(userId): u =", "inline keyboards and process button presses import telebot import time", "ImageDraw.Draw(txt) # draw text, half opacity d.text(((800)/2,(1136)/2), text, font=fnt, fill=(255,0,0,255),", "'TOK.jpg', 'TORSHIM.jpg', 'TUYA.jpg', 'UY.jpg', 'ZAMBARAK.jpg' ] try: img = random.choice(IMAGES)", "\"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id,", "def TextToImg(ext): IMAGES = [ 'AROQ.jpg', 'AK47.jpg', 'BAXT.jpg', 'BASKETBOL.jpg', 'BAXTLI.jpg',", "for the text, initialized to transparent text color txt =", "markup.row_width = 1 markup.add(InlineKeyboardButton(\"Azo bo'ling\", callback_data=\"cb_yes\", url='t.me/onideal'), InlineKeyboardButton(\"Tasdiqlash\", callback_data=\"cb_no\")) return", "message: True) def message_handler(message): us = getUserFromChannel(message.chat.id) if us ==", "bot.send_message(message.chat.id, \"\"\"\\ Juda soz!!!, Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else:", "InlineKeyboardMarkup, InlineKeyboardButton import os, sys from PIL import Image, ImageDraw,", "Ismingizni yozing \"\"\") bot.register_next_step_handler(msg, process_name_step) else: bot.send_message(message.chat.id, f\"Salom {message.from_user.first_name}, kanallarga", "bot.reply_to(message, 'oooops') @bot.message_handler(func=lambda message: True) def message_handler(message): us = getUserFromChannel(message.chat.id)", "'GAZ.jpg', 'HOTIN.jpg', 'BAXT.jpg', 'IPHONE.jpg', 'KOLBASA.jpg', 'KONFET.jpg', 'KOZGU.jpg', 'KUCHUK.jpg', 'MOSHINA.jpg', 'NEWISHTON.jpg',", "context d = ImageDraw.Draw(txt) # draw text, half opacity d.text(((800)/2,(1136)/2),", "out = Image.alpha_composite(base, txt) filename = random.randint(1,35) g = out.save(f'{filename}.png')", "color txt = Image.new(\"RGBA\", base.size, (255,255,255,0)) # get a font", "bot.send_message(call.from_user.id, f\"Salom {call.from_user.first_name}, kanallarga a'zo bo'ling va A'zolikni tekshirish buyrug'ini", "(255,255,255,0)) # get a font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) #", "# get a font fnt = ImageFont.truetype(\"OpenSans-Italic.ttf\", 40) # get", "the text, initialized to transparent text color txt = Image.new(\"RGBA\",", "Yes\") elif call.data == \"cb_no\": u = getUserFromChannel(call.from_user.id) if u" ]
[ "from rectangle2 import rectangle_area def test_unit_square(): assert rectangle_area([0, 0, 1,", "assert rectangle_area([1, 1, 4, 4]) == 9.0 def test_actual_rectangle(): assert", "rectangle_area def test_unit_square(): assert rectangle_area([0, 0, 1, 1]) == 1.0", "== 9.0 def test_actual_rectangle(): assert rectangle_area([0, 1, 4, 7]) ==", "0, 1, 1]) == 1.0 def test_large_square(): assert rectangle_area([1, 1,", "def test_large_square(): assert rectangle_area([1, 1, 4, 4]) == 9.0 def", "def test_unit_square(): assert rectangle_area([0, 0, 1, 1]) == 1.0 def", "== 1.0 def test_large_square(): assert rectangle_area([1, 1, 4, 4]) ==", "import rectangle_area def test_unit_square(): assert rectangle_area([0, 0, 1, 1]) ==", "4]) == 9.0 def test_actual_rectangle(): assert rectangle_area([0, 1, 4, 7])", "1.0 def test_large_square(): assert rectangle_area([1, 1, 4, 4]) == 9.0", "assert rectangle_area([0, 0, 1, 1]) == 1.0 def test_large_square(): assert", "9.0 def test_actual_rectangle(): assert rectangle_area([0, 1, 4, 7]) == 24.0", "test_unit_square(): assert rectangle_area([0, 0, 1, 1]) == 1.0 def test_large_square():", "<reponame>Southampton-RSG/2019-03-13-southampton-swc from rectangle2 import rectangle_area def test_unit_square(): assert rectangle_area([0, 0,", "rectangle_area([1, 1, 4, 4]) == 9.0 def test_actual_rectangle(): assert rectangle_area([0,", "1]) == 1.0 def test_large_square(): assert rectangle_area([1, 1, 4, 4])", "4, 4]) == 9.0 def test_actual_rectangle(): assert rectangle_area([0, 1, 4,", "test_large_square(): assert rectangle_area([1, 1, 4, 4]) == 9.0 def test_actual_rectangle():", "rectangle2 import rectangle_area def test_unit_square(): assert rectangle_area([0, 0, 1, 1])", "1, 4, 4]) == 9.0 def test_actual_rectangle(): assert rectangle_area([0, 1,", "rectangle_area([0, 0, 1, 1]) == 1.0 def test_large_square(): assert rectangle_area([1,", "1, 1]) == 1.0 def test_large_square(): assert rectangle_area([1, 1, 4," ]
[ "self.radio.request('bar') @init_radio def test_kwargs(self): ''' Keyword arguments works correctly. '''", "wrap class TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self): ''' \"request\", \"reply\" and", "def init_radio(f): def wrap(self, *args): self.radio = Radio() return f(self,", "def test_request_reply_stop_replying(self): ''' \"request\", \"reply\" and \"stopReplying\" methods work correctly.", "from unittest import TestCase, TestLoader from radio import (Radio, ListenerNotFound,", "with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) # Child exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo',", "was not bounded. ''' def foo_handler(): pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo',", "fails when trying to unbound handler that was not bounded.", "foo_handler) # Child exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio def", "self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10, 5)) @init_radio def test_on_already_bound(self):", "def test_kwargs(self): ''' Keyword arguments works correctly. ''' foo_list =", "fails when trying to bound handler that is already bounded.", "Child exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self): '''", "self.radio.reply('foo', foo_handler) # Child exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio", "True. ''' def foo_handler(): pass self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler,", "init_radio(f): def wrap(self, *args): self.radio = Radio() return f(self, *args)", "\"reply\" fails when trying to bound handler that is already", "self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar')", "is incorrect. ''' def foo_handler(required_arg): pass self.radio.reply('foo', foo_handler) with self.assertRaises(TypeError):", "my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar',", "TestLoader from radio import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f):", "def foo_handler(): pass self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler) # General exception", "self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) # Child exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler)", "with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails", "self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def test_kwargs(self): ''' Keyword arguments works correctly.", "(10, 5)) @init_radio def test_on_already_bound(self): ''' \"reply\" fails when trying", "foo=10), (10, 5)) @init_radio def test_on_already_bound(self): ''' \"reply\" fails when", "return 'foo' def bar_handler(my_arg=222): return my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler)", "@init_radio def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails when trying to unbound", "\"reply\" and \"stopReplying\" methods work correctly. ''' def foo_handler(): return", "foo_handler, soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails when arguments", "wrap(self, *args): self.radio = Radio() return f(self, *args) return wrap", "Radio() return f(self, *args) return wrap class TestRadioRequestReplyMethods(TestCase): @init_radio def", "when trying to bound handler that is already bounded. '''", "TestCase, TestLoader from radio import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def", "self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def test_kwargs(self):", "f(self, *args) return wrap class TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self): '''", "if safe-argument is set to True. ''' def foo_handler(): pass", "test_on_already_bound(self): ''' \"reply\" fails when trying to bound handler that", "bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar', my_arg=444),", "test_request_reply_stop_replying(self): ''' \"request\", \"reply\" and \"stopReplying\" methods work correctly. '''", "= Radio() return f(self, *args) return wrap class TestRadioRequestReplyMethods(TestCase): @init_radio", "''' foo_list = [] def foo_handler(foo, bar): return (foo, bar)", "bound handler that is already bounded. ''' def foo_handler(): pass", "bounded. ''' def foo_handler(): pass self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler) #", "self.radio.reply('foo', foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails when trying", "''' def foo_handler(): pass self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler, soft=True)", "TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self): ''' \"request\", \"reply\" and \"stopReplying\" methods", "''' def foo_handler(): return 'foo' def bar_handler(my_arg=222): return my_arg self.radio.reply('foo',", "to unbound handler that was not bounded. ''' def foo_handler():", "my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar')", "'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo')", "self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails when", "''' \"reply\" fails when trying to bound handler that is", "@init_radio def test_off_soft_mode(self): ''' \"stopReplying\" will not fail if safe-argument", "pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio def test_off_soft_mode(self): ''' \"stopReplying\"", "arguments works correctly. ''' foo_list = [] def foo_handler(foo, bar):", "def test_on_already_bound(self): ''' \"reply\" fails when trying to bound handler", "correctly. ''' foo_list = [] def foo_handler(foo, bar): return (foo,", "foo_handler) self.radio.reply('bar', foo_handler) # General exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler)", "fails when arguments for handler is incorrect. ''' def foo_handler(required_arg):", "333), 333) self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo')", "class TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self): ''' \"request\", \"reply\" and \"stopReplying\"", "is already bounded. ''' def foo_handler(): pass self.radio.reply('foo', foo_handler) self.radio.reply('bar',", "\"stopReplying\" will not fail if safe-argument is set to True.", "foo_handler(required_arg): pass self.radio.reply('foo', foo_handler) with self.assertRaises(TypeError): self.radio.request('foo') suite = TestLoader().loadTestsFromTestCase(TestRadioRequestReplyMethods)", "444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio", "foo_handler(): return 'foo' def bar_handler(my_arg=222): return my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar',", "when arguments for handler is incorrect. ''' def foo_handler(required_arg): pass", "arguments for handler is incorrect. ''' def foo_handler(required_arg): pass self.radio.reply('foo',", "-*- coding: utf-8 -*- from unittest import TestCase, TestLoader from", "bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10, 5)) @init_radio def", "333) self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo') with", "bounded. ''' def foo_handler(): pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio", "def foo_handler(): pass self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio", "''' \"request\" fails when arguments for handler is incorrect. '''", "-*- from unittest import TestCase, TestLoader from radio import (Radio,", "foo_handler(): pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio def test_off_soft_mode(self): '''", "self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar',", "unittest import TestCase, TestLoader from radio import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound,", "handler that is already bounded. ''' def foo_handler(): pass self.radio.reply('foo',", "foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails when trying to", "pass self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler) # General exception with self.assertRaises(HandlerAlreadyBound):", "''' def foo_handler(required_arg): pass self.radio.reply('foo', foo_handler) with self.assertRaises(TypeError): self.radio.request('foo') suite", "set to True. ''' def foo_handler(): pass self.radio.stopReplying('foo', foo_handler, soft=True)", "exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) # Child exception with self.assertRaises(ReplyHandlerAlreadyBound):", "@init_radio def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails when arguments for handler", "''' \"stopReplying\" will not fail if safe-argument is set to", "that is already bounded. ''' def foo_handler(): pass self.radio.reply('foo', foo_handler)", "self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound):", "to True. ''' def foo_handler(): pass self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo',", "coding: utf-8 -*- from unittest import TestCase, TestLoader from radio", "''' Keyword arguments works correctly. ''' foo_list = [] def", "@init_radio def test_request_reply_stop_replying(self): ''' \"request\", \"reply\" and \"stopReplying\" methods work", "# General exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) # Child exception", "foo_handler(): pass self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio def", "def test_off_soft_mode(self): ''' \"stopReplying\" will not fail if safe-argument is", "# -*- coding: utf-8 -*- from unittest import TestCase, TestLoader", "incorrect. ''' def foo_handler(required_arg): pass self.radio.reply('foo', foo_handler) with self.assertRaises(TypeError): self.radio.request('foo')", "def wrap(self, *args): self.radio = Radio() return f(self, *args) return", "self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound):", "unbound handler that was not bounded. ''' def foo_handler(): pass", "''' def foo_handler(): pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio def", "with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def test_kwargs(self): ''' Keyword arguments works", "[] def foo_handler(foo, bar): return (foo, bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo',", "self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10, 5)) @init_radio def test_on_already_bound(self): ''' \"reply\"", "bar=5, foo=10), (10, 5)) @init_radio def test_on_already_bound(self): ''' \"reply\" fails", "self.radio.stopReplying('foo') self.radio.stopReplying('bar') with self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def", "= [] def foo_handler(foo, bar): return (foo, bar) self.radio.reply('foo', foo_handler)", "to bound handler that is already bounded. ''' def foo_handler():", "import TestCase, TestLoader from radio import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound)", "correctly. ''' def foo_handler(): return 'foo' def bar_handler(my_arg=222): return my_arg", "with self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def test_kwargs(self): '''", "import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f): def wrap(self, *args):", "trying to unbound handler that was not bounded. ''' def", "self.radio.stopReplying('foo', foo_handler) @init_radio def test_off_soft_mode(self): ''' \"stopReplying\" will not fail", "(foo, bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10, 5)) @init_radio", "def foo_handler(foo, bar): return (foo, bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5,", "test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails when arguments for handler is incorrect.", "foo_handler(): pass self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler) # General exception with", "ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f): def wrap(self, *args): self.radio =", "HandlerAlreadyBound) def init_radio(f): def wrap(self, *args): self.radio = Radio() return", "ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f): def wrap(self, *args): self.radio = Radio()", "\"stopReplying\" methods work correctly. ''' def foo_handler(): return 'foo' def", "when trying to unbound handler that was not bounded. '''", "''' def foo_handler(): pass self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler) # General", "self.radio = Radio() return f(self, *args) return wrap class TestRadioRequestReplyMethods(TestCase):", "return my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222)", "General exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) # Child exception with", "self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails when", "foo_handler) @init_radio def test_off_soft_mode(self): ''' \"stopReplying\" will not fail if", "@init_radio def test_kwargs(self): ''' Keyword arguments works correctly. ''' foo_list", "def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails when arguments for handler is", "test_kwargs(self): ''' Keyword arguments works correctly. ''' foo_list = []", "foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\"", "with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio def test_off_soft_mode(self): ''' \"stopReplying\" will", "*args) return wrap class TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self): ''' \"request\",", "return wrap class TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self): ''' \"request\", \"reply\"", "foo_handler(foo, bar): return (foo, bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10),", "def foo_handler(): return 'foo' def bar_handler(my_arg=222): return my_arg self.radio.reply('foo', foo_handler)", "foo_list = [] def foo_handler(foo, bar): return (foo, bar) self.radio.reply('foo',", "self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self): '''", "# Child exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self):", "\"request\" fails when arguments for handler is incorrect. ''' def", "*args): self.radio = Radio() return f(self, *args) return wrap class", "5)) @init_radio def test_on_already_bound(self): ''' \"reply\" fails when trying to", "that was not bounded. ''' def foo_handler(): pass with self.assertRaises(ListenerNotFound):", "''' \"request\", \"reply\" and \"stopReplying\" methods work correctly. ''' def", "is set to True. ''' def foo_handler(): pass self.radio.stopReplying('foo', foo_handler,", "def foo_handler(required_arg): pass self.radio.reply('foo', foo_handler) with self.assertRaises(TypeError): self.radio.request('foo') suite =", "soft=True) self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails", "def foo_handler(): pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio def test_off_soft_mode(self):", "bar_handler(my_arg=222): return my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'),", "works correctly. ''' foo_list = [] def foo_handler(foo, bar): return", "222) self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar', my_arg=444), 444) self.radio.stopReplying('foo') self.radio.stopReplying('bar') with", "handler that was not bounded. ''' def foo_handler(): pass with", "''' \"stopReplying\" fails when trying to unbound handler that was", "already bounded. ''' def foo_handler(): pass self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler)", "'foo' def bar_handler(my_arg=222): return my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'),", "will not fail if safe-argument is set to True. '''", "self.radio.reply('bar', foo_handler) # General exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) #", "return (foo, bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10, 5))", "self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333),", "self.radio.reply('foo', foo_handler) self.radio.reply('bar', foo_handler) # General exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo',", "Keyword arguments works correctly. ''' foo_list = [] def foo_handler(foo,", "@init_radio def test_on_already_bound(self): ''' \"reply\" fails when trying to bound", "\"stopReplying\" fails when trying to unbound handler that was not", "test_off_soft_mode(self): ''' \"stopReplying\" will not fail if safe-argument is set", "pass self.radio.stopReplying('foo', foo_handler, soft=True) self.radio.stopReplying('foo', foo_handler, soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self):", "def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails when trying to unbound handler", "self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333), 333) self.assertEqual(self.radio.request('bar', my_arg=444), 444)", "foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10, 5)) @init_radio def test_on_already_bound(self): '''", "test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\" fails when trying to unbound handler that", "radio import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f): def wrap(self,", "\"request\", \"reply\" and \"stopReplying\" methods work correctly. ''' def foo_handler():", "bar): return (foo, bar) self.radio.reply('foo', foo_handler) self.assertEqual(self.radio.request('foo', bar=5, foo=10), (10,", "soft=True) @init_radio def test_trigger_fail_on_incorrect_arguments(self): ''' \"request\" fails when arguments for", "return f(self, *args) return wrap class TestRadioRequestReplyMethods(TestCase): @init_radio def test_request_reply_stop_replying(self):", "and \"stopReplying\" methods work correctly. ''' def foo_handler(): return 'foo'", "self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler) @init_radio def test_off_soft_mode(self): ''' \"stopReplying\" will not", "foo_handler) # General exception with self.assertRaises(HandlerAlreadyBound): self.radio.reply('foo', foo_handler) # Child", "handler is incorrect. ''' def foo_handler(required_arg): pass self.radio.reply('foo', foo_handler) with", "self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def test_kwargs(self): ''' Keyword arguments", "from radio import (Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f): def", "not bounded. ''' def foo_handler(): pass with self.assertRaises(ListenerNotFound): self.radio.stopReplying('foo', foo_handler)", "fail if safe-argument is set to True. ''' def foo_handler():", "not fail if safe-argument is set to True. ''' def", "trying to bound handler that is already bounded. ''' def", "work correctly. ''' def foo_handler(): return 'foo' def bar_handler(my_arg=222): return", "(Radio, ListenerNotFound, ReplyHandlerAlreadyBound, HandlerAlreadyBound) def init_radio(f): def wrap(self, *args): self.radio", "utf-8 -*- from unittest import TestCase, TestLoader from radio import", "safe-argument is set to True. ''' def foo_handler(): pass self.radio.stopReplying('foo',", "methods work correctly. ''' def foo_handler(): return 'foo' def bar_handler(my_arg=222):", "for handler is incorrect. ''' def foo_handler(required_arg): pass self.radio.reply('foo', foo_handler)", "exception with self.assertRaises(ReplyHandlerAlreadyBound): self.radio.reply('foo', foo_handler) @init_radio def test_off_handler_that_was_not_bounded(self): ''' \"stopReplying\"", "def bar_handler(my_arg=222): return my_arg self.radio.reply('foo', foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo')", "self.assertRaises(ListenerNotFound): self.radio.request('foo') with self.assertRaises(ListenerNotFound): self.radio.request('bar') @init_radio def test_kwargs(self): ''' Keyword", "foo_handler) self.radio.reply('bar', bar_handler) self.assertEqual(self.radio.request('foo'), 'foo') self.assertEqual(self.radio.request('bar'), 222) self.assertEqual(self.radio.request('bar', 333), 333)" ]
[ "pass class APIResourcePatternError(APIError): \"\"\" Raised when an app tries to", "class APIResourcePatternError(APIError): \"\"\" Raised when an app tries to override", "app \"\"\" pass class APIResourcePatternError(APIError): \"\"\" Raised when an app", "Raised when an app tries to override an existing URL", "\"\"\" Base exception for the API app \"\"\" pass class", "APIError(Exception): \"\"\" Base exception for the API app \"\"\" pass", "exception for the API app \"\"\" pass class APIResourcePatternError(APIError): \"\"\"", "app tries to override an existing URL regular expression pattern", "<gh_stars>1-10 class APIError(Exception): \"\"\" Base exception for the API app", "an app tries to override an existing URL regular expression", "\"\"\" Raised when an app tries to override an existing", "the API app \"\"\" pass class APIResourcePatternError(APIError): \"\"\" Raised when", "APIResourcePatternError(APIError): \"\"\" Raised when an app tries to override an", "when an app tries to override an existing URL regular", "\"\"\" pass class APIResourcePatternError(APIError): \"\"\" Raised when an app tries", "Base exception for the API app \"\"\" pass class APIResourcePatternError(APIError):", "tries to override an existing URL regular expression pattern \"\"\"", "API app \"\"\" pass class APIResourcePatternError(APIError): \"\"\" Raised when an", "to override an existing URL regular expression pattern \"\"\" pass", "for the API app \"\"\" pass class APIResourcePatternError(APIError): \"\"\" Raised", "class APIError(Exception): \"\"\" Base exception for the API app \"\"\"" ]
[ "def test_lazy_access(field): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "import Sequence import pytest from jina import Request, QueryLang, Document", "in request_generator(random_docs(10))] for r in reqs: assert r.size == 0", "jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ): r = Request() r.request_type = typ", "now it is read assert r.is_used assert r.index.docs[0].id == '1'", "r.request.index.docs assert len(r.dump()) == 3 assert r.request.is_used def test_message_size(): reqs", "{'start': 3, 'end': 4}} q2 = QueryLang({'name': 'SliceQL', 'parameters': {'start':", "in reqs: assert not r.is_used # write access r.train r.index.ClearField('docs')", "request_generator(random_docs(10))] for r in reqs: assert not r.request.is_used assert r.envelope", "len({id(q) for q in r.queryset}) == 2 r2 = Request()", "3, 'end': 4}} q2 = QueryLang({'name': 'SliceQL', 'parameters': {'start': 3,", "r2.queryset}) == 2 r = Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for", "for idx, q in enumerate(r.queryset): assert q.priority == idx assert", "same assert len({id(q) for q in r.queryset}) == 2 r2", "assert not r.is_used # access r.train print(getattr(r, field)) # now", "import sys from typing import Sequence import pytest from jina", "from jina import Request, QueryLang, Document from jina.clients.request import request_generator", "sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) == 3 assert r.size > sys.getsizeof(r.envelope.SerializeToString()) \\", "r.is_used def test_lazy_nest_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "[Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))] for r in reqs:", "typ assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def", "2 r = Request() r.queryset.extend([q1, q2, q3]) assert isinstance(r.queryset, Sequence)", "= QueryLang({'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}, 'priority': 1})", "= 'SliceQL' q3.parameters['start'] = 3 q3.parameters['end'] = 4 q3.priority =", "pb_typ): r = Request() assert r.request_type is None with pytest.raises(ValueError):", "reqs: assert not r.is_used assert r assert not r.is_used for", "= 2 r = Request() r.queryset.extend([q1, q2, q3]) assert isinstance(r.queryset,", "3 assert q.parameters['end'] == 4 # q1 and q2 refer", "3 q3.parameters['end'] = 4 q3.priority = 2 r = Request()", "not r.is_used # access r.train print(getattr(r, field)) # now it", "r in reqs: assert not r.is_used assert r assert not", "r.queryset}) == 2 r2 = Request() r2.queryset.extend(r.queryset) assert len({id(q) for", "r.train r.ClearField('index') # now it is read assert r.is_used def", "pb_typ): r = Request() r.request_type = typ for _ in", "assert not r.request.is_used for r in reqs: assert not r.request.is_used", "r in reqs: assert not r.request.is_used assert r.envelope assert len(r.dump())", "in reqs: assert not r.request.is_used assert r.request.index.docs assert len(r.dump()) ==", "from typing import Sequence import pytest from jina import Request,", "# now it is read assert r.is_used def test_lazy_msg_access(): reqs", "r.is_used # write access r.train r.index.ClearField('docs') # now it is", "{'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}} q2 = QueryLang({'name':", "assert len(r.queryset) == 3 for idx, q in enumerate(r.queryset): assert", "r.request_type = 'index' # write access r.train r.docs.append(Document()) # now", "typing import Sequence import pytest from jina import Request, QueryLang,", "@pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ): r =", "for r in reqs: assert not r.request.is_used assert r.request.index.docs assert", "q.parameters['start'] == 3 assert q.parameters['end'] == 4 with pytest.raises(TypeError): r.queryset.extend(1)", "jina_pb2.RequestProto.ControlRequestProto.IDLE # now it is read assert r.is_used assert len(r.index.docs)", "r in reqs: assert not r.is_used r.request_type = 'index' #", "request_generator from jina.proto import jina_pb2 from jina.proto.jina_pb2 import EnvelopeProto from", "refer to the same assert len({id(q) for q in r.queryset})", "idx, q in enumerate(r.queryset): assert q.priority == idx assert q.parameters['start']", "= {'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}} q2 =", "jina_pb2.QueryLangProto() q3.name = 'SliceQL' q3.parameters['start'] = 3 q3.parameters['end'] = 4", "_trigger_fields.difference({'command', 'args', 'flush'})) def test_lazy_access(field): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "EnvelopeProto()) for r in request_generator(random_docs(10))] for r in reqs: assert", "r.request assert len(r.dump()) == 3 assert not r.request.is_used for r", "r.request_type = typ for _ in range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert", "+ sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "in range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs) == 10 assert len(r.groundtruths)", "for r in request_generator(random_docs(10))] for r in reqs: assert r.size", "len(r.dump()) == 3 assert r.request.is_used def test_message_size(): reqs = [Message(None,", "# write access r.train r.docs[0].id = '1' * 16 #", "r in request_generator(random_docs(10))) for r in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def", "len({id(q) for q in r2.queryset}) == 2 r = Request()", "not r.is_used # write access r.train r.docs[0].id = '1' *", "def test_lazy_request_fields(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "<reponame>Immich/jina import sys from typing import Sequence import pytest from", "r.docs[0].id = '1' * 16 # now it is read", "# write access r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE # now it", "q1 = {'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}} q2", "r.ClearField('index') # now it is read assert r.is_used def test_lazy_nested_clear_access():", "16 def test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "jina.proto.jina_pb2 import EnvelopeProto from jina.types.message import Message from jina.types.request import", "q3.name = 'SliceQL' q3.parameters['start'] = 3 q3.parameters['end'] = 4 q3.priority", "in reqs: assert not r.is_used assert r.index assert r.is_used def", "== idx assert q.parameters['start'] == 3 assert q.parameters['end'] == 4", "jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ): r =", "3 for idx, q in enumerate(r.queryset): assert q.priority == idx", "import _trigger_fields from tests import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'}))", "= jina_pb2.RequestProto.ControlRequestProto.IDLE # now it is read assert r.is_used assert", "for r in request_generator(random_docs(10))) for r in reqs: assert not", "for r in reqs: assert not r.is_used # write access", "test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "request_id='123', request_type='IndexRequest') for r in request_generator(random_docs(10))] for r in reqs:", "r.is_used assert r assert not r.is_used for r in reqs:", "request_generator(random_docs(10))] for r in reqs: assert r.size == 0 assert", "list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1 = {'name': 'SliceQL', 'parameters': {'start': 3,", "= typ for _ in range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs)", "3 assert r.request.is_used def test_message_size(): reqs = [Message(None, r, 'test',", "0 def test_lazy_append_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "assert r.is_used def test_multiple_access(): reqs = [Request(r.SerializeToString(), EnvelopeProto()) for r", "assert r.is_used def test_lazy_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "r = Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for idx, q in", "in request_generator(random_docs(10))) for r in reqs: assert not r.is_used #", "r = Request() r.request_type = typ for _ in range(10):", "r.is_used for r in reqs: assert not r.is_used assert r.index", "from jina.types.message import Message from jina.types.request import _trigger_fields from tests", "read assert r.is_used def test_lazy_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "r.is_used assert r.index assert r.is_used def test_lazy_nest_access(): reqs = (Request(r.SerializeToString(),", "assert q.parameters['end'] == 4 with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto),", "isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ):", "reqs: assert not r.is_used r.request_type = 'index' # write access", "not r.is_used # write access r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE #", "r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE # now it is read assert", "q3]) assert isinstance(r.queryset, Sequence) assert len(r.queryset) == 3 for idx,", "r.is_used assert len(r.index.docs) == 0 def test_lazy_append_access(): reqs = (Request(r.SerializeToString(),", "r.request.is_used assert r.envelope assert len(r.dump()) == 3 assert not r.request.is_used", "in reqs: assert r.size == 0 assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString())", "in reqs: assert not r.is_used assert r assert not r.is_used", "with pytest.raises(ValueError): print(r.body) r.request_type = typ assert r._request_type == typ", "jina import Request, QueryLang, Document from jina.clients.request import request_generator from", "enumerate(r.queryset): assert q.priority == idx assert q.parameters['start'] == 3 assert", "tests import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'})) def test_lazy_access(field): reqs", "# now it is read assert r.is_used assert len(r.index.docs) ==", "from tests import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'})) def test_lazy_access(field):", "import Request, QueryLang, Document from jina.clients.request import request_generator from jina.proto", "'test', '123', request_id='123', request_type='IndexRequest') for r in request_generator(random_docs(10))] for r", "it is read assert r.is_used def test_lazy_clear_access(): reqs = (Request(r.SerializeToString(),", "r.request.is_used for r in reqs: assert not r.request.is_used assert r.request", "for q in r.queryset}) == 2 r2 = Request() r2.queryset.extend(r.queryset)", "access r.train r.docs.append(Document()) # now it is read assert r.is_used", "in request_generator(random_docs(10))) for r in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset():", "('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ): r = Request() r.request_type =", "r2.queryset.extend(r.queryset) assert len({id(q) for q in r2.queryset}) == 2 r", "r in reqs: assert not r.is_used # write access r.train", "3, 'end': 4}, 'priority': 1}) q3 = jina_pb2.QueryLangProto() q3.name =", "access r.train r.docs[0].id = '1' * 16 # now it", "test_lazy_msg_access(): reqs = [Message(None, r.SerializeToString(), 'test', '123', request_id='123', request_type='IndexRequest') for", "= [Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))] for r in", "is None with pytest.raises(ValueError): print(r.body) r.request_type = typ assert r._request_type", "== '1' * 16 def test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "16 # now it is read assert r.is_used assert r.index.docs[0].id", "assert len({id(q) for q in r2.queryset}) == 2 r =", "r.is_used r.request_type = 'index' # write access r.train r.docs.append(Document()) #", "assert not r.is_used # write access r.train r.ClearField('index') # now", "r in reqs: assert r.size == 0 assert sys.getsizeof(r.envelope.SerializeToString()) assert", "4 q3.priority = 2 r = Request() r.queryset.extend([q1, q2, q3])", "Sequence) assert len(r.queryset) == 3 for idx, q in enumerate(r.queryset):", "idx assert q.parameters['start'] == 3 assert q.parameters['end'] == 4 #", "r.request.is_used assert r.request.index.docs assert len(r.dump()) == 3 assert r.request.is_used def", "assert r.size > sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs", "now it is read assert r.is_used def test_lazy_nested_clear_access(): reqs =", "q3 = jina_pb2.QueryLangProto() q3.name = 'SliceQL' q3.parameters['start'] = 3 q3.parameters['end']", "def test_lazy_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "== typ assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)])", "assert not r.request.is_used assert r.request.index.docs assert len(r.dump()) == 3 assert", "assert len(r.dump()) == 3 assert r.size > sys.getsizeof(r.envelope.SerializeToString()) \\ +", "Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for idx, q in enumerate(r.queryset): assert", "jina.proto import jina_pb2 from jina.proto.jina_pb2 import EnvelopeProto from jina.types.message import", "== 3 assert q.parameters['end'] == 4 with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ',", "r.request.is_used def test_message_size(): reqs = [Message(None, r, 'test', '123') for", "= 'index' # write access r.train r.docs.append(Document()) # now it", "assert r.is_used assert len(r.index.docs) == 0 def test_lazy_append_access(): reqs =", "reqs: assert not r.is_used # write access r.train r.ClearField('index') #", "test_lazy_nest_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "'args', 'flush'})) def test_lazy_access(field): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "reqs: assert r.size == 0 assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert", "r.request_type = typ assert r._request_type == typ assert isinstance(r.body, pb_typ)", "assert r.index assert r.is_used def test_lazy_nest_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "== 3 assert q.parameters['end'] == 4 # q1 and q2", "r in reqs: assert not r.is_used assert r.index assert r.is_used", "r.size == 0 assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) ==", "assert r.size == 0 assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump())", "is read assert r.is_used def test_lazy_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "[('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ,", "r.is_used # write access r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE # now", "import Message from jina.types.request import _trigger_fields from tests import random_docs", "2 r2 = Request() r2.queryset.extend(r.queryset) assert len({id(q) for q in", "assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) == 3 assert r.size > sys.getsizeof(r.envelope.SerializeToString())", "= Request() r.queryset.extend([q1, q2, q3]) assert isinstance(r.queryset, Sequence) assert len(r.queryset)", "r.is_used # write access r.train r.ClearField('index') # now it is", "assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) == 3 assert r.size", "access r.train print(getattr(r, field)) # now it is read assert", "pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ): r", "test_request_extend_queryset(): q1 = {'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}}", "q2 refer to the same assert len({id(q) for q in", "reqs = [Message(None, r.SerializeToString(), 'test', '123', request_id='123', request_type='IndexRequest') for r", "for r in request_generator(random_docs(10))] for r in reqs: assert not", "== 3 assert not r.request.is_used for r in reqs: assert", "'flush'})) def test_lazy_access(field): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "read assert r.is_used assert len(r.index.docs) == 0 def test_lazy_append_access(): reqs", "= Request() assert r.request_type is None with pytest.raises(ValueError): print(r.body) r.request_type", "4}, 'priority': 1}) q3 = jina_pb2.QueryLangProto() q3.name = 'SliceQL' q3.parameters['start']", "len(r.dump()) == 3 assert r.size > sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString())", "EnvelopeProto from jina.types.message import Message from jina.types.request import _trigger_fields from", "= 3 q3.parameters['end'] = 4 q3.priority = 2 r =", "r.SerializeToString(), 'test', '123', request_id='123', request_type='IndexRequest') for r in request_generator(random_docs(10))] for", "r = Request() assert r.request_type is None with pytest.raises(ValueError): print(r.body)", "== 3 assert r.size > sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString()) def", "assert not r.is_used # write access r.train r.index.ClearField('docs') # now", "# q1 and q2 refer to the same assert len({id(q)", "reqs: assert not r.is_used assert r.index assert r.is_used def test_lazy_nest_access():", "jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ): r = Request() assert", "test_add_doc_to_type(typ, pb_typ): r = Request() r.request_type = typ for _", "not r.is_used # write access r.train r.ClearField('index') # now it", "not r.request.is_used assert r.envelope assert len(r.dump()) == 3 assert not", "assert r._request_type == typ assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto),", "= Request() r2.queryset.extend(r.queryset) assert len({id(q) for q in r2.queryset}) ==", "to the same assert len({id(q) for q in r.queryset}) ==", "for r in reqs: assert not r.is_used assert r assert", "r._request_type == typ assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search',", "jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ): r = Request() assert r.request_type is", "len(r.index.docs) == 0 def test_lazy_append_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "'end': 4}, 'priority': 1}) q3 = jina_pb2.QueryLangProto() q3.name = 'SliceQL'", "now it is read assert r.is_used def test_lazy_clear_access(): reqs =", "isinstance(r.queryset, Sequence) assert len(r.queryset) == 3 for idx, q in", "q2 = QueryLang({'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}, 'priority':", "Request() r.request_type = typ for _ in range(10): r.docs.append(Document()) r.groundtruths.append(Document())", "def test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "assert r.request assert len(r.dump()) == 3 assert not r.request.is_used for", "read assert r.is_used def test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "assert q.priority == idx assert q.parameters['start'] == 3 assert q.parameters['end']", "r.train r.index.ClearField('docs') # now it is read assert r.is_used def", "== 2 r = Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for idx,", "> sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs = (Request(r.SerializeToString(),", "4}} q2 = QueryLang({'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4},", "is read assert r.is_used def test_multiple_access(): reqs = [Request(r.SerializeToString(), EnvelopeProto())", "[Message(None, r, 'test', '123') for r in request_generator(random_docs(10))] for r", "# write access r.train r.docs.append(Document()) # now it is read", "test_lazy_request_fields(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "q in r.queryset}) == 2 r2 = Request() r2.queryset.extend(r.queryset) assert", "assert len(r.index.docs) == 0 def test_lazy_append_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "r.is_used def test_lazy_msg_access(): reqs = [Message(None, r.SerializeToString(), 'test', '123', request_id='123',", "q in r2.queryset}) == 2 r = Request() r.queryset.append(q1) r.queryset.append(q2)", "\\ + sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "field)) # now it is read assert r.is_used def test_multiple_access():", "r.is_used assert r.index.docs[0].id == '1' * 16 def test_lazy_change_message_type(): reqs", "'priority': 1}) q3 = jina_pb2.QueryLangProto() q3.name = 'SliceQL' q3.parameters['start'] =", "4 # q1 and q2 refer to the same assert", "('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ): r = Request() assert r.request_type", "r.request_type is None with pytest.raises(ValueError): print(r.body) r.request_type = typ assert", "1}) q3 = jina_pb2.QueryLangProto() q3.name = 'SliceQL' q3.parameters['start'] = 3", "'SliceQL' q3.parameters['start'] = 3 q3.parameters['end'] = 4 q3.priority = 2", "r.is_used # access r.train print(getattr(r, field)) # now it is", "= 4 q3.priority = 2 r = Request() r.queryset.extend([q1, q2,", "('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ): r", "from jina.clients.request import request_generator from jina.proto import jina_pb2 from jina.proto.jina_pb2", "_ in range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs) == 10 assert", "import request_generator from jina.proto import jina_pb2 from jina.proto.jina_pb2 import EnvelopeProto", "write access r.train r.docs.append(Document()) # now it is read assert", "test_lazy_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "'123') for r in request_generator(random_docs(10))] for r in reqs: assert", "@pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def", "in enumerate(r.queryset): assert q.priority == idx assert q.parameters['start'] == 3", "sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "'end': 4}} q2 = QueryLang({'name': 'SliceQL', 'parameters': {'start': 3, 'end':", "print(r.body) r.request_type = typ assert r._request_type == typ assert isinstance(r.body,", "for _ in range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs) == 10", "= typ assert r._request_type == typ assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ',", "= jina_pb2.QueryLangProto() q3.name = 'SliceQL' q3.parameters['start'] = 3 q3.parameters['end'] =", "reqs = [Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))] for r", "print(getattr(r, field)) # now it is read assert r.is_used def", "assert r.is_used assert r.index.docs[0].id == '1' * 16 def test_lazy_change_message_type():", "{'start': 3, 'end': 4}, 'priority': 1}) q3 = jina_pb2.QueryLangProto() q3.name", "it is read assert r.is_used assert len(r.index.docs) == 0 def", "write access r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE # now it is", "the same assert len({id(q) for q in r.queryset}) == 2", "test_lazy_append_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "r.train print(getattr(r, field)) # now it is read assert r.is_used", "r in request_generator(random_docs(10))] for r in reqs: assert r.size ==", "Sequence import pytest from jina import Request, QueryLang, Document from", "assert r.request_type is None with pytest.raises(ValueError): print(r.body) r.request_type = typ", "r, 'test', '123') for r in request_generator(random_docs(10))] for r in", "'index' # write access r.train r.docs.append(Document()) # now it is", "for q in r2.queryset}) == 2 r = Request() r.queryset.append(q1)", "Request, QueryLang, Document from jina.clients.request import request_generator from jina.proto import", "r in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1 = {'name':", "is read assert r.is_used assert r.index.docs[0].id == '1' * 16", "r in reqs: assert not r.request.is_used assert r.request.index.docs assert len(r.dump())", "for r in reqs: assert not r.is_used assert r.index assert", "not r.request.is_used assert r.request.index.docs assert len(r.dump()) == 3 assert r.request.is_used", "r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for idx, q in enumerate(r.queryset): assert q.priority", "# write access r.train r.index.ClearField('docs') # now it is read", "read assert r.is_used assert r.index.docs[0].id == '1' * 16 def", "for r in reqs: assert not r.is_used r.request_type = 'index'", "# now it is read assert r.is_used def test_multiple_access(): reqs", "= [Message(None, r.SerializeToString(), 'test', '123', request_id='123', request_type='IndexRequest') for r in", "r.size > sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs =", "r.index.docs[0].id == '1' * 16 def test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(),", "request_generator(random_docs(10))) for r in reqs: assert not r.is_used # write", "= Request() r.request_type = typ for _ in range(10): r.docs.append(Document())", "@pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'})) def test_lazy_access(field): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "test_empty_request_type(typ, pb_typ): r = Request() assert r.request_type is None with", "now it is read assert r.is_used def test_lazy_msg_access(): reqs =", "for r in reqs: assert not r.request.is_used assert r.envelope assert", "Request() r2.queryset.extend(r.queryset) assert len({id(q) for q in r2.queryset}) == 2", "assert r.is_used def test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "r.docs.append(Document()) # now it is read assert r.is_used def test_lazy_clear_access():", "not r.is_used r.request_type = 'index' # write access r.train r.docs.append(Document())", "reqs: assert not r.is_used # write access r.train r.index.ClearField('docs') #", "not r.is_used for r in reqs: assert not r.is_used assert", "4 with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search',", "EnvelopeProto()) for r in request_generator(random_docs(10))) for r in reqs: assert", "# access r.train print(getattr(r, field)) # now it is read", "0 assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) == 3 assert", "request_generator(random_docs(10))) for r in reqs: assert not r.is_used r.request_type =", "('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ): r = Request()", "def test_lazy_append_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "access r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE # now it is read", "assert not r.is_used assert r.index assert r.is_used def test_lazy_nest_access(): reqs", "not r.is_used # write access r.train r.index.ClearField('docs') # now it", "in reqs: assert not r.is_used # access r.train print(getattr(r, field))", "import EnvelopeProto from jina.types.message import Message from jina.types.request import _trigger_fields", "Request() r.queryset.extend([q1, q2, q3]) assert isinstance(r.queryset, Sequence) assert len(r.queryset) ==", "reqs: assert not r.is_used # write access r.train r.docs[0].id =", "for r in request_generator(random_docs(10))) for r in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys())", "== 0 def test_lazy_append_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto),", "import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'})) def test_lazy_access(field): reqs =", "'1' * 16 # now it is read assert r.is_used", "assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ,", "_trigger_fields from tests import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'})) def", "for r in reqs: assert r.size == 0 assert sys.getsizeof(r.envelope.SerializeToString())", "pytest.raises(ValueError): print(r.body) r.request_type = typ assert r._request_type == typ assert", "== 0 assert sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) == 3", "reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1 = {'name': 'SliceQL', 'parameters':", "3 assert r.size > sys.getsizeof(r.envelope.SerializeToString()) \\ + sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields():", "it is read assert r.is_used assert r.index.docs[0].id == '1' *", "it is read assert r.is_used def test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(),", "pytest from jina import Request, QueryLang, Document from jina.clients.request import", "assert not r.is_used for r in reqs: assert not r.is_used", "def test_lazy_msg_access(): reqs = [Message(None, r.SerializeToString(), 'test', '123', request_id='123', request_type='IndexRequest')", "test_message_size(): reqs = [Message(None, r, 'test', '123') for r in", "in reqs: assert not r.is_used r.request_type = 'index' # write", "from jina.types.request import _trigger_fields from tests import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command',", "assert r.is_used def test_lazy_nest_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "[('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ): r = Request()", "q in enumerate(r.queryset): assert q.priority == idx assert q.parameters['start'] ==", "# now it is read assert r.is_used assert r.index.docs[0].id ==", "reqs: assert not r.request.is_used assert r.request.index.docs assert len(r.dump()) == 3", "assert len(r.dump()) == 3 assert r.request.is_used def test_message_size(): reqs =", "r.request.is_used for r in reqs: assert not r.request.is_used assert r.request.index.docs", "r2 = Request() r2.queryset.extend(r.queryset) assert len({id(q) for q in r2.queryset})", "from jina.proto.jina_pb2 import EnvelopeProto from jina.types.message import Message from jina.types.request", "== 3 assert r.request.is_used def test_message_size(): reqs = [Message(None, r,", "request_generator(random_docs(10))) for r in reqs: assert not r.is_used # access", "reqs: assert not r.is_used # write access r.train r.control.command =", "q2, q3]) assert isinstance(r.queryset, Sequence) assert len(r.queryset) == 3 for", "* 16 # now it is read assert r.is_used assert", "import pytest from jina import Request, QueryLang, Document from jina.clients.request", "request_generator(random_docs(10))) for r in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1", "sys from typing import Sequence import pytest from jina import", "assert not r.is_used # write access r.train r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE", "None with pytest.raises(ValueError): print(r.body) r.request_type = typ assert r._request_type ==", "from jina.proto import jina_pb2 from jina.proto.jina_pb2 import EnvelopeProto from jina.types.message", "[Message(None, r.SerializeToString(), 'test', '123', request_id='123', request_type='IndexRequest') for r in request_generator(random_docs(10))]", "r in request_generator(random_docs(10))) for r in reqs: assert not r.is_used", "= (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for r in", "'parameters': {'start': 3, 'end': 4}, 'priority': 1}) q3 = jina_pb2.QueryLangProto()", "in r2.queryset}) == 2 r = Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3)", "access r.train r.index.ClearField('docs') # now it is read assert r.is_used", "== 4 with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto),", "typ assert r._request_type == typ assert isinstance(r.body, pb_typ) @pytest.mark.parametrize('typ,pb_typ', [('index',", "jina_pb2 from jina.proto.jina_pb2 import EnvelopeProto from jina.types.message import Message from", "'123', request_id='123', request_type='IndexRequest') for r in request_generator(random_docs(10))] for r in", "random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args', 'flush'})) def test_lazy_access(field): reqs = (Request(r.SerializeToString(),", "is read assert r.is_used assert len(r.index.docs) == 0 def test_lazy_append_access():", "r.queryset.extend([q1, q2, q3]) assert isinstance(r.queryset, Sequence) assert len(r.queryset) == 3", "jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)]) def test_empty_request_type(typ, pb_typ):", "assert r assert not r.is_used for r in reqs: assert", "r.index.ClearField('docs') # now it is read assert r.is_used def test_lazy_msg_access():", "QueryLang, Document from jina.clients.request import request_generator from jina.proto import jina_pb2", "'test', '123') for r in request_generator(random_docs(10))] for r in reqs:", "assert q.parameters['start'] == 3 assert q.parameters['end'] == 4 with pytest.raises(TypeError):", "q3.parameters['start'] = 3 q3.parameters['end'] = 4 q3.priority = 2 r", "it is read assert r.is_used def test_multiple_access(): reqs = [Request(r.SerializeToString(),", "r.is_used def test_lazy_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "assert q.parameters['start'] == 3 assert q.parameters['end'] == 4 # q1", "len(r.queryset) == 3 for idx, q in enumerate(r.queryset): assert q.priority", "assert not r.request.is_used assert r.envelope assert len(r.dump()) == 3 assert", "not r.request.is_used assert r.request assert len(r.dump()) == 3 assert not", "'SliceQL', 'parameters': {'start': 3, 'end': 4}, 'priority': 1}) q3 =", "read assert r.is_used def test_lazy_msg_access(): reqs = [Message(None, r.SerializeToString(), 'test',", "assert not r.request.is_used assert r.request assert len(r.dump()) == 3 assert", "def test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs) == 10 assert len(r.groundtruths) == 10", "r.request.is_used assert r.request assert len(r.dump()) == 3 assert not r.request.is_used", "assert q.parameters['end'] == 4 # q1 and q2 refer to", "sys.getsizeof(r.envelope.SerializeToString()) assert sys.getsizeof(r.request.SerializeToString()) assert len(r.dump()) == 3 assert r.size >", "QueryLang({'name': 'SliceQL', 'parameters': {'start': 3, 'end': 4}, 'priority': 1}) q3", "reqs: assert not r.request.is_used assert r.envelope assert len(r.dump()) == 3", "in request_generator(random_docs(10))] for r in reqs: assert not r.request.is_used assert", "assert r.request.is_used def test_message_size(): reqs = [Message(None, r, 'test', '123')", "r in request_generator(random_docs(10))] for r in reqs: assert not r.request.is_used", "test_multiple_access(): reqs = [Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))] for", "len(r.dump()) == 3 assert not r.request.is_used for r in reqs:", "in reqs: assert not r.is_used # write access r.train r.control.command", "write access r.train r.docs[0].id = '1' * 16 # now", "def test_empty_request_type(typ, pb_typ): r = Request() assert r.request_type is None", "r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control', jina_pb2.RequestProto.ControlRequestProto)])", "2 r = Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for idx, q", "r.queryset.append(q3) for idx, q in enumerate(r.queryset): assert q.priority == idx", "jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto)]) def test_add_doc_to_type(typ, pb_typ): r = Request() r.request_type", "assert not r.is_used assert r assert not r.is_used for r", "(Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for r in reqs:", "== 2 r2 = Request() r2.queryset.extend(r.queryset) assert len({id(q) for q", "assert not r.is_used # write access r.train r.docs[0].id = '1'", "test_lazy_access(field): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "q1 and q2 refer to the same assert len({id(q) for", "not r.is_used assert r.index assert r.is_used def test_lazy_nest_access(): reqs =", "pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index', jina_pb2.RequestProto.IndexRequestProto), ('search', jina_pb2.RequestProto.SearchRequestProto), ('control',", "write access r.train r.index.ClearField('docs') # now it is read assert", "# now it is read assert r.is_used def test_lazy_clear_access(): reqs", "assert r.index.docs[0].id == '1' * 16 def test_lazy_change_message_type(): reqs =", "assert r.is_used def test_lazy_msg_access(): reqs = [Message(None, r.SerializeToString(), 'test', '123',", "q3.parameters['end'] = 4 q3.priority = 2 r = Request() r.queryset.extend([q1,", "jina.types.message import Message from jina.types.request import _trigger_fields from tests import", "in request_generator(random_docs(10))) for r in reqs: assert not r.is_used r.request_type", "assert r.request.index.docs assert len(r.dump()) == 3 assert r.request.is_used def test_message_size():", "q.parameters['end'] == 4 # q1 and q2 refer to the", "idx assert q.parameters['start'] == 3 assert q.parameters['end'] == 4 with", "Request() assert r.request_type is None with pytest.raises(ValueError): print(r.body) r.request_type =", "range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs) == 10 assert len(r.groundtruths) ==", "q.priority == idx assert q.parameters['start'] == 3 assert q.parameters['end'] ==", "def test_message_size(): reqs = [Message(None, r, 'test', '123') for r", "= Request() r.queryset.append(q1) r.queryset.append(q2) r.queryset.append(q3) for idx, q in enumerate(r.queryset):", "Document from jina.clients.request import request_generator from jina.proto import jina_pb2 from", "def test_multiple_access(): reqs = [Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))]", "read assert r.is_used def test_multiple_access(): reqs = [Request(r.SerializeToString(), EnvelopeProto()) for", "now it is read assert r.is_used def test_multiple_access(): reqs =", "def test_lazy_nest_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10)))", "request_generator(random_docs(10))] for r in reqs: assert not r.is_used assert r", "now it is read assert r.is_used assert len(r.index.docs) == 0", "r.control.command = jina_pb2.RequestProto.ControlRequestProto.IDLE # now it is read assert r.is_used", "'parameters': {'start': 3, 'end': 4}} q2 = QueryLang({'name': 'SliceQL', 'parameters':", "sys.getsizeof(r.request.SerializeToString()) def test_lazy_request_fields(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "request_type='IndexRequest') for r in request_generator(random_docs(10))] for r in reqs: assert", "assert isinstance(r.queryset, Sequence) assert len(r.queryset) == 3 for idx, q", "in r.queryset}) == 2 r2 = Request() r2.queryset.extend(r.queryset) assert len({id(q)", "r.train r.docs[0].id = '1' * 16 # now it is", "in reqs: assert not r.request.is_used assert r.request assert len(r.dump()) ==", "q.parameters['start'] == 3 assert q.parameters['end'] == 4 # q1 and", "for r in reqs: assert not r.is_used # access r.train", "jina.types.request import _trigger_fields from tests import random_docs @pytest.mark.parametrize('field', _trigger_fields.difference({'command', 'args',", "3 assert q.parameters['end'] == 4 with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train',", "test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for", "def test_request_extend_queryset(): q1 = {'name': 'SliceQL', 'parameters': {'start': 3, 'end':", "r in request_generator(random_docs(10))] for r in reqs: assert not r.is_used", "in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1 = {'name': 'SliceQL',", "def test_add_doc_to_type(typ, pb_typ): r = Request() r.request_type = typ for", "not r.is_used assert r assert not r.is_used for r in", "'SliceQL', 'parameters': {'start': 3, 'end': 4}} q2 = QueryLang({'name': 'SliceQL',", "r.is_used # write access r.train r.docs[0].id = '1' * 16", "assert not r.is_used r.request_type = 'index' # write access r.train", "= '1' * 16 # now it is read assert", "reqs = [Message(None, r, 'test', '123') for r in request_generator(random_docs(10))]", "in reqs: assert not r.request.is_used assert r.envelope assert len(r.dump()) ==", "assert len({id(q) for q in r.queryset}) == 2 r2 =", "in reqs: assert not r.is_used # write access r.train r.docs[0].id", "Message from jina.types.request import _trigger_fields from tests import random_docs @pytest.mark.parametrize('field',", "assert r.envelope assert len(r.dump()) == 3 assert not r.request.is_used for", "q.parameters['end'] == 4 with pytest.raises(TypeError): r.queryset.extend(1) @pytest.mark.parametrize('typ,pb_typ', [('train', jina_pb2.RequestProto.TrainRequestProto), ('index',", "r.queryset.append(q2) r.queryset.append(q3) for idx, q in enumerate(r.queryset): assert q.priority ==", "'1' * 16 def test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "it is read assert r.is_used def test_lazy_msg_access(): reqs = [Message(None,", "and q2 refer to the same assert len({id(q) for q", "r assert not r.is_used for r in reqs: assert not", "3 assert not r.request.is_used for r in reqs: assert not", "for r in reqs: assert not r.request.is_used assert r.request assert", "reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in request_generator(random_docs(10))) for r", "r = Request() r.queryset.extend([q1, q2, q3]) assert isinstance(r.queryset, Sequence) assert", "in request_generator(random_docs(10))] for r in reqs: assert not r.is_used assert", "r in reqs: assert not r.request.is_used assert r.request assert len(r.dump())", "r.is_used def test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r in", "= [Message(None, r, 'test', '123') for r in request_generator(random_docs(10))] for", "assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1 = {'name': 'SliceQL', 'parameters': {'start':", "assert len(r.dump()) == 3 assert not r.request.is_used for r in", "for r in reqs: assert list(r.DESCRIPTOR.fields_by_name.keys()) def test_request_extend_queryset(): q1 =", "# now it is read assert r.is_used def test_lazy_nested_clear_access(): reqs", "import jina_pb2 from jina.proto.jina_pb2 import EnvelopeProto from jina.types.message import Message", "is read assert r.is_used def test_lazy_msg_access(): reqs = [Message(None, r.SerializeToString(),", "q3.priority = 2 r = Request() r.queryset.extend([q1, q2, q3]) assert", "== 4 # q1 and q2 refer to the same", "r.train r.docs.append(Document()) # now it is read assert r.is_used def", "r.is_used def test_multiple_access(): reqs = [Request(r.SerializeToString(), EnvelopeProto()) for r in", "r.envelope assert len(r.dump()) == 3 assert not r.request.is_used for r", "access r.train r.ClearField('index') # now it is read assert r.is_used", "jina.clients.request import request_generator from jina.proto import jina_pb2 from jina.proto.jina_pb2 import", "in reqs: assert not r.is_used # write access r.train r.ClearField('index')", "== 3 for idx, q in enumerate(r.queryset): assert q.priority ==", "typ for _ in range(10): r.docs.append(Document()) r.groundtruths.append(Document()) assert len(r.docs) ==", "reqs: assert not r.request.is_used assert r.request assert len(r.dump()) == 3", "is read assert r.is_used def test_lazy_nested_clear_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto())", "r.index assert r.is_used def test_lazy_nest_access(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for", "not r.request.is_used for r in reqs: assert not r.request.is_used assert", "# write access r.train r.ClearField('index') # now it is read", "r in reqs: assert not r.is_used # access r.train print(getattr(r,", "reqs: assert not r.is_used # access r.train print(getattr(r, field)) #", "* 16 def test_lazy_change_message_type(): reqs = (Request(r.SerializeToString(), EnvelopeProto()) for r", "write access r.train r.ClearField('index') # now it is read assert" ]
[ "__file__ ) ) def Settings( **kwargs ): return { 'interpreter_path':", "Settings( **kwargs ): return { 'interpreter_path': sys.executable, 'sys_path': [ os.path.join(", "import os import sys DIR_OF_THIS_SCRIPT = os.path.abspath( os.path.dirname( __file__ )", "DIR_OF_THIS_SCRIPT = os.path.abspath( os.path.dirname( __file__ ) ) def Settings( **kwargs", "sys DIR_OF_THIS_SCRIPT = os.path.abspath( os.path.dirname( __file__ ) ) def Settings(", "= os.path.abspath( os.path.dirname( __file__ ) ) def Settings( **kwargs ):", ") def Settings( **kwargs ): return { 'interpreter_path': sys.executable, 'sys_path':", "os.path.abspath( os.path.dirname( __file__ ) ) def Settings( **kwargs ): return", "): return { 'interpreter_path': sys.executable, 'sys_path': [ os.path.join( DIR_OF_THIS_SCRIPT, 'third_party'", "'interpreter_path': sys.executable, 'sys_path': [ os.path.join( DIR_OF_THIS_SCRIPT, 'third_party' ) ] }", "def Settings( **kwargs ): return { 'interpreter_path': sys.executable, 'sys_path': [", "return { 'interpreter_path': sys.executable, 'sys_path': [ os.path.join( DIR_OF_THIS_SCRIPT, 'third_party' )", "os.path.dirname( __file__ ) ) def Settings( **kwargs ): return {", "{ 'interpreter_path': sys.executable, 'sys_path': [ os.path.join( DIR_OF_THIS_SCRIPT, 'third_party' ) ]", "os import sys DIR_OF_THIS_SCRIPT = os.path.abspath( os.path.dirname( __file__ ) )", "**kwargs ): return { 'interpreter_path': sys.executable, 'sys_path': [ os.path.join( DIR_OF_THIS_SCRIPT,", ") ) def Settings( **kwargs ): return { 'interpreter_path': sys.executable,", "import sys DIR_OF_THIS_SCRIPT = os.path.abspath( os.path.dirname( __file__ ) ) def" ]
[ "author_email='<EMAIL>', packages=[ 'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License', description='Utils", "description='Utils for the SmartCache project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating", "SmartCache project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System :: POSIX", "project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System :: POSIX ::", "OSI Approved :: Apache 2.0 License\", \"Programming Language :: Python", "setup( name='utils', version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[ 'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache',", "\"License :: OSI Approved :: Apache 2.0 License\", \"Programming Language", "classifier=[ \"Operating System :: POSIX :: Linux\", \"License :: OSI", "], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License', description='Utils for the SmartCache", "System :: POSIX :: Linux\", \"License :: OSI Approved ::", "url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License', description='Utils for the SmartCache project', long_description=\"To", "packages=[ 'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License', description='Utils for", ":: OSI Approved :: Apache 2.0 License\", \"Programming Language ::", "from distutils.core import setup setup( name='utils', version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[", "2.0 License', description='Utils for the SmartCache project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(),", "the SmartCache project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System ::", "license='Apache 2.0 License', description='Utils for the SmartCache project', long_description=\"To do...\",", "2.0 License\", \"Programming Language :: Python :: 3 :: Only\"", ":: POSIX :: Linux\", \"License :: OSI Approved :: Apache", "Linux\", \"License :: OSI Approved :: Apache 2.0 License\", \"Programming", "version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[ 'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0", "do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System :: POSIX :: Linux\", \"License", "POSIX :: Linux\", \"License :: OSI Approved :: Apache 2.0", ":: Apache 2.0 License\", \"Programming Language :: Python :: 3", "Apache 2.0 License\", \"Programming Language :: Python :: 3 ::", "License\", \"Programming Language :: Python :: 3 :: Only\" ]", "for the SmartCache project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System", "'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License', description='Utils for the", "distutils.core import setup setup( name='utils', version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[ 'utils',", "scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License', description='Utils for the SmartCache project',", "\"Operating System :: POSIX :: Linux\", \"License :: OSI Approved", "Approved :: Apache 2.0 License\", \"Programming Language :: Python ::", "author='<NAME>', author_email='<EMAIL>', packages=[ 'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache 2.0 License',", "install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System :: POSIX :: Linux\", \"License ::", "\"Programming Language :: Python :: 3 :: Only\" ] )", "name='utils', version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[ 'utils', ], scripts=[], url='https://github.com/Cloud-PG/smart-cache', license='Apache", "setup setup( name='utils', version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[ 'utils', ], scripts=[],", "import setup setup( name='utils', version='1.0.0', author='<NAME>', author_email='<EMAIL>', packages=[ 'utils', ],", ":: Linux\", \"License :: OSI Approved :: Apache 2.0 License\",", "License', description='Utils for the SmartCache project', long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[", "long_description=\"To do...\", install_requires=open(\"requirements.txt\").read(), classifier=[ \"Operating System :: POSIX :: Linux\"," ]
[ "a Eight Sleep heat-based sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY def __init__(", "<gh_stars>1-10 \"\"\"Support for Eight Sleep binary sensors.\"\"\" from __future__ import", "EightSleep, user_id: str | None, sensor: str, ) -> None:", "None: return eight: EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT]", "entities.append( EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\") ) async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity):", "in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\") ) async_add_entities(entities) class", "-> bool: \"\"\"Return true if the binary sensor is on.\"\"\"", "from . import EightSleepBaseEntity from .const import DATA_API, DATA_HEAT, DOMAIN", "EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities = []", "DataUpdateCoordinator, eight: EightSleep, user_id: str | None, sensor: str, )", "bool: \"\"\"Return true if the binary sensor is on.\"\"\" assert", "None = None, ) -> None: \"\"\"Set up the eight", "async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info:", "HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None =", "ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )", "up the eight sleep binary sensor.\"\"\" if discovery_info is None:", "async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType |", "\"Presence Sensor: %s, Side: %s, User: %s\", sensor, self._user_obj.side, user_id,", "hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None", "None: \"\"\"Set up the eight sleep binary sensor.\"\"\" if discovery_info", "DiscoveryInfoType | None = None, ) -> None: \"\"\"Set up", "eight: EightSleep, user_id: str | None, sensor: str, ) ->", "eight, user_id, sensor) assert self._user_obj _LOGGER.debug( \"Presence Sensor: %s, Side:", "hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities = [] for user", "for Eight Sleep binary sensors.\"\"\" from __future__ import annotations import", "from __future__ import annotations import logging from pyeight.eight import EightSleep", "_attr_device_class = BinarySensorDeviceClass.OCCUPANCY def __init__( self, coordinator: DataUpdateCoordinator, eight: EightSleep,", "from .const import DATA_API, DATA_HEAT, DOMAIN _LOGGER = logging.getLogger(__name__) async", "class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of a Eight Sleep heat-based sensor.\"\"\"", "@property def is_on(self) -> bool: \"\"\"Return true if the binary", "EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\") ) async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation", "pyeight.eight import EightSleep from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, )", "heat-based sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY def __init__( self, coordinator: DataUpdateCoordinator,", "import DataUpdateCoordinator from . import EightSleepBaseEntity from .const import DATA_API,", "from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from", "sensor: str, ) -> None: \"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator, eight,", "logging from pyeight.eight import EightSleep from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass,", "HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType", "DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities = [] for user in eight.users.values():", "true if the binary sensor is on.\"\"\" assert self._user_obj return", "| None, sensor: str, ) -> None: \"\"\"Initialize the sensor.\"\"\"", "import EightSleepBaseEntity from .const import DATA_API, DATA_HEAT, DOMAIN _LOGGER =", "\"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator, eight, user_id, sensor) assert self._user_obj _LOGGER.debug(", "None, sensor: str, ) -> None: \"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator,", "from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from", "%s, Side: %s, User: %s\", sensor, self._user_obj.side, user_id, ) @property", "import EightSleep from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from", "= hass.data[DOMAIN][DATA_HEAT] entities = [] for user in eight.users.values(): entities.append(", "Sleep heat-based sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY def __init__( self, coordinator:", "self, coordinator: DataUpdateCoordinator, eight: EightSleep, user_id: str | None, sensor:", "DATA_HEAT, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant,", "eight, user.userid, \"bed_presence\") ) async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of", "None, ) -> None: \"\"\"Set up the eight sleep binary", "discovery_info: DiscoveryInfoType | None = None, ) -> None: \"\"\"Set", "for user in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\") )", "BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback", "the sensor.\"\"\" super().__init__(coordinator, eight, user_id, sensor) assert self._user_obj _LOGGER.debug( \"Presence", "from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import", "from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing", "eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\") ) async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity,", "return eight: EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities", "__init__( self, coordinator: DataUpdateCoordinator, eight: EightSleep, user_id: str | None,", "[] for user in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\")", "hass.data[DOMAIN][DATA_HEAT] entities = [] for user in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator,", "str, ) -> None: \"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator, eight, user_id,", "= BinarySensorDeviceClass.OCCUPANCY def __init__( self, coordinator: DataUpdateCoordinator, eight: EightSleep, user_id:", ") -> None: \"\"\"Set up the eight sleep binary sensor.\"\"\"", "%s, User: %s\", sensor, self._user_obj.side, user_id, ) @property def is_on(self)", "import annotations import logging from pyeight.eight import EightSleep from homeassistant.components.binary_sensor", "import DATA_API, DATA_HEAT, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_platform(", "_LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant, config: ConfigType,", "sensor.\"\"\" if discovery_info is None: return eight: EightSleep = hass.data[DOMAIN][DATA_API]", "| None = None, ) -> None: \"\"\"Set up the", "%s\", sensor, self._user_obj.side, user_id, ) @property def is_on(self) -> bool:", "import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType,", "discovery_info is None: return eight: EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator", "from pyeight.eight import EightSleep from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity,", "import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator import", ") async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of a Eight Sleep", "ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import EightSleepBaseEntity", "str | None, sensor: str, ) -> None: \"\"\"Initialize the", "if the binary sensor is on.\"\"\" assert self._user_obj return bool(self._user_obj.bed_presence)", "\"\"\"Representation of a Eight Sleep heat-based sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY", "assert self._user_obj _LOGGER.debug( \"Presence Sensor: %s, Side: %s, User: %s\",", ") @property def is_on(self) -> bool: \"\"\"Return true if the", "= hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities = [] for", "import logging from pyeight.eight import EightSleep from homeassistant.components.binary_sensor import (", "BinarySensorDeviceClass.OCCUPANCY def __init__( self, coordinator: DataUpdateCoordinator, eight: EightSleep, user_id: str", ".const import DATA_API, DATA_HEAT, DOMAIN _LOGGER = logging.getLogger(__name__) async def", "-> None: \"\"\"Set up the eight sleep binary sensor.\"\"\" if", "= [] for user in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight, user.userid,", "heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities = [] for user in", ") -> None: \"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator, eight, user_id, sensor)", "BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import", "import ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import", "user_id, sensor) assert self._user_obj _LOGGER.debug( \"Presence Sensor: %s, Side: %s,", "if discovery_info is None: return eight: EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator:", "async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of a Eight Sleep heat-based", "homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator", "is_on(self) -> bool: \"\"\"Return true if the binary sensor is", "binary sensor.\"\"\" if discovery_info is None: return eight: EightSleep =", "Sensor: %s, Side: %s, User: %s\", sensor, self._user_obj.side, user_id, )", "sensor.\"\"\" super().__init__(coordinator, eight, user_id, sensor) assert self._user_obj _LOGGER.debug( \"Presence Sensor:", "\"\"\"Support for Eight Sleep binary sensors.\"\"\" from __future__ import annotations", "\"bed_presence\") ) async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of a Eight", "self._user_obj.side, user_id, ) @property def is_on(self) -> bool: \"\"\"Return true", "sensor) assert self._user_obj _LOGGER.debug( \"Presence Sensor: %s, Side: %s, User:", "sleep binary sensor.\"\"\" if discovery_info is None: return eight: EightSleep", "def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType", "import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from", "( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform", "user in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight, user.userid, \"bed_presence\") ) async_add_entities(entities)", "_LOGGER.debug( \"Presence Sensor: %s, Side: %s, User: %s\", sensor, self._user_obj.side,", "Side: %s, User: %s\", sensor, self._user_obj.side, user_id, ) @property def", "user_id: str | None, sensor: str, ) -> None: \"\"\"Initialize", "def is_on(self) -> bool: \"\"\"Return true if the binary sensor", "homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .", "coordinator: DataUpdateCoordinator, eight: EightSleep, user_id: str | None, sensor: str,", "-> None: \"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator, eight, user_id, sensor) assert", "BinarySensorEntity): \"\"\"Representation of a Eight Sleep heat-based sensor.\"\"\" _attr_device_class =", "Sleep binary sensors.\"\"\" from __future__ import annotations import logging from", "EightSleep from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core", "EightSleepBaseEntity from .const import DATA_API, DATA_HEAT, DOMAIN _LOGGER = logging.getLogger(__name__)", "homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import EightSleepBaseEntity from .const import", "= logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities:", ". import EightSleepBaseEntity from .const import DATA_API, DATA_HEAT, DOMAIN _LOGGER", "\"\"\"Return true if the binary sensor is on.\"\"\" assert self._user_obj", "DATA_API, DATA_HEAT, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass:", "None: \"\"\"Initialize the sensor.\"\"\" super().__init__(coordinator, eight, user_id, sensor) assert self._user_obj", "the eight sleep binary sensor.\"\"\" if discovery_info is None: return", "async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) ->", "super().__init__(coordinator, eight, user_id, sensor) assert self._user_obj _LOGGER.debug( \"Presence Sensor: %s,", "is None: return eight: EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator =", "eight sleep binary sensor.\"\"\" if discovery_info is None: return eight:", "AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator", "__future__ import annotations import logging from pyeight.eight import EightSleep from", "DataUpdateCoordinator from . import EightSleepBaseEntity from .const import DATA_API, DATA_HEAT,", "sensors.\"\"\" from __future__ import annotations import logging from pyeight.eight import", "of a Eight Sleep heat-based sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY def", "entities = [] for user in eight.users.values(): entities.append( EightHeatSensor(heat_coordinator, eight,", "\"\"\"Set up the eight sleep binary sensor.\"\"\" if discovery_info is", "DiscoveryInfoType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import EightSleepBaseEntity from", "DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant, config:", "config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None,", "EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of a Eight Sleep heat-based sensor.\"\"\" _attr_device_class", "Eight Sleep binary sensors.\"\"\" from __future__ import annotations import logging", "self._user_obj _LOGGER.debug( \"Presence Sensor: %s, Side: %s, User: %s\", sensor,", "= None, ) -> None: \"\"\"Set up the eight sleep", "def __init__( self, coordinator: DataUpdateCoordinator, eight: EightSleep, user_id: str |", "user.userid, \"bed_presence\") ) async_add_entities(entities) class EightHeatSensor(EightSleepBaseEntity, BinarySensorEntity): \"\"\"Representation of a", "annotations import logging from pyeight.eight import EightSleep from homeassistant.components.binary_sensor import", "logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback,", "eight: EightSleep = hass.data[DOMAIN][DATA_API] heat_coordinator: DataUpdateCoordinator = hass.data[DOMAIN][DATA_HEAT] entities =", "Eight Sleep heat-based sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY def __init__( self,", "binary sensors.\"\"\" from __future__ import annotations import logging from pyeight.eight", "User: %s\", sensor, self._user_obj.side, user_id, ) @property def is_on(self) ->", "user_id, ) @property def is_on(self) -> bool: \"\"\"Return true if", "homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant", "homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import", ") from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from", "AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None:", "sensor.\"\"\" _attr_device_class = BinarySensorDeviceClass.OCCUPANCY def __init__( self, coordinator: DataUpdateCoordinator, eight:", "sensor, self._user_obj.side, user_id, ) @property def is_on(self) -> bool: \"\"\"Return", "from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import EightSleepBaseEntity from .const" ]
[ "('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test',", "session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True)", "mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda", "ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'this is unexpected' log", "is unexpected' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message ==", "session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock()", "'test'} response.raise_for_status.return_value = False request.return_value = response token = 'foo'", ")) def test_params_generated(mocker, params): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock()", "('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def test_unexpected_exception_is_logged(mocker, caplog, method,", "import pytest from requests.exceptions import HTTPError, Timeout from indico.testing.util import", "('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/',", ")) def test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url): request = mocker.patch('indico_ravem.util.requests.request') response", "'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url):", "session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' event_vc_room = MagicMock() event_vc_room.link_object.room", "pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'this", "assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request') request.remote_addr", "{}), ('get', {'p1': '1stparam'}), ('post', {'p1': '1stparam'}), ('get', {'p1': '1stparam',", "== expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {}, {'p1': '1stparam'}, {'p1': '1stparam',", "MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value = False", "'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'),", "= MagicMock() event_vc_room.link_object = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context')", "{'result': 'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', param1='test1',", "CERN Indico plugins. # Copyright (C) 2014 - 2022 CERN", "CERN Indico plugins are free software; you can redistribute #", "('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test',", "ravem_api_call(endpoint, param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[0][1] ==", "as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'Well this", "request.call_count == 1 assert request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', (", "1 assert request.call_args[1]['params'] == params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request =", "terms of the MIT License; see # the LICENSE file", "@pytest.mark.usefixtures('db') def test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value", "excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'this is unexpected'", "assert request.call_count == 1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock()", "param2='test2') assert request.call_count == 1 assert request.call_args[0][0] == method @pytest.mark.usefixtures('db')", "file is part of the CERN Indico plugins. # Copyright", "the CERN Indico plugins. # Copyright (C) 2014 - 2022", "('get', 'post')) def test_correct_http_method(mocker, method): request = mocker.patch('indico_ravem.util.requests.request') response =", "= {'result': 'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint',", "def test_http_error_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.method =", "pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value) == \"Timeout while contacting", "response ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2') assert request.call_count == 1 assert", "'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'),", "with pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value) == \"Timeout while", "log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == '{} {}", "indico_ravem.util import has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post')) def test_correct_http_method(mocker,", "import MagicMock import pytest from requests.exceptions import HTTPError, Timeout from", "('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test',", "= request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value = False assert has_access(event_vc_room)", "request=request) with pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value) == \"Timeout", "and/or modify them under the terms of the MIT License;", "test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result':", "**params) assert str(excinfo.value) == 'Well this is embarrassing' log =", "1 assert request.call_args[0][0] == method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request =", "request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this is unexpected') with pytest.raises(IndexError)", "# Copyright (C) 2014 - 2022 CERN # # The", "event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.event.can_manage.return_value", "as excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value) == \"Timeout while contacting the", "{}\".format(method.upper(), 'test_endpoint', params, 'this is unexpected') assert request.call_count == 1", "'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1", "'Well this is embarrassing' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert", "response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', params=params) assert request.call_count", "assert log.message == '{} {} failed with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint')", "'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), ( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/',", "param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[0][1] == expected_url", "== 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), ( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'),", "'post')) def test_correct_http_method(mocker, method): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock()", "'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', method=method, param1='test1',", "assert 'Authorization' in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] == 'Bearer %s' %", "redistribute # them and/or modify them under the terms of", "(C) 2014 - 2022 CERN # # The CERN Indico", "The CERN Indico plugins are free software; you can redistribute", "params): request = mocker.patch('indico_ravem.util.requests.request') request.method = method.upper() request.url = RavemPlugin.settings.get('api_endpoint')", "'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint',", "'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'),", "@pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get', {}), ('post', {}), ('get', {'p1':", "'', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker, root_endpoint, endpoint,", "in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] == 'Bearer %s' % token @pytest.mark.usefixtures('db')", "%s' % token @pytest.mark.usefixtures('db') def test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request') response", "== 'this is unexpected' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert", "= False request.return_value = response ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count", "= '<NAME>' event_vc_room = MagicMock() event_vc_room.link_object.room = None assert not", "'<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value =", "method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock()", "CERN # # The CERN Indico plugins are free software;", "software; you can redistribute # them and/or modify them under", "'1stparam', 'p2': '2ndparam'} )) def test_params_generated(mocker, params): request = mocker.patch('indico_ravem.util.requests.request')", "extract_logs from indico_ravem.plugin import RavemPlugin from indico_ravem.util import has_access, ravem_api_call", "indico_ravem.plugin import RavemPlugin from indico_ravem.util import has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method',", "has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session') session.user =", "of the CERN Indico plugins. # Copyright (C) 2014 -", "= mocker.patch('indico_ravem.util.requests.request') request.method = method.upper() request.url = RavemPlugin.settings.get('api_endpoint') + 'test_endpoint'", "{'p1': '1stparam'}, {'p1': '1stparam', 'p2': '2ndparam'} )) def test_params_generated(mocker, params):", "% token @pytest.mark.usefixtures('db') def test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request') response =", "= response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2') assert request.call_count ==", "RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1 assert", "'expected_url'), ( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint',", "response.raise_for_status.side_effect = HTTPError('Well this is embarrassing') response.request = request response.url", "log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == \"failed call:", "mocker.patch('indico_ravem.util.session') session.user = '<NAME>' request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12'", "RavemPlugin from indico_ravem.util import has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post'))", "ravem_api_call('test_endpoint') assert str(excinfo.value) == \"Timeout while contacting the room.\" assert", "False request.return_value = response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2') assert", "= IndexError('this is unexpected') with pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint', method=method,", "= MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value =", "test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' session = mocker.patch('indico_ravem.util.session')", "'endpoint', 'expected_url'), ( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/',", "'<NAME>' request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal')", "== 1 assert request.call_args[1]['params'] == params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request", "test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock()", "import has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post')) def test_correct_http_method(mocker, method):", "= MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value =", "MagicMock() response.raise_for_status.side_effect = HTTPError('Well this is embarrassing') response.request = request", "= 'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count ==", "1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock() event_vc_room.link_object = None", "@pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>'", "{}: {}\".format(method.upper(), 'test_endpoint', params, 'this is unexpected') assert request.call_count ==", "log.message == '{} {} failed with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') +", "= response ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2') assert request.call_count == 1", "param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[1]['headers']['Accept'] == 'application/json'", "param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[0][0] == method", "@pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value", "response.request.url request.return_value = response with pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint', method=method,", "ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post')) def test_correct_http_method(mocker, method): request =", "request.call_args[0][0] == method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request') response", "- 2022 CERN # # The CERN Indico plugins are", "== 'Well this is embarrassing' log = extract_logs(caplog, one=True, name='indico.plugin.ravem')", "contacting the room.\" assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'),", "= MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.event.can_manage.return_value =", "with {}: {}\".format(method.upper(), 'test_endpoint', params, 'this is unexpected') assert request.call_count", "('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/',", "= '192.168.127.12' session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room", "== 1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock() event_vc_room.link_object =", "'2ndparam'}) )) def test_http_error_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request')", "Indico plugins are free software; you can redistribute # them", "has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post')) def test_correct_http_method(mocker, method): request", "== params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect =", "under the terms of the MIT License; see # the", "@pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post')) def test_correct_http_method(mocker, method): request = mocker.patch('indico_ravem.util.requests.request')", "HTTPError, Timeout from indico.testing.util import extract_logs from indico_ravem.plugin import RavemPlugin", "'2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def test_unexpected_exception_is_logged(mocker, caplog,", "'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'),", "def test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' session =", "the MIT License; see # the LICENSE file for more", "requests.exceptions import HTTPError, Timeout from indico.testing.util import extract_logs from indico_ravem.plugin", "# The CERN Indico plugins are free software; you can", "method.upper() request.url = RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response = MagicMock() response.raise_for_status.side_effect", "('get', {'p1': '1stparam'}), ('post', {'p1': '1stparam'}), ('get', {'p1': '1stparam', 'p2':", "with pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) ==", "import HTTPError, Timeout from indico.testing.util import extract_logs from indico_ravem.plugin import", "'1stparam'}), ('get', {'p1': '1stparam', 'p2': '2ndparam'}), ('post', {'p1': '1stparam', 'p2':", "= mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect =", "excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value) == \"Timeout while contacting the room.\"", "with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well this is embarrassing')", "endpoint, expected_url): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value =", "= None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker): session", "param2='test2') assert request.call_count == 1 assert request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db')", "response.raise_for_status.return_value = False request.return_value = response token = 'foo' RavemPlugin.settings.set('access_token',", "assert str(excinfo.value) == 'this is unexpected' log = extract_logs(caplog, one=True,", "HTTPError('Well this is embarrassing') response.request = request response.url = response.request.url", "= 'User:123' event_vc_room.event.can_manage.return_value = False assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def", "response.raise_for_status.return_value = False request.return_value = response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1',", "test error message', request=request) with pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint') assert", "the room.\" assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), (", "'./final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint',", "'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint',", "{'result': 'test'} response.raise_for_status.return_value = False request.return_value = response token =", "'./final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint',", "response.json.return_value = {'result': 'test'} response.raise_for_status.return_value = False request.return_value = response", "request.call_count == 1 assert request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint',", "== 'Bearer %s' % token @pytest.mark.usefixtures('db') def test_accepts_json(mocker): request =", "('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/',", "( ('get', {}), ('post', {}), ('get', {'p1': '1stparam'}), ('post', {'p1':", "@pytest.mark.parametrize('method', ('get', 'post')) def test_correct_http_method(mocker, method): request = mocker.patch('indico_ravem.util.requests.request') response", "session.user = '<NAME>' event_vc_room = MagicMock() event_vc_room.link_object.room = None assert", "= response token = 'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1', param2='test2')", "token @pytest.mark.usefixtures('db') def test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock()", "'1stparam', 'p2': '2ndparam'}) )) def test_http_error_is_logged(mocker, caplog, method, params): request", "request.return_value = response ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2') assert request.call_count ==", "MagicMock() event_vc_room.link_object.room = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def", "'2ndparam'}) )) def test_unexpected_exception_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request')", "def test_correct_http_method(mocker, method): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value", "event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value = False assert", "{'p1': '1stparam', 'p2': '2ndparam'}) )) def test_unexpected_exception_is_logged(mocker, caplog, method, params):", "'Bearer %s' % token @pytest.mark.usefixtures('db') def test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request')", "'2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def test_http_error_is_logged(mocker, caplog,", "= response ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1 assert", "1 assert request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {}, {'p1':", "{'p1': '1stparam', 'p2': '2ndparam'} )) def test_params_generated(mocker, params): request =", "= False request.return_value = response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2')", "('get', {'p1': '1stparam', 'p2': '2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'})", "request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), ( ('https://ravem.test/', 'final_endpoint',", "MagicMock import pytest from requests.exceptions import HTTPError, Timeout from indico.testing.util", "= extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == '{} {} failed", "root_endpoint, endpoint, expected_url): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value", "response = MagicMock() response.raise_for_status.side_effect = HTTPError('Well this is embarrassing') response.request", "request.return_value = response token = 'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1',", "= method.upper() request.url = RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response = MagicMock()", "Timeout('Timeout test error message', request=request) with pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint')", "mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout test error message', request=request) with pytest.raises(Timeout)", "pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'Well", "is unexpected') with pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert", "lambda x: session.user event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value", "'request_context') def test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' request", "ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[1]['headers']['Accept'] ==", "response token = 'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1', param2='test2') assert", "failed with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well this is", ")) def test_unexpected_exception_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect", "method=method, param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[0][0] ==", "'request_context') def test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' session", "{} failed with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well this", "plugins. # Copyright (C) 2014 - 2022 CERN # #", "{'p1': '1stparam', 'p2': '2ndparam'}) )) def test_http_error_is_logged(mocker, caplog, method, params):", "extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == \"failed call: {} {}", "request = mocker.patch('indico_ravem.util.requests.request') request.method = method.upper() request.url = RavemPlugin.settings.get('api_endpoint') +", "as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'this is", "are free software; you can redistribute # them and/or modify", "response.request = request response.url = response.request.url request.return_value = response with", "response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2') assert request.call_count == 1", "params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout", "mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result': 'test'} response.raise_for_status.return_value =", "request.call_args[1]['params'] == params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect", "unittest.mock import MagicMock import pytest from requests.exceptions import HTTPError, Timeout", "file for more details. from unittest.mock import MagicMock import pytest", "request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get', {}), ('post',", "root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[0][1]", "{'p1': '1stparam'}), ('post', {'p1': '1stparam'}), ('get', {'p1': '1stparam', 'p2': '2ndparam'}),", "from unittest.mock import MagicMock import pytest from requests.exceptions import HTTPError,", "# # The CERN Indico plugins are free software; you", "('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/',", "can redistribute # them and/or modify them under the terms", "retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda x: session.user event_vc_room =", "is part of the CERN Indico plugins. # Copyright (C)", "str(excinfo.value) == \"Timeout while contacting the room.\" assert request.call_count ==", "event_vc_room.event.can_manage.return_value = False assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker): request", "MIT License; see # the LICENSE file for more details.", "from indico_ravem.util import has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get', 'post')) def", "= response ravem_api_call('test_endpoint', params=params) assert request.call_count == 1 assert request.call_args[1]['params']", "assert request.call_count == 1 assert request.call_args[1]['params'] == params @pytest.mark.usefixtures('db') def", "= False assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker): request =", "free software; you can redistribute # them and/or modify them", "@pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock() event_vc_room.link_object = None assert", "params, 'this is unexpected') assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method',", "+ 'test_endpoint' response = MagicMock() response.raise_for_status.side_effect = HTTPError('Well this is", "= '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value", "request.call_count == 1 assert request.call_args[1]['params'] == params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker):", "('post', {'p1': '1stparam'}), ('get', {'p1': '1stparam', 'p2': '2ndparam'}), ('post', {'p1':", "License; see # the LICENSE file for more details. from", "assert request.call_count == 1 assert request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint',", "response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', param1='test1', param2='test2') assert", "request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value = False assert has_access(event_vc_room) @pytest.mark.usefixtures('db',", ")) def test_http_error_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.method", "from requests.exceptions import HTTPError, Timeout from indico.testing.util import extract_logs from", "caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.method = method.upper() request.url", "request.call_count == 1 assert 'Authorization' in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] ==", "= mocker.patch('indico_ravem.util.session') session.user = '<NAME>' request = mocker.patch('indico_ravem.util.request') request.remote_addr =", "of the MIT License; see # the LICENSE file for", "log.message == \"failed call: {} {} with {}: {}\".format(method.upper(), 'test_endpoint',", "session.user event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr", "= MagicMock() event_vc_room.link_object.room = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context')", "'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'),", "event_vc_room.link_object.room = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker):", "def test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value =", "session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' request = mocker.patch('indico_ravem.util.request') request.remote_addr", "params): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result':", "= mocker.patch('indico_ravem.util.session') session.user = '<NAME>' event_vc_room = MagicMock() event_vc_room.link_object.room =", "response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2')", "def test_unexpected_exception_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect =", "request.url = RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response = MagicMock() response.raise_for_status.side_effect =", "# the LICENSE file for more details. from unittest.mock import", "{} {} with {}: {}\".format(method.upper(), 'test_endpoint', params, 'this is unexpected')", "embarrassing') assert request.call_count == 1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room =", "event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.event.can_manage.return_value = True assert", "def test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url): request = mocker.patch('indico_ravem.util.requests.request') response =", "assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get', {}),", "MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.event.can_manage.return_value = True assert has_access(event_vc_room) event_vc_room.event.can_manage.assert_called_once_with(session.user)", "ravem_api_call('test_endpoint', params=params) assert request.call_count == 1 assert request.call_args[1]['params'] == params", "more details. from unittest.mock import MagicMock import pytest from requests.exceptions", "{}, {'p1': '1stparam'}, {'p1': '1stparam', 'p2': '2ndparam'} )) def test_params_generated(mocker,", "is embarrassing') assert request.call_count == 1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room", "'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint',", "'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'),", "method=method, **params) assert str(excinfo.value) == 'Well this is embarrassing' log", "call: {} {} with {}: {}\".format(method.upper(), 'test_endpoint', params, 'this is", "unexpected') with pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value)", "\"failed call: {} {} with {}: {}\".format(method.upper(), 'test_endpoint', params, 'this", "('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker, root_endpoint,", "'./sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '',", "test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result':", "{'p1': '1stparam'}), ('get', {'p1': '1stparam', 'p2': '2ndparam'}), ('post', {'p1': '1stparam',", "= False request.return_value = response ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2') assert", "extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == '{} {} failed with", "= mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout test error message', request=request) with", "= MagicMock() response.json.return_value = {'result': 'test'} response.raise_for_status.return_value = False request.return_value", "assert request.call_args[1]['params'] == params @pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request')", "None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker): session =", "is embarrassing') response.request = request response.url = response.request.url request.return_value =", "this is embarrassing' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message", "'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', param1='test1', param2='test2')", "method, params): request = mocker.patch('indico_ravem.util.requests.request') request.method = method.upper() request.url =", "= False request.return_value = response token = 'foo' RavemPlugin.settings.set('access_token', token)", "assert request.call_count == 1 assert request.call_args[0][0] == method @pytest.mark.usefixtures('db') def", "method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well this is embarrassing') assert request.call_count", "them under the terms of the MIT License; see #", "def test_accepts_json(mocker): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value =", "assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session')", "'test_endpoint', params, 'this is unexpected') assert request.call_count == 1 @pytest.mark.usefixtures('db')", "response.url = response.request.url request.return_value = response with pytest.raises(HTTPError) as excinfo:", "= RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response = MagicMock() response.raise_for_status.side_effect = HTTPError('Well", "request.side_effect = IndexError('this is unexpected') with pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint',", "event_vc_room.link_object = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker):", "'test_endpoint' response = MagicMock() response.raise_for_status.side_effect = HTTPError('Well this is embarrassing')", "'', 'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url): request =", "param1='test1', param2='test2') assert request.call_count == 1 assert 'Authorization' in request.call_args[1]['headers']", "'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'),", "Indico plugins. # Copyright (C) 2014 - 2022 CERN #", "ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'Well this is embarrassing'", "test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout test error message',", "you can redistribute # them and/or modify them under the", "event_vc_room = MagicMock() event_vc_room.link_object = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db',", "= extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == \"failed call: {}", "MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.event.can_manage.return_value = True", "request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] == 'Bearer %s' % token @pytest.mark.usefixtures('db') def", "unexpected' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == \"failed", "request.remote_addr = '192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda x:", "name='indico.plugin.ravem') assert log.message == '{} {} failed with {}'.format( method.upper(),", "**params) assert str(excinfo.value) == 'this is unexpected' log = extract_logs(caplog,", "RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2') assert request.call_count == 1 assert", "request.return_value = response with pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint', method=method, **params)", "= response.request.url request.return_value = response with pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint',", "('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/',", "test_correct_http_method(mocker, method): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value =", "= MagicMock() response.raise_for_status.side_effect = HTTPError('Well this is embarrassing') response.request =", "event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value", "'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'),", "assert request.call_count == 1 assert 'Authorization' in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization']", "== 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get', {}), ('post', {}),", "plugins are free software; you can redistribute # them and/or", "== 1 assert request.call_args[0][0] == method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request", "IndexError('this is unexpected') with pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint', method=method, **params)", "('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/',", "'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'),", "'./final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', './final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', 'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint',", "('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url): request", "while contacting the room.\" assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method',", "{}), ('post', {}), ('get', {'p1': '1stparam'}), ('post', {'p1': '1stparam'}), ('get',", "2014 - 2022 CERN # # The CERN Indico plugins", "request.method = method.upper() request.url = RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response =", "@pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), ( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'),", "param2='test2') assert request.call_count == 1 assert 'Authorization' in request.call_args[1]['headers'] assert", "assert request.call_count == 1 assert request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params',", "method=method, **params) assert str(excinfo.value) == 'this is unexpected' log =", "{'result': 'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', method=method,", "1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get', {}), ('post', {}), ('get',", "'p2': '2ndparam'}) )) def test_http_error_is_logged(mocker, caplog, method, params): request =", "this is embarrassing') assert request.call_count == 1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access():", "('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/',", "'192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda x: session.user event_vc_room", "'params'), ( ('get', {}), ('post', {}), ('get', {'p1': '1stparam'}), ('post',", "request response.url = response.request.url request.return_value = response with pytest.raises(HTTPError) as", "room.\" assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get',", "= HTTPError('Well this is embarrassing') response.request = request response.url =", "('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/',", "x: session.user event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value =", "('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def test_http_error_is_logged(mocker, caplog, method,", "request.side_effect = Timeout('Timeout test error message', request=request) with pytest.raises(Timeout) as", "'192.168.127.12' session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room =", "def test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock() event_vc_room.link_object = None assert not", "'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'),", "the terms of the MIT License; see # the LICENSE", "@pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {}, {'p1': '1stparam'}, {'p1': '1stparam', 'p2': '2ndparam'}", "== \"failed call: {} {} with {}: {}\".format(method.upper(), 'test_endpoint', params,", "'p2': '2ndparam'}) )) def test_unexpected_exception_is_logged(mocker, caplog, method, params): request =", "( {}, {'p1': '1stparam'}, {'p1': '1stparam', 'p2': '2ndparam'} )) def", "'2ndparam'} )) def test_params_generated(mocker, params): request = mocker.patch('indico_ravem.util.requests.request') response =", "caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this is", "'this is unexpected') assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'),", "request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect", "'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'),", "method, params): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this is unexpected')", "with pytest.raises(IndexError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) ==", "= Timeout('Timeout test error message', request=request) with pytest.raises(Timeout) as excinfo:", "one=True, name='indico.plugin.ravem') assert log.message == \"failed call: {} {} with", "from indico_ravem.plugin import RavemPlugin from indico_ravem.util import has_access, ravem_api_call @pytest.mark.usefixtures('db')", "part of the CERN Indico plugins. # Copyright (C) 2014", "param2='test2') assert request.call_count == 1 assert request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db')", "the LICENSE file for more details. from unittest.mock import MagicMock", "assert str(excinfo.value) == \"Timeout while contacting the room.\" assert request.call_count", "'User:123' event_vc_room.event.can_manage.return_value = False assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker):", "response with pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value)", "has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session') session.user =", "request.return_value = response ravem_api_call('test_endpoint', params=params) assert request.call_count == 1 assert", "test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' event_vc_room = MagicMock()", "ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[0][0]", "mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr", "token) ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1 assert 'Authorization'", "'p2': '2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def test_http_error_is_logged(mocker,", "@pytest.mark.parametrize('params', ( {}, {'p1': '1stparam'}, {'p1': '1stparam', 'p2': '2ndparam'} ))", "== 1 assert 'Authorization' in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] == 'Bearer", "pytest from requests.exceptions import HTTPError, Timeout from indico.testing.util import extract_logs", "event_vc_room.vc_room.data.get.return_value = 'User:123' event_vc_room.event.can_manage.return_value = False assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context')", "ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1 assert 'Authorization' in", "str(excinfo.value) == 'Well this is embarrassing' log = extract_logs(caplog, one=True,", "one=True, name='indico.plugin.ravem') assert log.message == '{} {} failed with {}'.format(", "= {'result': 'test'} response.raise_for_status.return_value = False request.return_value = response token", "= {'result': 'test'} response.raise_for_status.return_value = False request.return_value = response RavemPlugin.settings.set('api_endpoint',", "has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request') request.remote_addr =", "message', request=request) with pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value) ==", "request.return_value = response ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1", "= False request.return_value = response ravem_api_call('test_endpoint', params=params) assert request.call_count ==", "embarrassing') response.request = request response.url = response.request.url request.return_value = response", "event_vc_room = MagicMock() event_vc_room.link_object.room = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db',", "mocker.patch('indico_ravem.util.session') session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment =", "= mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result': 'test'} response.raise_for_status.return_value", "see # the LICENSE file for more details. from unittest.mock", "LICENSE file for more details. from unittest.mock import MagicMock import", "'test'} response.raise_for_status.return_value = False request.return_value = response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint,", "mocker.patch('indico_ravem.util.requests.request') request.method = method.upper() request.url = RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response", "# them and/or modify them under the terms of the", "params=params) assert request.call_count == 1 assert request.call_args[1]['params'] == params @pytest.mark.usefixtures('db')", "= request response.url = response.request.url request.return_value = response with pytest.raises(HTTPError)", "@pytest.mark.parametrize(('method', 'params'), ( ('get', {}), ('post', {}), ('get', {'p1': '1stparam'}),", "session.user = '<NAME>' request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' retrieve_principal", "Copyright (C) 2014 - 2022 CERN # # The CERN", "assert request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {}, {'p1': '1stparam'},", "unexpected') assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), ( ('get',", "modify them under the terms of the MIT License; see", "('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), ))", "False request.return_value = response ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count ==", "'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint',", "params): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this is unexpected') with", "name='indico.plugin.ravem') assert log.message == \"failed call: {} {} with {}:", "False request.return_value = response ravem_api_call('test_endpoint', params=params) assert request.call_count == 1", "mocker.patch('indico_ravem.util.session') session.user = '<NAME>' event_vc_room = MagicMock() event_vc_room.link_object.room = None", "excinfo: ravem_api_call('test_endpoint', method=method, **params) assert str(excinfo.value) == 'Well this is", "token = 'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count", "'1stparam'}, {'p1': '1stparam', 'p2': '2ndparam'} )) def test_params_generated(mocker, params): request", "MagicMock() event_vc_room.link_object = None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def", "'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', params=params) assert", "is embarrassing' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message ==", "= mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda x: session.user event_vc_room = MagicMock()", "1 assert 'Authorization' in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] == 'Bearer %s'", "'1stparam', 'p2': '2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def", "mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda x: session.user event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment", "expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {}, {'p1': '1stparam'}, {'p1': '1stparam', 'p2':", "import RavemPlugin from indico_ravem.util import has_access, ravem_api_call @pytest.mark.usefixtures('db') @pytest.mark.parametrize('method', ('get',", "= lambda x: session.user event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True)", "retrieve_principal.side_effect = lambda x: session.user event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment =", "# This file is part of the CERN Indico plugins.", "= mocker.patch('indico_ravem.util.session') session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal') event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment", "{}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well this is embarrassing') assert", "{'result': 'test'} response.raise_for_status.return_value = False request.return_value = response ravem_api_call('test_endpoint', params=params)", "'./sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '', 'https://ravem.test/'), ('https://ravem.test/api/', '',", "'sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', 'sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint',", "import extract_logs from indico_ravem.plugin import RavemPlugin from indico_ravem.util import has_access,", "method): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result':", "request.call_count == 1 @pytest.mark.usefixtures('db') def test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock() event_vc_room.link_object", "'<NAME>' event_vc_room = MagicMock() event_vc_room.link_object.room = None assert not has_access(event_vc_room)", "assert log.message == \"failed call: {} {} with {}: {}\".format(method.upper(),", "request.return_value = response RavemPlugin.settings.set('api_endpoint', root_endpoint) ravem_api_call(endpoint, param1='test1', param2='test2') assert request.call_count", "test_unexpected_exception_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this", "= '<NAME>' request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' retrieve_principal =", "'1stparam'}), ('post', {'p1': '1stparam'}), ('get', {'p1': '1stparam', 'p2': '2ndparam'}), ('post',", "{'result': 'test'} response.raise_for_status.return_value = False request.return_value = response RavemPlugin.settings.set('api_endpoint', root_endpoint)", "'test_endpoint', 'Well this is embarrassing') assert request.call_count == 1 @pytest.mark.usefixtures('db')", "assert request.call_args[0][0] == method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request')", "assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session')", "is unexpected') assert request.call_count == 1 @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('method', 'params'), (", "= '192.168.127.12' retrieve_principal = mocker.patch('indico_ravem.util._retrieve_principal') retrieve_principal.side_effect = lambda x: session.user", "request.call_args[1]['headers']['Authorization'] == 'Bearer %s' % token @pytest.mark.usefixtures('db') def test_accepts_json(mocker): request", "@pytest.mark.usefixtures('db') def test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout test", "== 1 assert request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'),", "assert str(excinfo.value) == 'Well this is embarrassing' log = extract_logs(caplog,", "for more details. from unittest.mock import MagicMock import pytest from", "'Well this is embarrassing') assert request.call_count == 1 @pytest.mark.usefixtures('db') def", "False assert has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request')", "MagicMock() response.json.return_value = {'result': 'test'} response.raise_for_status.return_value = False request.return_value =", "test_unlinked_event_vc_room_has_no_access(): event_vc_room = MagicMock() event_vc_room.link_object = None assert not has_access(event_vc_room)", "('get', {}), ('post', {}), ('get', {'p1': '1stparam'}), ('post', {'p1': '1stparam'}),", "'1stparam', 'p2': '2ndparam'}) )) def test_unexpected_exception_is_logged(mocker, caplog, method, params): request", "'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'),", "mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>'", "{} with {}: {}\".format(method.upper(), 'test_endpoint', params, 'this is unexpected') assert", "embarrassing' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message == '{}", "None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker): session =", "str(excinfo.value) == 'this is unexpected' log = extract_logs(caplog, one=True, name='indico.plugin.ravem')", "RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well this is embarrassing') assert request.call_count ==", "'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'), ('https://ravem.test', './final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', './final_endpoint',", "'this is unexpected' log = extract_logs(caplog, one=True, name='indico.plugin.ravem') assert log.message", "def test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' event_vc_room =", "'Authorization' in request.call_args[1]['headers'] assert request.call_args[1]['headers']['Authorization'] == 'Bearer %s' % token", "@pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>'", "== method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker): request = mocker.patch('indico_ravem.util.requests.request') response =", "+ 'test_endpoint', 'Well this is embarrassing') assert request.call_count == 1", "1 assert request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), (", "This file is part of the CERN Indico plugins. #", "def test_params_generated(mocker, params): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value", "= None assert not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker): session", "= response with pytest.raises(HTTPError) as excinfo: ravem_api_call('test_endpoint', method=method, **params) assert", "event_vc_room = MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value", "expected_url): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result':", "not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session') session.user", "'./sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/', './sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test/', '',", "response ravem_api_call('test_endpoint', params=params) assert request.call_count == 1 assert request.call_args[1]['params'] ==", "assert request.call_args[1]['headers']['Authorization'] == 'Bearer %s' % token @pytest.mark.usefixtures('db') def test_accepts_json(mocker):", "{'p1': '1stparam', 'p2': '2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'}) ))", "( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint', 'https://ravem.test/api/final_endpoint'), ('https://ravem.test/api/v2/', 'final_endpoint', 'https://ravem.test/api/v2/final_endpoint'),", "@pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), ( ('https://ravem.test/', 'final_endpoint', 'https://ravem.test/final_endpoint'), ('https://ravem.test/api/', 'final_endpoint',", "== 1 assert request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {},", "'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker,", "indico.testing.util import extract_logs from indico_ravem.plugin import RavemPlugin from indico_ravem.util import", "request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' session = mocker.patch('indico_ravem.util.session') session.user", "2022 CERN # # The CERN Indico plugins are free", "request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value = {'result': 'test'}", "'https://ravem.test/api/v2/'), )) def test_correct_api_endpoint(mocker, root_endpoint, endpoint, expected_url): request = mocker.patch('indico_ravem.util.requests.request')", "request.call_args[0][1] == expected_url @pytest.mark.usefixtures('db') @pytest.mark.parametrize('params', ( {}, {'p1': '1stparam'}, {'p1':", "test_params_generated(mocker, params): request = mocker.patch('indico_ravem.util.requests.request') response = MagicMock() response.json.return_value =", "False request.return_value = response token = 'foo' RavemPlugin.settings.set('access_token', token) ravem_api_call('test_endpoint',", "details. from unittest.mock import MagicMock import pytest from requests.exceptions import", "== '{} {} failed with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint',", "== \"Timeout while contacting the room.\" assert request.call_count == 1", "= MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.event.can_manage.return_value = True assert has_access(event_vc_room)", "error message', request=request) with pytest.raises(Timeout) as excinfo: ravem_api_call('test_endpoint') assert str(excinfo.value)", "from indico.testing.util import extract_logs from indico_ravem.plugin import RavemPlugin from indico_ravem.util", "('post', {}), ('get', {'p1': '1stparam'}), ('post', {'p1': '1stparam'}), ('get', {'p1':", "'p2': '2ndparam'}), ('post', {'p1': '1stparam', 'p2': '2ndparam'}) )) def test_unexpected_exception_is_logged(mocker,", "request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout test error message', request=request)", "request.call_count == 1 assert request.call_args[0][0] == method @pytest.mark.usefixtures('db') def test_correct_auth_method(mocker):", "RavemPlugin.settings.get('api_endpoint') + 'test_endpoint' response = MagicMock() response.raise_for_status.side_effect = HTTPError('Well this", "assert request.call_args[1]['headers']['Accept'] == 'application/json' @pytest.mark.usefixtures('db') @pytest.mark.parametrize(('root_endpoint', 'endpoint', 'expected_url'), ( ('https://ravem.test/',", "response ravem_api_call('test_endpoint', param1='test1', param2='test2') assert request.call_count == 1 assert request.call_args[1]['headers']['Accept']", "mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this is unexpected') with pytest.raises(IndexError) as excinfo:", "def test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' request =", "= mocker.patch('indico_ravem.util.requests.request') request.side_effect = IndexError('this is unexpected') with pytest.raises(IndexError) as", "'p2': '2ndparam'} )) def test_params_generated(mocker, params): request = mocker.patch('indico_ravem.util.requests.request') response", "'request_context') def test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' event_vc_room", "Timeout from indico.testing.util import extract_logs from indico_ravem.plugin import RavemPlugin from", "@pytest.mark.usefixtures('db', 'request_context') def test_check_if_current_user_can_modify(mocker): request = mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12'", "response = MagicMock() response.json.return_value = {'result': 'test'} response.raise_for_status.return_value = False", "= mocker.patch('indico_ravem.util.request') request.remote_addr = '192.168.127.12' session = mocker.patch('indico_ravem.util.session') session.user =", "\"Timeout while contacting the room.\" assert request.call_count == 1 @pytest.mark.usefixtures('db')", "('https://ravem.test/api/v2/', 'sub/final_endpoint', 'https://ravem.test/api/v2/sub/final_endpoint'), ('https://ravem.test', './sub/final_endpoint', 'https://ravem.test/sub/final_endpoint'), ('https://ravem.test/api/', './sub/final_endpoint', 'https://ravem.test/api/sub/final_endpoint'), ('https://ravem.test/api/v2/',", "test_http_error_is_logged(mocker, caplog, method, params): request = mocker.patch('indico_ravem.util.requests.request') request.method = method.upper()", "'{} {} failed with {}'.format( method.upper(), RavemPlugin.settings.get('api_endpoint') + 'test_endpoint', 'Well", "test_check_if_current_user_is_room_owner(mocker): session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' request = mocker.patch('indico_ravem.util.request')", "them and/or modify them under the terms of the MIT", "request.remote_addr = '192.168.127.12' session = mocker.patch('indico_ravem.util.session') session.user = '<NAME>' mocker.patch('indico_ravem.util._retrieve_principal')", "def test_raises_timeout(mocker): request = mocker.patch('indico_ravem.util.requests.request') request.side_effect = Timeout('Timeout test error", "'', 'https://ravem.test/'), ('https://ravem.test/api/', '', 'https://ravem.test/api/'), ('https://ravem.test/api/v2/', '', 'https://ravem.test/api/v2/'), )) def", "MagicMock() event_vc_room.link_object.room.has_equipment = MagicMock(return_value=True) event_vc_room.link_object.room.get_attribute_value.return_value = request.remote_addr event_vc_room.vc_room.data.get.return_value = 'User:123'", "this is embarrassing') response.request = request response.url = response.request.url request.return_value", "False request.return_value = response ravem_api_call('test_endpoint', method=method, param1='test1', param2='test2') assert request.call_count", "not has_access(event_vc_room) @pytest.mark.usefixtures('db', 'request_context') def test_unlinked_room_has_no_access(mocker): session = mocker.patch('indico_ravem.util.session') session.user" ]
[ "# -------------------------django---------------------- from django.conf.urls import url from .views import OrgView,", "utf-8 _*_ # --------------------------- __author__ = 'StormSha' __date__ = '2018/3/28", "import url from .views import OrgView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView,", "name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"),", "name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"),", "url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$',", "# --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$', TeacherListView.as_view(), name=\"teacher_list\"),", "AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$', TeacherListView.as_view(), name=\"teacher_list\"), url(r'^teacher/detail/(?P<teacher_id>\\d+)/$', TeacherDetailView.as_view(), name=\"teacher_detail\")", "'2018/3/28 18:01' # --------------------------- # -------------------------django---------------------- from django.conf.urls import url", "OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏-------------------------", "__date__ = '2018/3/28 18:01' # --------------------------- # -------------------------django---------------------- from django.conf.urls", "'StormSha' __date__ = '2018/3/28 18:01' # --------------------------- # -------------------------django---------------------- from", "import TeacherListView, TeacherDetailView urlpatterns = [ url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$',", "AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(),", "from django.conf.urls import url from .views import OrgView, AddUserAskView, OrgHomeView,", "AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from .views import TeacherListView,", "name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$', TeacherListView.as_view(), name=\"teacher_list\"), url(r'^teacher/detail/(?P<teacher_id>\\d+)/$', TeacherDetailView.as_view(), name=\"teacher_detail\") ]", "urlpatterns = [ url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$',", ".views import OrgView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from", "OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from .views import TeacherListView, TeacherDetailView", "__author__ = 'StormSha' __date__ = '2018/3/28 18:01' # --------------------------- #", "from .views import OrgView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView", "name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), #", "url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$',", "_*_ # --------------------------- __author__ = 'StormSha' __date__ = '2018/3/28 18:01'", "OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from .views import TeacherListView, TeacherDetailView urlpatterns", "url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), #", "name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$', TeacherListView.as_view(),", "name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"),", "OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$',", "= '2018/3/28 18:01' # --------------------------- # -------------------------django---------------------- from django.conf.urls import", "18:01' # --------------------------- # -------------------------django---------------------- from django.conf.urls import url from", "OrgDescView, OrgTeacherView, AddFavView from .views import TeacherListView, TeacherDetailView urlpatterns =", "from .views import TeacherListView, TeacherDetailView urlpatterns = [ url(r'^list/$', OrgView.as_view(),", "= [ url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(),", "[ url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"),", "OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"),", "= 'StormSha' __date__ = '2018/3/28 18:01' # --------------------------- # -------------------------django----------------------", "TeacherListView, TeacherDetailView urlpatterns = [ url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(),", "--------------------------- # -------------------------django---------------------- from django.conf.urls import url from .views import", "AddFavView from .views import TeacherListView, TeacherDetailView urlpatterns = [ url(r'^list/$',", "_*_ coding: utf-8 _*_ # --------------------------- __author__ = 'StormSha' __date__", "OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(),", "url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"), url(r'^home/(?P<org_id>\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$',", "url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------", "url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(),", "-------------------------django---------------------- from django.conf.urls import url from .views import OrgView, AddUserAskView,", "name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"), # --------------机构收藏------------------------- url(r'^add_fav/$',", "url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$', TeacherListView.as_view(), name=\"teacher_list\"), url(r'^teacher/detail/(?P<teacher_id>\\d+)/$', TeacherDetailView.as_view(),", "# _*_ coding: utf-8 _*_ # --------------------------- __author__ = 'StormSha'", "# --------------------------- __author__ = 'StormSha' __date__ = '2018/3/28 18:01' #", "# --------------------------- # -------------------------django---------------------- from django.conf.urls import url from .views", "OrgHomeView.as_view(), name=\"org_home\"), url(r'^course/(?P<org_id>\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"), url(r'^desc/(?P<org_id>\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"), url(r'^org_teacher/(?P<org_id>\\d+)/$', OrgTeacherView.as_view(),", "OrgView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from .views import", "import OrgView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from .views", "--------------------------- __author__ = 'StormSha' __date__ = '2018/3/28 18:01' # ---------------------------", "TeacherDetailView urlpatterns = [ url(r'^list/$', OrgView.as_view(), name=\"org_list\"), url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"),", ".views import TeacherListView, TeacherDetailView urlpatterns = [ url(r'^list/$', OrgView.as_view(), name=\"org_list\"),", "django.conf.urls import url from .views import OrgView, AddUserAskView, OrgHomeView, OrgCourseView,", "coding: utf-8 _*_ # --------------------------- __author__ = 'StormSha' __date__ =", "url from .views import OrgView, AddUserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView,", "OrgTeacherView, AddFavView from .views import TeacherListView, TeacherDetailView urlpatterns = [", "--------------机构收藏------------------------- url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"), # -----------------------teacher------------------------------ url(r'^teacher/list/$', TeacherListView.as_view(), name=\"teacher_list\"), url(r'^teacher/detail/(?P<teacher_id>\\d+)/$'," ]
[ "Migration(migrations.Migration): dependencies = [ ('filer', '0009_auto_20171220_1635'), ] operations = [", "operations = [ migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False, related_name='filer_image_file', parent_link=True,", "[ migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False, related_name='filer_image_file', parent_link=True, to='filer.File', on_delete=django.db.models.deletion.CASCADE),", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies", "utf-8 -*- from __future__ import unicode_literals from django.db import migrations,", "-*- from __future__ import unicode_literals from django.db import migrations, models", "migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('filer',", "('filer', '0009_auto_20171220_1635'), ] operations = [ migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True,", "class Migration(migrations.Migration): dependencies = [ ('filer', '0009_auto_20171220_1635'), ] operations =", "dependencies = [ ('filer', '0009_auto_20171220_1635'), ] operations = [ migrations.AlterField(", "] operations = [ migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False, related_name='filer_image_file',", "migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False, related_name='filer_image_file', parent_link=True, to='filer.File', on_delete=django.db.models.deletion.CASCADE), ),", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('filer', '0009_auto_20171220_1635'),", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from", "<filename>tech_project/lib/python2.7/site-packages/filer/migrations/0010_auto_20180414_2058.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals", "'0009_auto_20171220_1635'), ] operations = [ migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False,", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =", "from __future__ import unicode_literals from django.db import migrations, models import", "django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('filer', '0009_auto_20171220_1635'), ] operations", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [", "import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('filer', '0009_auto_20171220_1635'), ]", "= [ migrations.AlterField( model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False, related_name='filer_image_file', parent_link=True, to='filer.File',", "= [ ('filer', '0009_auto_20171220_1635'), ] operations = [ migrations.AlterField( model_name='image',", "__future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion", "[ ('filer', '0009_auto_20171220_1635'), ] operations = [ migrations.AlterField( model_name='image', name='file_ptr',", "model_name='image', name='file_ptr', field=models.OneToOneField(primary_key=True, serialize=False, related_name='filer_image_file', parent_link=True, to='filer.File', on_delete=django.db.models.deletion.CASCADE), ), ]", "unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "import unicode_literals from django.db import migrations, models import django.db.models.deletion class" ]
[ "if hcaldigi is not None: hcaldigi.HBDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'):", "process = ageHF(process,False) return process def turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0)", "= 2.5 # try to get conditions if int(lumi) in", "import _years_LHC, _years_HLLHC_ultimate module.years = _years_LHC + _years_HLLHC_ultimate return module", "}, } ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]):", "range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for", "process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator =", "= hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in", "None: hcaldigi.HBDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon) return", "if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster", "always together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi)) # functions to", "from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal module.years = _years_LHC + _years_HLLHC_nominal", "ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC) process = ageHF(process,True) process = ageSiPM(process,True,lumi)", "0.103, 1000 : 0.175, 3000 : 0.435, 4500 : 0.707,", "_seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in range(0,len(_clusters)):", "ageHB(process,True,\"\") return process def turn_off_HB_aging(process): process = ageHB(process,False,\"\") return process", "from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC)", "ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]): if lumi", "import HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi =", "HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is", "getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening = cms.untracked.bool(False) return", "and Hcal in phase2 geom configuration process=ageEcal(process,4500,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return", "if hcaldigi is not None: hcaldigi.HFDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'):", "= cms.double(float(lumi)) # available conditions ecal_lumis = [300,1000,3000,4500] ecal_conditions =", "hcal_lumi and lumi < hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"]", "= setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is not None:", "= getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening = cms.bool(turnon)", "ecal_thresholds = { 300 : 0.103, 1000 : 0.175, 3000", "return process.mix.digitizers.hgchebackDigitizer elif section == 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer", ": 0.175, 3000 : 0.435, 4500 : 0.707, } ecal_seed_multiplier", "cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed", "between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,1000,5.0e34) return", "2.5], \"rec\": [1.0, 2.0, 2.0, 2.0], }, 4500: { \"seed\":", "on 'complete' aging for ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity =", "if int(lumi) in ecal_lumis: if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition", "record = cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") )", "= ageSiPM(process,True,lumi) return process def turn_on_HB_aging(process): process = ageHB(process,True,\"\") return", "process = ageHF(process,True) process = ageSiPM(process,True,lumi) return process def turn_on_HB_aging(process):", "process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is not", "True enables default, False disables # recalibration and darkening always", "handle normal mixing or premixing def getHcalDigitizer(process): if hasattr(process,'mixData'): return", "{ \"seed\": [1.5, 3.0, 3.0, 3.0], \"rec\": [1.25, 2.5, 2.5,", "need to be further activated by turning on 'complete' aging", "agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process", "None: hcaldigi.DelivLuminosity = cms.double(float(lumi)) # integrated lumi in fb-1 #", "= process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold =", "if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon) return process def ageHE(process,turnon,scenarioHLLHC): if", "process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return", "process = ageHE(process,False,\"\") return process def turn_on_HF_aging(process): process = ageHF(process,True)", "} ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]): if", "not None: hcaldigi.HFDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon)", "activiated by tuning on 'complete' aging for ecal process.g4SimHits.ECalSD.InstLuminosity =", "not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record =", "by turning on 'complete' aging for HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity", "return None # change assumptions about lumi rate def setScenarioHLLHC(module,scenarioHLLHC):", "3000 : 0.435, 4500 : 0.707, } ecal_seed_multiplier = 2.5", "ageHB(process,False,\"\") return process def turn_on_HE_aging(process): process = ageHE(process,True,\"\") return process", "if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi)) # functions to enable individual", "process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict", "and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif section == 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'):", "from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def", "HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi", "process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in phase2", "hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HBDarkening =", "import HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def realisticHGCalStartup(process): from", "if hcaldigi is not None: hcaldigi.HFDarkening = cms.untracked.bool(False) return process", "ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))), connect =", "ecal_seed_multiplier = 2.5 # try to get conditions if int(lumi)", "turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP =", "hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"]", "turn_off_HF_aging(process): process = ageHF(process,False) return process def turn_off_SiPM_aging(process): process =", "def getHGCalDigitizer(process,section): if hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if section == 'EE'", ": 0.103, 1000 : 0.175, 3000 : 0.435, 4500 :", "hasattr(process,'mixData'): return process.mixData if hasattr(process,'mix') and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return", "return process.mix.digitizers.hfnoseDigitizer return None # change assumptions about lumi rate", "lines need to be further activiated by tuning on 'complete'", "cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds =", "in phase2 geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return process def", "module.years = _years_LHC + _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import", "hcal_lumi in enumerate(hcal_lumis[:-1]): if lumi >= hcal_lumi and lumi <", "process = ageHB(process,False,\"\") return process def turn_on_HE_aging(process): process = ageHE(process,True,\"\")", "def ageHB(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP =", "if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP", "= HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi", "2.5, 2.5, 2.5], \"rec\": [1.0, 2.0, 2.0, 2.0], }, 4500:", "process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier)", "2.0], }, 4500: { \"seed\": [1.5, 3.0, 3.0, 3.0], \"rec\":", "ageHE(process,False,\"\") return process def turn_on_HF_aging(process): process = ageHF(process,True) return process", "conditions ecal_lumis = [300,1000,3000,4500] ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'],", "hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif section == 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return", "adjustments # adjust PF thresholds for increased noise # based", "1.5, 1.5], \"rec\": [0.8, 1.2, 1.2, 1.2], }, 3000: {", "= cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for", "turnon # todo: determine ZS threshold adjustments # adjust PF", "range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return process def ecal_complete_aging(process):", "300: { \"seed\": [0.5, 0.625, 0.75, 0.75], \"rec\": [0.4, 0.5,", "process def turn_on_HE_aging(process): process = ageHE(process,True,\"\") return process def turn_off_HE_aging(process):", "hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HEDarkening =", "1000, 3000, 4500, 1e10] hcal_thresholds = { 300: { \"seed\":", "if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return process def ecal_complete_aging(process): if", "3.0, 3.0], \"rec\": [1.25, 2.5, 2.5, 2.5], }, } ctmodules", "hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"]", "process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator", "return process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal", "process=ageEcal(process,1000,5.0e34) return process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between", "if hasattr(process,'mixData'): return process.mixData if hasattr(process,'mix') and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'):", "enable individual subdet aging process = ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC)", "in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return process def", "need to be further activiated by tuning on 'complete' aging", "and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return None # change assumptions about", "increased noise # based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300, 1000,", "getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HEDarkening = cms.bool(turnon) if", "hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon) return process def ageHE(process,turnon,scenarioHLLHC): if turnon:", "HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process", "return process def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these lines need to", "HGCal and Hcal in phase2 geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process)", "lines need to be further activated by turning on 'complete'", "= cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) )", "on 'complete' aging for HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi))", "HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) #", "1000: { \"seed\": [1.0, 1.5, 1.5, 1.5], \"rec\": [0.8, 1.2,", "hcaldigi.HEDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon) return process", "process def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo)", "turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon # todo: determine ZS threshold adjustments", "process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process) if hcaldigi is not", "customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid", "ZS thresholds (tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage =", "in ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1]", "#avoid conflict between HGCal and Hcal in phase2 geom configuration", "hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator", "def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process)", "process=ageEcal(process,300,5.0e34) return process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between", "2.0, 2.0], }, 4500: { \"seed\": [1.5, 3.0, 3.0, 3.0],", "hcaldigi is not None: hcaldigi.HBDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration", "return process def turn_on_HB_aging(process): process = ageHB(process,True,\"\") return process def", "icluster in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return process", "hcaldigi.DelivLuminosity = cms.double(float(lumi)) # integrated lumi in fb-1 # these", "hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34)", "_years_LHC + _years_HLLHC_ultimate return module # turnon = True enables", "= ageHF(process,True) return process def turn_off_HF_aging(process): process = ageHF(process,False) return", "HGCal and Hcal in phase2 geom configuration process=ageEcal(process,4500,7.5e34) process=agedHGCal(process) process=agedHFNose(process)", "further activated by turning on 'complete' aging for HF if", "= { 300: { \"seed\": [0.5, 0.625, 0.75, 0.75], \"rec\":", "HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process)", "and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif section == 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'):", "None: hcaldigi.HFDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon) return", "= cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return process def", "Hcal in phase2 geom configuration process=ageEcal(process,1000,5.0e34) return process def customise_aging_3000(process):", "get conditions if int(lumi) in ecal_lumis: if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet()", "= turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon # todo: determine ZS threshold", "break return process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process) if hcaldigi", "def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal", "be further activated by turning on 'complete' aging for HF", "and hasattr(process.mix,'digitizers'): if section == 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer", "# functions to enable individual subdet aging process = ageHB(process,True,scenarioHLLHC)", "process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process) if hcaldigi is not", "agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process", "CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi", "= HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise", "== 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif section == 'BH'", "getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.DelivLuminosity = cms.double(float(lumi)) #", "\"seed\": [1.5, 3.0, 3.0, 3.0], \"rec\": [1.25, 2.5, 2.5, 2.5],", "process def turn_on_HB_aging(process): process = ageHB(process,True,\"\") return process def turn_off_HB_aging(process):", "for ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]), tag =", "2.5 # try to get conditions if int(lumi) in ecal_lumis:", "turn_on_HB_aging(process): process = ageHB(process,True,\"\") return process def turn_off_HB_aging(process): process =", "ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] #", "\"rec\": [1.25, 2.5, 2.5, 2.5], }, } ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO']", "ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.DelivLuminosity", "for ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) # available", "phase2 geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_3000_ultimate(process):", "{ \"seed\": [1.0, 1.5, 1.5, 1.5], \"rec\": [0.8, 1.2, 1.2,", "= ageSiPM(process,False,0.0) return process def hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening =", "hasattr(process,'g4SimHits'): #these lines need to be further activiated by tuning", "is not None: hcaldigi.HFDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration =", "def turn_off_HE_aging(process): process = ageHE(process,False,\"\") return process def turn_on_HF_aging(process): process", "darkening always together def ageHB(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import", "hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif section == 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return", "300 : 0.103, 1000 : 0.175, 3000 : 0.435, 4500", "= cms.double(float(lumi)) # functions to enable individual subdet aging process", "process = ageSiPM(process,True,lumi) return process def turn_on_HB_aging(process): process = ageHB(process,True,\"\")", "= cms.double(float(lumi)) # integrated lumi in fb-1 # these lines", "ZS threshold adjustments # adjust PF thresholds for increased noise", "0.75], \"rec\": [0.4, 0.5, 0.6, 0.6], }, 1000: { \"seed\":", "for increased noise # based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300,", "= getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HEDarkening = cms.bool(turnon)", "return process def turn_on_HF_aging(process): process = ageHF(process,True) return process def", "process = ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC) process = ageHF(process,True) process", "todo: determine ZS threshold adjustments # adjust PF thresholds for", "customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in", "getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process def", "process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in phase2", "cms.untracked.bool(False) return process def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these lines need", "hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm", "# update PF thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = {", "= ageHB(process,True,\"\") return process def turn_off_HB_aging(process): process = ageHB(process,False,\"\") return", "ecal_lumis = [300,1000,3000,4500] ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'],", "cms.bool(turnon) return process def ageHF(process,turnon): hcaldigi = getHcalDigitizer(process) if hcaldigi", "import HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def agedHGCal(process,algo=0): from", "1e10] hcal_thresholds = { 300: { \"seed\": [0.5, 0.625, 0.75,", "from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def", "process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid", "['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update PF thresholds,", "ctmod in ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 =", "= _years_LHC + _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC,", "= cms.untracked.bool(False) return process def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these lines", "= { 300 : 0.103, 1000 : 0.175, 3000 :", "_years_LHC, _years_HLLHC_nominal module.years = _years_LHC + _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from", "hcaldigi is not None: hcaldigi.HEDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration", "enables default, False disables # recalibration and darkening always together", "tuning on 'complete' aging for ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity", ">= hcal_lumi and lumi < hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold =", "to set proper ZS thresholds (tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage =", "elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate module.years = _years_LHC", "change assumptions about lumi rate def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from", "== 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif section == 'FH'", "hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return None def getHGCalDigitizer(process,section): if", "from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate module.years = _years_LHC + _years_HLLHC_ultimate", "from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC)", "is not None: hcaldigi.HFDarkening = cms.untracked.bool(False) return process def ageEcal(process,lumi,instLumi):", "hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening =", "process = ageHE(process,True,scenarioHLLHC) process = ageHF(process,True) process = ageSiPM(process,True,lumi) return", "hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon) return process def ageHF(process,turnon): hcaldigi =", "getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break", "process = ageHE(process,True,\"\") return process def turn_off_HE_aging(process): process = ageHE(process,False,\"\")", "phase2 geom configuration process=ageEcal(process,1000,5.0e34) return process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process)", "getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening = cms.bool(turnon) if", "scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate module.years = _years_LHC +", "= [300, 1000, 3000, 4500, 1e10] hcal_thresholds = { 300:", "[ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update PF", "== 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif section == 'HFNose'", "# integrated lumi in fb-1 # these lines need to", "'complete' aging for HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity", "if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon) return process def agedHFNose(process,algo=0): from", "on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = { 300 : 0.103, 1000 :", "FWCore.ParameterSet.Config as cms # handle normal mixing or premixing def", "def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process) return", "process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in phase2 geom", "def hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process)", "process.mix.digitizers.hcal return None def getHGCalDigitizer(process,section): if hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if", "hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif section == 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return", "hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0]", "process def turn_off_HB_aging(process): process = ageHB(process,False,\"\") return process def turn_on_HE_aging(process):", "+ _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate module.years", "{ \"seed\": [0.5, 0.625, 0.75, 0.75], \"rec\": [0.4, 0.5, 0.6,", "process.GlobalTag.toGet=cms.VPSet() for ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]), tag", "= ageHE(process,False,\"\") return process def turn_on_HF_aging(process): process = ageHF(process,True) return", "def turn_on_HB_aging(process): process = ageHB(process,True,\"\") return process def turn_off_HB_aging(process): process", "hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon) return process def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi", "HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process)", "cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon) return process def ageHF(process,turnon):", "['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update PF thresholds, based", "for icluster in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return", "import HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process) return process # needs lumi", "if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold =", "Hcal in phase2 geom configuration process=ageEcal(process,4500,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process", "4500 : 0.707, } ecal_seed_multiplier = 2.5 # try to", "return process.mix.digitizers.hgchefrontDigitizer elif section == 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer", "hcal_thresholds = { 300: { \"seed\": [0.5, 0.625, 0.75, 0.75],", "ageHF(process,True) process = ageSiPM(process,True,lumi) return process def turn_on_HB_aging(process): process =", "process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)])", "recalibration and darkening always together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi))", "process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and", "conflict between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,1000,5.0e34)", "[300, 1000, 3000, 4500, 1e10] hcal_thresholds = { 300: {", "['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update PF thresholds, based on", "as cms # handle normal mixing or premixing def getHcalDigitizer(process):", "= cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon) return process def", "= getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.DelivLuminosity = cms.double(float(lumi))", "if hcaldigi is not None: hcaldigi.DelivLuminosity = cms.double(float(lumi)) # integrated", "process.es_hardcode.iLumi = cms.double(float(lumi)) # functions to enable individual subdet aging", "PF thresholds for increased noise # based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis", "HGCal_setRealisticStartupNoise(process) return process # needs lumi to set proper ZS", "hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for", "0.625, 0.75, 0.75], \"rec\": [0.4, 0.5, 0.6, 0.6], }, 1000:", "process = HGCal_setRealisticStartupNoise(process) return process # needs lumi to set", "process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) # recalibration and darkening", "return process def turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0) return process def", "_clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return process def ecal_complete_aging(process): if hasattr(process,'g4SimHits'):", "hasattr(process,'mix') and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return None def", "CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi", "= cms.double(ecal_thresholds[int(lumi)]) return process def ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY =", "process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and", "fb-1 # these lines need to be further activated by", "mixing or premixing def getHcalDigitizer(process): if hasattr(process,'mixData'): return process.mixData if", "2.5], }, } ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi in", "import _years_LHC, _years_HLLHC_nominal module.years = _years_LHC + _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\":", "section == 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return None #", "ecal_lumis: if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet(", "_seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in", "if section == 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif section", "# recalibration and darkening always together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi =", "based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300, 1000, 3000, 4500, 1e10]", "geom configuration process=ageEcal(process,1000,5.0e34) return process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid", "1.5, 1.5, 1.5], \"rec\": [0.8, 1.2, 1.2, 1.2], }, 3000:", "hcaldigi is not None: hcaldigi.HFDarkening = cms.untracked.bool(False) return process def", "return None def getHGCalDigitizer(process,section): if hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if section", "process def turn_off_HF_aging(process): process = ageHF(process,False) return process def turn_off_SiPM_aging(process):", "cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return process def customise_aging_300(process):", "}, 1000: { \"seed\": [1.0, 1.5, 1.5, 1.5], \"rec\": [0.8,", "3.0], \"rec\": [1.25, 2.5, 2.5, 2.5], }, } ctmodules =", "for ctmod in ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2", "}, 4500: { \"seed\": [1.5, 3.0, 3.0, 3.0], \"rec\": [1.25,", "section == 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif section ==", "= ageHE(process,True,scenarioHLLHC) process = ageHF(process,True) process = ageSiPM(process,True,lumi) return process", "cms.bool(turnon) return process def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process", "hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process) if", "hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return", "functions to enable individual subdet aging process = ageHB(process,True,scenarioHLLHC) process", "process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) # available conditions ecal_lumis", "SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def agedHGCal(process,algo=0):", "= _years_LHC + _years_HLLHC_ultimate return module # turnon = True", "customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in", "return process.mix.digitizers.hgceeDigitizer elif section == 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer", "# needs lumi to set proper ZS thresholds (tbd) def", "process def turn_off_HE_aging(process): process = ageHE(process,False,\"\") return process def turn_on_HF_aging(process):", "lumi >= hcal_lumi and lumi < hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold", "return process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal", "\"rec\": [0.4, 0.5, 0.6, 0.6], }, 1000: { \"seed\": [1.0,", "hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi", "SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def realisticHGCalStartup(process):", "import HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi =", "0.5, 0.6, 0.6], }, 1000: { \"seed\": [1.0, 1.5, 1.5,", "= ageHF(process,True) process = ageSiPM(process,True,lumi) return process def turn_on_HB_aging(process): process", ": 0.707, } ecal_seed_multiplier = 2.5 # try to get", "lumi in fb-1 # these lines need to be further", "if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False)", "in phase2 geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process def", "https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300, 1000, 3000, 4500, 1e10] hcal_thresholds =", "def ageHF(process,turnon): hcaldigi = getHcalDigitizer(process) if hcaldigi is not None:", "= cms.bool(turnon) return process def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise", "process def hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi =", "conflict between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,3000,5.0e34)", "iseed in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters =", "\"rec\": [1.0, 2.0, 2.0, 2.0], }, 4500: { \"seed\": [1.5,", "if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) # recalibration", "hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]),", "realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process) return process", "not None: hcaldigi.DelivLuminosity = cms.double(float(lumi)) # integrated lumi in fb-1", "between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process)", "process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon # todo: determine ZS", "= cms.bool(turnon) return process def ageHF(process,turnon): hcaldigi = getHcalDigitizer(process) if", "process def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these lines need to be", "return process def ageHE(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP", "'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif section == 'FH' and", "needs lumi to set proper ZS thresholds (tbd) def ageSiPM(process,turnon,lumi):", "hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process", "int(lumi) in ecal_lumis: if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition in", "module # turnon = True enables default, False disables #", "process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) # available conditions ecal_lumis = [300,1000,3000,4500] ecal_conditions", "\"seed\": [1.0, 1.5, 1.5, 1.5], \"rec\": [0.8, 1.2, 1.2, 1.2],", "to be further activated by turning on 'complete' aging for", "= getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening = cms.untracked.bool(False)", "ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]): if lumi >= hcal_lumi and lumi", "setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal module.years =", "process def turn_on_HF_aging(process): process = ageHF(process,True) return process def turn_off_HF_aging(process):", "if hasattr(process,'g4SimHits'): #these lines need to be further activiated by", "ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold", "return process def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process =", "getHcalDigitizer(process): if hasattr(process,'mixData'): return process.mixData if hasattr(process,'mix') and hasattr(process.mix,'digitizers') and", "turn_off_HE_aging(process): process = ageHE(process,False,\"\") return process def turn_on_HF_aging(process): process =", "integrated lumi in fb-1 # these lines need to be", "[1.0, 1.5, 1.5, 1.5], \"rec\": [0.8, 1.2, 1.2, 1.2], },", "= True enables default, False disables # recalibration and darkening", "[300,1000,3000,4500] ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ]", "process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in phase2", "process def ageHE(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP", "3000: { \"seed\": [1.25, 2.5, 2.5, 2.5], \"rec\": [1.0, 2.0,", "return process def ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if", "[1.0, 2.0, 2.0, 2.0], }, 4500: { \"seed\": [1.5, 3.0,", "CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate module.years = _years_LHC + _years_HLLHC_ultimate return", "hcaldigi is not None: hcaldigi.HFDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration", "hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if", "configuration process=ageEcal(process,1000,5.0e34) return process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict", "# handle normal mixing or premixing def getHcalDigitizer(process): if hasattr(process,'mixData'):", "hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in ctmodules: if hasattr(process,ctmod):", "HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi", "process=agedHFNose(process) return process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between", "cms.double(ecal_thresholds[int(lumi)]) return process def ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True)", "in enumerate(hcal_lumis[:-1]): if lumi >= hcal_lumi and lumi < hcal_lumis[ilumi+1]:", "None: hcaldigi.HEDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon) return", "if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record", "= hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator =", "ageSiPM(process,True,lumi) return process def turn_on_HB_aging(process): process = ageHB(process,True,\"\") return process", "['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update PF thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf", "customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in", "process def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process)", "hcal_lumis = [300, 1000, 3000, 4500, 1e10] hcal_thresholds = {", "elif section == 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return None", "and darkening always together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi)) #", "# these lines need to be further activated by turning", "process # needs lumi to set proper ZS thresholds (tbd)", "in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))), connect", "# change assumptions about lumi rate def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\":", "def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these lines need to be further", "return process def ageHF(process,turnon): hcaldigi = getHcalDigitizer(process) if hcaldigi is", "hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in ctmodules:", "cms.untracked.bool(False) return process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process def", "and lumi < hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold", "Hcal in phase2 geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process", "process.mix.digitizers.hgchebackDigitizer elif section == 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return", "return process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process def customise_aging_1000(process):", "[0.5, 0.625, 0.75, 0.75], \"rec\": [0.4, 0.5, 0.6, 0.6], },", "= hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process)", "Hcal in phase2 geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return process", "conditions if int(lumi) in ecal_lumis: if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for", "['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]): if lumi >= hcal_lumi", "turn_on_HF_aging(process): process = ageHF(process,True) return process def turn_off_HF_aging(process): process =", "{ 300: { \"seed\": [0.5, 0.625, 0.75, 0.75], \"rec\": [0.4,", "PF thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = { 300 :", "return process def turn_on_HE_aging(process): process = ageHE(process,True,\"\") return process def", "module.years = _years_LHC + _years_HLLHC_ultimate return module # turnon =", "= getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HBDarkening = cms.bool(turnon)", "is not None: hcaldigi.HBDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration =", "None def getHGCalDigitizer(process,section): if hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if section ==", "enumerate(hcal_lumis[:-1]): if lumi >= hcal_lumi and lumi < hcal_lumis[ilumi+1]: if", "and darkening always together def ageHB(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff", "def getHcalDigitizer(process): if hasattr(process,'mixData'): return process.mixData if hasattr(process,'mix') and hasattr(process.mix,'digitizers')", "= hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 =", "= hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process def ageHcal(process,lumi,instLumi,scenarioHLLHC):", "process = ageHB(process,True,\"\") return process def turn_off_HB_aging(process): process = ageHB(process,False,\"\")", "turn_off_HB_aging(process): process = ageHB(process,False,\"\") return process def turn_on_HE_aging(process): process =", "1.2], }, 3000: { \"seed\": [1.25, 2.5, 2.5, 2.5], \"rec\":", "or premixing def getHcalDigitizer(process): if hasattr(process,'mixData'): return process.mixData if hasattr(process,'mix')", "hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process) if hcaldigi is", "= cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process) if hcaldigi is not None:", "to enable individual subdet aging process = ageHB(process,True,scenarioHLLHC) process =", "process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict", "2.5, 2.5], \"rec\": [1.0, 2.0, 2.0, 2.0], }, 4500: {", "= hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator =", "cms.double(float(lumi)) # available conditions ecal_lumis = [300,1000,3000,4500] ecal_conditions = [", "darkening always together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi)) # functions", "cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening", "assumptions about lumi rate def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff", "process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict", "ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection =", "hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold =", "together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi)) # functions to enable", "normal mixing or premixing def getHcalDigitizer(process): if hasattr(process,'mixData'): return process.mixData", "(tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon #", "ageHF(process,True) return process def turn_off_HF_aging(process): process = ageHF(process,False) return process", "cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if", "getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi =", "[1.25, 2.5, 2.5, 2.5], \"rec\": [1.0, 2.0, 2.0, 2.0], },", "thresholds for increased noise # based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis =", "{ \"seed\": [1.25, 2.5, 2.5, 2.5], \"rec\": [1.0, 2.0, 2.0,", "process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in ctmodules: if hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1", "in fb-1 # these lines need to be further activated", "def turn_off_HB_aging(process): process = ageHB(process,False,\"\") return process def turn_on_HE_aging(process): process", "0.175, 3000 : 0.435, 4500 : 0.707, } ecal_seed_multiplier =", "= [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update", "and Hcal in phase2 geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return", "= process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold =", "cms.double(float(lumi)) # recalibration and darkening always together if hasattr(process,'es_hardcode'): process.es_hardcode.iLumi", "process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is not", "and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return None def getHGCalDigitizer(process,section): if hasattr(process,'mix')", "process.es_hardcode.heUpgrade.doRadiationDamage = turnon # todo: determine ZS threshold adjustments #", "setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HBDarkening", "_years_HLLHC_nominal module.years = _years_LHC + _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff", "update PF thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = { 300", "process=agedHFNose(process) return process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between", "process.mixData if hasattr(process,'mix') and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return", "if hcaldigi is not None: hcaldigi.HEDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'):", "process = ageHF(process,True) return process def turn_off_HF_aging(process): process = ageHF(process,False)", "turnon = True enables default, False disables # recalibration and", "return process def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process =", "hcal_thresholds[hcal_lumi][\"rec\"][-1] break return process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process) if", "noise # based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300, 1000, 3000,", "<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms # handle normal mixing or", "[0.8, 1.2, 1.2, 1.2], }, 3000: { \"seed\": [1.25, 2.5,", "conflict between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,3000,7.5e34)", "< hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"]", "_clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\": _clusters[icluster].gatheringThreshold", "process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid", "= cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) # available conditions ecal_lumis =", "and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return None def getHGCalDigitizer(process,section):", "4500, 1e10] hcal_thresholds = { 300: { \"seed\": [0.5, 0.625,", "phase2 geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_4500_ultimate(process):", "} ecal_seed_multiplier = 2.5 # try to get conditions if", "to get conditions if int(lumi) in ecal_lumis: if not hasattr(process.GlobalTag,'toGet'):", ") if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in range(0,len(_seeds)):", "process def ageHF(process,turnon): hcaldigi = getHcalDigitizer(process) if hcaldigi is not", "= HGCal_setRealisticStartupNoise(process) return process # needs lumi to set proper", "thresholds (tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon", "getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HBDarkening = cms.bool(turnon) if", "# adjust PF thresholds for increased noise # based on:", "[1.25, 2.5, 2.5, 2.5], }, } ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for", "ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) # available conditions", "= ageHE(process,True,\"\") return process def turn_off_HE_aging(process): process = ageHE(process,False,\"\") return", "conflict between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,4500,7.5e34)", "turning on 'complete' aging for HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity =", "section == 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif section ==", "== 'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return None # change", "if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal module.years = _years_LHC", "to be further activiated by tuning on 'complete' aging for", "thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = { 300 : 0.103,", "elif section == 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif section", "https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = { 300 : 0.103, 1000 : 0.175,", "False disables # recalibration and darkening always together def ageHB(process,turnon,scenarioHLLHC):", "aging process = ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC) process = ageHF(process,True)", "proper ZS thresholds (tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage", "setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HEDarkening", "tag = cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if hasattr(process,\"particleFlowClusterECALUncorrected\"):", "= cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon) return process def", "and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif section == 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'):", "activated by turning on 'complete' aging for HF if hasattr(process,'g4SimHits'):", "ageHE(process,True,\"\") return process def turn_off_HE_aging(process): process = ageHE(process,False,\"\") return process", "return process def turn_off_HE_aging(process): process = ageHE(process,False,\"\") return process def", "ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these lines need to be further activiated", "def turn_on_HE_aging(process): process = ageHE(process,True,\"\") return process def turn_off_HE_aging(process): process", "default, False disables # recalibration and darkening always together def", "hcaldigi.HFDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon) return process", "geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\")", "= hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1] break return", "HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process) return process # needs lumi to", "if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm =", "process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP = setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if", "}, 3000: { \"seed\": [1.25, 2.5, 2.5, 2.5], \"rec\": [1.0,", "lumi to set proper ZS thresholds (tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage", "_clusters[icluster].gatheringThreshold = cms.double(ecal_thresholds[int(lumi)]) return process def ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY", "is not None: hcaldigi.DelivLuminosity = cms.double(float(lumi)) # integrated lumi in", "[0.4, 0.5, 0.6, 0.6], }, 1000: { \"seed\": [1.0, 1.5,", "2.5, 2.5, 2.5], }, } ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi,", "not None: hcaldigi.HBDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon)", "from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process) return process #", "process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for ctmod", "return process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal", "def turn_off_HF_aging(process): process = ageHF(process,False) return process def turn_off_SiPM_aging(process): process", "SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process = HGCal_setRealisticStartupNoise(process) return process # needs", "configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_4500_ultimate(process): process=ageHcal(process,4500,7.5e34,\"ultimate\") process=turn_off_HE_aging(process)", "# todo: determine ZS threshold adjustments # adjust PF thresholds", "= hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"]", "return process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal", "return process.mixData if hasattr(process,'mix') and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal", "not None: hcaldigi.HEDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon)", "] # update PF thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds =", "'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif section == 'HFNose' and", "return process def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process =", "configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process)", "threshold adjustments # adjust PF thresholds for increased noise #", "= cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) # recalibration and darkening always", "process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if", "aging for HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity =", "not None: hcaldigi.HFDarkening = cms.untracked.bool(False) return process def ageEcal(process,lumi,instLumi): if", "hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return None # change assumptions about lumi", "return process.mix.digitizers.hcal return None def getHGCalDigitizer(process,section): if hasattr(process,'mix') and hasattr(process.mix,'digitizers'):", "_years_HLLHC_ultimate return module # turnon = True enables default, False", "['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'], ] # update PF thresholds, based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds", "0.707, } ecal_seed_multiplier = 2.5 # try to get conditions", "process = ageSiPM(process,False,0.0) return process def hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening", "\"rec\": [0.8, 1.2, 1.2, 1.2], }, 3000: { \"seed\": [1.25,", "= HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi", "def turn_on_HF_aging(process): process = ageHF(process,True) return process def turn_off_HF_aging(process): process", "on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300, 1000, 3000, 4500, 1e10] hcal_thresholds", "elif section == 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif section", "def ageHE(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP =", "1000 : 0.175, 3000 : 0.435, 4500 : 0.707, }", "recalibration and darkening always together def ageHB(process,turnon,scenarioHLLHC): if turnon: from", "about lumi rate def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import", "if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"]", "subdet aging process = ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC) process =", "= setScenarioHLLHC(process.HEDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is not None:", "is not None: hcaldigi.HEDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration =", "hasattr(process,ctmod): getattr(process,ctmod).HBThreshold1 = hcal_thresholds[hcal_lumi][\"rec\"][0] getattr(process,ctmod).HBThreshold2 = hcal_thresholds[hcal_lumi][\"rec\"][1] getattr(process,ctmod).HBThreshold = hcal_thresholds[hcal_lumi][\"rec\"][-1]", "section == 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif section ==", "process.es_hardcode.HFRecalibration = cms.bool(turnon) return process def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import", "_years_LHC, _years_HLLHC_ultimate module.years = _years_LHC + _years_HLLHC_ultimate return module #", "None: hcaldigi.HFDarkening = cms.untracked.bool(False) return process def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'):", "in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector", "premixing def getHcalDigitizer(process): if hasattr(process,'mixData'): return process.mixData if hasattr(process,'mix') and", "further activiated by tuning on 'complete' aging for ecal process.g4SimHits.ECalSD.InstLuminosity", "process.es_hardcode.HERecalibration = cms.bool(turnon) return process def ageHF(process,turnon): hcaldigi = getHcalDigitizer(process)", "= cms.double(float(lumi)) # recalibration and darkening always together if hasattr(process,'es_hardcode'):", "process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return process", "_seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold", "HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if hcaldigi is", "process.mix.digitizers.hgceeDigitizer elif section == 'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif", "process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) # recalibration and darkening always together if", "hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\":", "hcaldigi is not None: hcaldigi.DelivLuminosity = cms.double(float(lumi)) # integrated lumi", "cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in range(0,len(_clusters)): if _clusters[icluster].detector.value()==\"ECAL_BARREL\":", "= HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise", "= cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds", "return process def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process) if hcaldigi is", "def ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection", "# based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg hcal_lumis = [300, 1000, 3000, 4500,", "cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HFRecalibration = cms.bool(turnon) return process def agedHFNose(process,algo=0):", "return module # turnon = True enables default, False disables", "2.5, 2.5], }, } ctmodules = ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi", "def turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0) return process def hf_complete_aging(process): if", "hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.DelivLuminosity =", "be further activiated by tuning on 'complete' aging for ecal", "'complete' aging for ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi))", "= [300,1000,3000,4500] ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'], ['EcalLaserAPDPNRatiosRcd','EcalLaserAPDPNRatios_TL{:d}_upgrade_8deg_mc'], ['EcalPedestalsRcd','EcalPedestals_TL{:d}_upgradeTIA_8deg_mc'], ['EcalTPGLinearizationConstRcd','EcalTPGLinearizationConst_TL{:d}_upgrade_8deg_mc'],", "0.75, 0.75], \"rec\": [0.4, 0.5, 0.6, 0.6], }, 1000: {", "3000, 4500, 1e10] hcal_thresholds = { 300: { \"seed\": [0.5,", "def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal module.years", "lumi rate def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC,", "ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon # todo: determine", "None # change assumptions about lumi rate def setScenarioHLLHC(module,scenarioHLLHC): if", "= ageHB(process,False,\"\") return process def turn_on_HE_aging(process): process = ageHE(process,True,\"\") return", "def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal", "hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return None def getHGCalDigitizer(process,section): if hasattr(process,'mix') and", "these lines need to be further activated by turning on", "process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\")", "process def turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0) return process def hf_complete_aging(process):", "ageHB(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP", "hcaldigi.HBDarkening = cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon) return process", "scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal module.years = _years_LHC +", "connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\") ) ) if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector", "return process def turn_off_HB_aging(process): process = ageHB(process,False,\"\") return process def", "always together def ageHB(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP", "if hasattr(process,'mix') and hasattr(process.mix,'digitizers') and hasattr(process.mix.digitizers,'hcal'): return process.mix.digitizers.hcal return None", "turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0) return process def hf_complete_aging(process): if hasattr(process,'g4SimHits'):", "turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP process.HEDarkeningEP =", "if lumi >= hcal_lumi and lumi < hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'):", "hasattr(process.mix,'digitizers'): if section == 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return process.mix.digitizers.hgceeDigitizer elif", "ageHF(process,False) return process def turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0) return process", "'FH' and hasattr(process.mix.digitizers,'hgchefrontDigitizer'): return process.mix.digitizers.hgchefrontDigitizer elif section == 'BH' and", "set proper ZS thresholds (tbd) def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon", "return process def turn_off_HF_aging(process): process = ageHF(process,False) return process def", "if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP", "based on https://indico.cern.ch/event/653123/contributions/2659235/attachments/1491385/2318364/170711_upsg_ledovskoy.pdf ecal_thresholds = { 300 : 0.103, 1000", "+ _years_HLLHC_ultimate return module # turnon = True enables default,", "turn_on_HE_aging(process): process = ageHE(process,True,\"\") return process def turn_off_HE_aging(process): process =", "determine ZS threshold adjustments # adjust PF thresholds for increased", "process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))), connect = cms.string(\"frontier://FrontierProd/CMS_CONDITIONS\")", "disables # recalibration and darkening always together def ageHB(process,turnon,scenarioHLLHC): if", "between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,4500,7.5e34) process=agedHGCal(process)", "hasattr(process,'es_hardcode'): process.es_hardcode.iLumi = cms.double(float(lumi)) # functions to enable individual subdet", "return process def hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi", "HGCal and Hcal in phase2 geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process)", "process.mix.digitizers.hfnoseDigitizer return None # change assumptions about lumi rate def", "#these lines need to be further activiated by tuning on", "adjust PF thresholds for increased noise # based on: https://baylor.box.com/s/w32ja75krcbxcycyifexu28dwlgrj7wg", "\"seed\": [1.25, 2.5, 2.5, 2.5], \"rec\": [1.0, 2.0, 2.0, 2.0],", "# recalibration and darkening always together def ageHB(process,turnon,scenarioHLLHC): if turnon:", "_years_HLLHC_ultimate module.years = _years_LHC + _years_HLLHC_ultimate return module # turnon", "\"seed\": [0.5, 0.625, 0.75, 0.75], \"rec\": [0.4, 0.5, 0.6, 0.6],", "ageSiPM(process,False,0.0) return process def hf_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True)", "4500: { \"seed\": [1.5, 3.0, 3.0, 3.0], \"rec\": [1.25, 2.5,", "# available conditions ecal_lumis = [300,1000,3000,4500] ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'],", "1.2, 1.2], }, 3000: { \"seed\": [1.25, 2.5, 2.5, 2.5],", "def customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal", "cms.double(float(lumi)) # integrated lumi in fb-1 # these lines need", "HGCal and Hcal in phase2 geom configuration process=ageEcal(process,1000,5.0e34) return process", "ecal_condition in ecal_conditions: process.GlobalTag.toGet.append(cms.PSet( record = cms.string(ecal_condition[0]), tag = cms.string(ecal_condition[1].format(int(lumi))),", "together def ageHB(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HBDarkeningEP process.HBDarkeningEP", "def agedHFNose(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HFNose_setEndOfLifeNoise process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return", "ageHE(process,True,scenarioHLLHC) process = ageHF(process,True) process = ageSiPM(process,True,lumi) return process def", "{ 300 : 0.103, 1000 : 0.175, 3000 : 0.435,", "= cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon) return process def", "import FWCore.ParameterSet.Config as cms # handle normal mixing or premixing", "_years_LHC + _years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate", "hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"]", "process.es_hardcode.HBRecalibration = cms.bool(turnon) return process def ageHE(process,turnon,scenarioHLLHC): if turnon: from", "process def ecal_complete_aging(process): if hasattr(process,'g4SimHits'): process.g4SimHits.ECalSD.AgeingWithSlopeLY = cms.untracked.bool(True) if hasattr(process,'ecal_digi_parameters'):", "for iseed in range(0,len(_seeds)): if _seeds[iseed].detector.value()==\"ECAL_BARREL\": _seeds[iseed].seedingThreshold = cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters", "try to get conditions if int(lumi) in ecal_lumis: if not", "in ecal_lumis: if not hasattr(process.GlobalTag,'toGet'): process.GlobalTag.toGet=cms.VPSet() for ecal_condition in ecal_conditions:", "hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) # recalibration and", "return process # needs lumi to set proper ZS thresholds", "ageHE(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import HEDarkeningEP process.HEDarkeningEP = HEDarkeningEP", "HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setRealisticStartupNoise process", "# turnon = True enables default, False disables # recalibration", "_years_HLLHC_nominal elif scenarioHLLHC==\"ultimate\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_ultimate module.years =", "cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) # available conditions ecal_lumis = [300,1000,3000,4500]", "and Hcal in phase2 geom configuration process=ageEcal(process,1000,5.0e34) return process def", "cms.bool(turnon) return process def ageHE(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import", "if hasattr(process,'ecal_digi_parameters'): process.ecal_digi_parameters.UseLCcorrection = cms.untracked.bool(False) return process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\")", ") ) if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in", "cms # handle normal mixing or premixing def getHcalDigitizer(process): if", "if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.HFDarkening = cms.untracked.bool(True) hcaldigi = getHcalDigitizer(process) if hcaldigi", "process.mix.digitizers.hgchefrontDigitizer elif section == 'BH' and hasattr(process.mix.digitizers,'hgchebackDigitizer'): return process.mix.digitizers.hgchebackDigitizer elif", "process = HFNose_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import", "if hasattr(process,'es_hardcode'): process.es_hardcode.HERecalibration = cms.bool(turnon) return process def ageHF(process,turnon): hcaldigi", "= cms.double(ecal_thresholds[int(lumi)]*ecal_seed_multiplier) _clusters = process.particleFlowClusterECALUncorrected.initialClusteringStep.thresholdsByDetector for icluster in range(0,len(_clusters)): if", "hcaldigi.HFDarkening = cms.untracked.bool(False) return process def ageEcal(process,lumi,instLumi): if hasattr(process,'g4SimHits'): #these", "rate def setScenarioHLLHC(module,scenarioHLLHC): if scenarioHLLHC==\"nominal\": from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal", "0.6, 0.6], }, 1000: { \"seed\": [1.0, 1.5, 1.5, 1.5],", "for HF if hasattr(process,'g4SimHits'): process.g4SimHits.HCalSD.InstLuminosity = cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi))", "= ['calotowermaker','caloTowerForTrk','caloTowerForTrkPreSplitting','towerMaker','towerMakerWithHO'] for ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]): if lumi >=", "ageHF(process,turnon): hcaldigi = getHcalDigitizer(process) if hcaldigi is not None: hcaldigi.HFDarkening", "cms.bool(turnon) if hasattr(process,'es_hardcode'): process.es_hardcode.HBRecalibration = cms.bool(turnon) return process def ageHE(process,turnon,scenarioHLLHC):", "getHGCalDigitizer(process,section): if hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if section == 'EE' and", "process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return process def realisticHGCalStartup(process): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import", "if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold = hcal_thresholds[hcal_lumi][\"rec\"] for ctmod in ctmodules: if", "between HGCal and Hcal in phase2 geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process)", "process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and", "= hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'):", "= cms.untracked.bool(False) return process def customise_aging_300(process): process=ageHcal(process,300,5.0e34,\"nominal\") process=ageEcal(process,300,5.0e34) return process", "def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal", "= cms.bool(turnon) return process def ageHE(process,turnon,scenarioHLLHC): if turnon: from CalibCalorimetry.HcalPlugins.HBHEDarkening_cff", "= ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC) process = ageHF(process,True) process =", "individual subdet aging process = ageHB(process,True,scenarioHLLHC) process = ageHE(process,True,scenarioHLLHC) process", "by tuning on 'complete' aging for ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi)", "def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo) return", "[1.5, 3.0, 3.0, 3.0], \"rec\": [1.25, 2.5, 2.5, 2.5], },", "def ageHcal(process,lumi,instLumi,scenarioHLLHC): hcaldigi = getHcalDigitizer(process) if hcaldigi is not None:", "in phase2 geom configuration process=ageEcal(process,1000,5.0e34) return process def customise_aging_3000(process): process=ageHcal(process,3000,5.0e34,\"nominal\")", "and Hcal in phase2 geom configuration process=ageEcal(process,3000,7.5e34) process=agedHGCal(process) process=agedHFNose(process) return", "0.435, 4500 : 0.707, } ecal_seed_multiplier = 2.5 # try", "'HFNose' and hasattr(process.mix.digitizers,'hfnoseDigitizer'): return process.mix.digitizers.hfnoseDigitizer return None # change assumptions", "cms.double(float(lumi)) # functions to enable individual subdet aging process =", "process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.recHitEnergyNorms[0].recHitEnergyNorm = hcal_thresholds[hcal_lumi][\"rec\"] process.particleFlowClusterHBHE.pfClusterBuilder.positionCalc.logWeightDenominatorByDetector[0].logWeightDenominator", ": 0.435, 4500 : 0.707, } ecal_seed_multiplier = 2.5 #", "# try to get conditions if int(lumi) in ecal_lumis: if", "= turnon # todo: determine ZS threshold adjustments # adjust", "1.2, 1.2, 1.2], }, 3000: { \"seed\": [1.25, 2.5, 2.5,", "for ilumi, hcal_lumi in enumerate(hcal_lumis[:-1]): if lumi >= hcal_lumi and", "= hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'): process.particleFlowRecHitHBHE.producers[0].qualityTests[0].cuts[0].threshold", "process.particleFlowClusterHBHE.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowClusterHCAL'): process.particleFlowClusterHCAL.pfClusterBuilder.allCellsPositionCalc.logWeightDenominatorByDetector[0].logWeightDenominator = hcal_thresholds[hcal_lumi][\"rec\"] if hasattr(process,'particleFlowRecHitHBHE'):", "3.0, 3.0, 3.0], \"rec\": [1.25, 2.5, 2.5, 2.5], }, }", "geom configuration process=ageEcal(process,3000,5.0e34) process=agedHGCal(process) process=agedHFNose(process) return process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\")", "lumi < hcal_lumis[ilumi+1]: if hasattr(process,'particleFlowClusterHBHE'): process.particleFlowClusterHBHE.seedFinder.thresholdsByDetector[0].seedingThreshold = hcal_thresholds[hcal_lumi][\"seed\"] process.particleFlowClusterHBHE.initialClusteringStep.thresholdsByDetector[0].gatheringThreshold =", "aging for ecal process.g4SimHits.ECalSD.InstLuminosity = cms.double(instLumi) process.g4SimHits.ECalSD.DelivLuminosity = cms.double(float(lumi)) #", "1.5], \"rec\": [0.8, 1.2, 1.2, 1.2], }, 3000: { \"seed\":", "available conditions ecal_lumis = [300,1000,3000,4500] ecal_conditions = [ ['EcalIntercalibConstantsRcd','EcalIntercalibConstants_TL{:d}_upgrade_8deg_v2_mc'], ['EcalIntercalibConstantsMCRcd','EcalIntercalibConstantsMC_TL{:d}_upgrade_8deg_v2_mc'],", "2.0, 2.0, 2.0], }, 4500: { \"seed\": [1.5, 3.0, 3.0,", "process def customise_aging_3000_ultimate(process): process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and", "process.HBDarkeningEP = HBDarkeningEP process.HBDarkeningEP = setScenarioHLLHC(process.HBDarkeningEP,scenarioHLLHC) hcaldigi = getHcalDigitizer(process) if", "customise_aging_1000(process): process=ageHcal(process,1000,5.0e34,\"nominal\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in", "0.6], }, 1000: { \"seed\": [1.0, 1.5, 1.5, 1.5], \"rec\":", "if hasattr(process,\"particleFlowClusterECALUncorrected\"): _seeds = process.particleFlowClusterECALUncorrected.seedFinder.thresholdsByDetector for iseed in range(0,len(_seeds)): if", "= ageHF(process,False) return process def turn_off_SiPM_aging(process): process = ageSiPM(process,False,0.0) return", "if hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if section == 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'):", "cms.double(float(instLumi)) process.g4SimHits.HCalSD.DelivLuminosity = cms.double(float(lumi)) # recalibration and darkening always together", "process=ageHcal(process,3000,7.5e34,\"ultimate\") process=turn_off_HE_aging(process) #avoid conflict between HGCal and Hcal in phase2", "CalibCalorimetry.HcalPlugins.HBHEDarkening_cff import _years_LHC, _years_HLLHC_nominal module.years = _years_LHC + _years_HLLHC_nominal elif", "process def agedHGCal(process,algo=0): from SimCalorimetry.HGCalSimProducers.hgcalDigitizer_cfi import HGCal_setEndOfLifeNoise process = HGCal_setEndOfLifeNoise(process,byDose=True,byDoseAlgo=algo)", "hasattr(process,'mix') and hasattr(process.mix,'digitizers'): if section == 'EE' and hasattr(process.mix.digitizers,'hgceeDigitizer'): return", "def ageSiPM(process,turnon,lumi): process.es_hardcode.hbUpgrade.doRadiationDamage = turnon process.es_hardcode.heUpgrade.doRadiationDamage = turnon # todo:" ]
[ "radius] self.axis = (self.p2 - self.p1) / length def update_point(self,", "in zip(self.joints, self.joint_positions): joint.set('pos', ' '.join([str(x) for x in pos]))", "p1 self.p2 = p2 super().set_params(new_params) def get_smallest_z(self): return min(self.p1[2], self.p2[2])", "def update_params(self, new_params): if self.worldbody: assert len(new_params) == self.n_all_params, \"Wrong", "body.get_param_limits() limits[0] += body_limits[0] limits[1] += body_limits[1] return limits def", "self.params = new_params def update_point(self, p, new_params): pass def update_xml(self):", "self.params[0])# + rfac * (new_params[1] / self.params[1]) def update_xml(self): self.xml.set('fromto',", "in self.joints] self.joint_positions = [np.array([float(x) for x in p.split()]) for", "= list(1.0 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params() == params", "body_limits = body.get_param_limits() limits[0] += body_limits[0] limits[1] += body_limits[1] return", "self.params[0] ** 3 class Capsule(Geom): min_length = 0.175 max_length =", "for body in self.parts: params += body.get_params() return params def", "= self.geom.get_volume() v2 = sum([b.geom.get_volume() for b in self.parts]) volumes[j.get('name')]", "get_param_names(self): return ['radius'] def get_volume(self): return 4./3. * np.pi *", "get_param_limits(self): return self.body.get_param_limits() def get_param_names(self): return self.body.get_param_names() def get_height(self): return", "get_volume(self): pass class Sphere(Geom): min_radius = .05 max_radius = .4", "robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params() == params #assert robot.get_height() == 1.31", "[.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params() == params assert robot.get_height() ==", "b in body.findall('body')] pos = [b.get('pos') for b in body.findall('body')]", "if self.worldbody: assert len(new_params) == self.n_all_params, \"Wrong number of parameters\"", "self.geom.get_param_limits() for body in self.parts: body_limits = body.get_param_limits() limits[0] +=", "self.worldbody: self.update_initial_position() else: return remaining_params def get_body_names(self): names = [self.xml.get('name')]", "gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset() #env.render() import os from scipy.misc", "params assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml')", "str(self.params[1])) # radius def set_params(self, new_params): p1 = self.update_point(self.p1, new_params)", "update_xml(self): self.xml.set('size', str(self.params[0])) def get_smallest_z(self): return self.center[2] - self.params[0] def", "get_height(self): max_height = -self.geom.get_smallest_z() for body, pos in zip(self.parts, self.part_positions):", "max_height = max(max_height, body.get_height() - pos[2]) return max_height def update_initial_position(self):", "outdir = 'xml_vid' os.makedirs(outdir, exist_ok=True) i = 0 for _", "' '.join([str(x) for x in np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1])) #", "params = list(1.0 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params() ==", "/ self.params[0])# + rfac * (new_params[1] / self.params[1]) def update_xml(self):", "'mujoco_assets/ant_test.xml') assert robot.get_params() == params assert robot.get_height() == .2 print(robot.get_param_limits())", "new_params): pass def update_xml(self): pass def update(self, new_params): self.set_params(new_params) self.update_xml()", "= p2 super().set_params(new_params) def get_smallest_z(self): return min(self.p1[2], self.p2[2]) - self.params[1]", "def get_height(self): return self.body.get_height() def get_joints(self): return self.body.get_joints() def get_volumes(self):", "= env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg', '-r', '60', '-f',", "self.params[1]**3 + self.params[0] * np.pi * self.params[1]**2 class Body: geoms", "update_xml(self): pass def update(self, new_params): self.set_params(new_params) self.update_xml() def get_smallest_z(self): pass", "self.parts: names += body.get_names() return names def get_joints(self): joints =", "def update_xml(self): for body, pos in zip(self.parts, self.part_positions): body.xml.set('pos', '", "p, new_params): pass def update_xml(self): pass def update(self, new_params): self.set_params(new_params)", "MuJoCoXmlRobot: def __init__(self, model_xml): self.model_xml = model_xml self.tree = ET.parse(self.model_xml)", "+ lfac * (-1.0 + new_params[0] / self.params[0])# + rfac", "def update_point(self, p, new_params): lfac = p.dot(self.axis) * self.axis rfac", "= [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params() == params assert robot.get_height()", "'.join([str(x) for x in np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1])) # radius", "self.center = np.array([float(x) for x in self.xml.get('pos').split()]) def update_point(self, p,", "for x in p.split()]) for p in pos] self.n =", "len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2]) - self.get_height() def get_height(self): max_height =", "new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def get_params(self): params = self.geom.get_params() for", "self.xml.get('name') param_names = [name + '-' + p for p", "param_names = [name + '-' + p for p in", "= [name + '-' + p for p in self.geom.get_param_names()]", "- self.center) * new_params[0] / self.params[0]) + self.center def update_xml(self):", "types def __init__(self, body, worldbody=False): self.xml = body self.worldbody =", "robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params =", "0 for _ in range(10): env.reset() for _ in range(100):", "param_names += body.get_param_names() return param_names def update_params(self, new_params): if self.worldbody:", "as ET class Geom(object): def __init__(self, geom): self.xml = geom", "= self.update_point(self.p1, new_params) p2 = self.update_point(self.p2, new_params) # update only", "import numpy as np import xml.etree.ElementTree as ET class Geom(object):", "for _ in range(10): env.reset() for _ in range(100): env.step(env.action_space.sample())", "rgb) i+=1 sp.call(['ffmpeg', '-r', '60', '-f', 'image2', '-i', os.path.join(outdir, '%05d.png'),", "self.xml = body self.worldbody = worldbody geom_xml = body.find('geom') #", "update_point(self, p, new_params): lfac = p.dot(self.axis) * self.axis rfac =", "def update_xml(self): self.xml.set('fromto', ' '.join([str(x) for x in np.concatenate([self.p1, self.p2])]))", "return param_names def update_params(self, new_params): if self.worldbody: assert len(new_params) ==", "import imsave import subprocess as sp outdir = 'xml_vid' os.makedirs(outdir,", "imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg', '-r', '60', '-f', 'image2', '-i',", "self.update(new_params[:self.n]) remaining_params = new_params[self.n:] for body in self.parts: remaining_params =", "self.params = [float(self.xml.get('size'))] # radius self.center = np.array([float(x) for x", "for j in self.joints] self.joint_positions = [np.array([float(x) for x in", "+ self.params[0] * np.pi * self.params[1]**2 class Body: geoms =", "get_smallest_z(self): return min(self.p1[2], self.p2[2]) - self.params[1] def get_param_limits(self): return [[self.min_length,", "body, pos in zip(self.parts, self.part_positions): max_height = max(max_height, body.get_height() -", "def get_volumes(self): volumes = {} if len(self.joints) > 0: for", "set_body_positions(self, new_params): for i, pos in enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos,", "self.params[1]**2 class Body: geoms = {'sphere': Sphere, 'capsule': Capsule} #", "def get_param_names(self): return ['length','radius'] def get_volume(self): return 4./3. * np.pi", "= [Body(b) for b in body.findall('body')] pos = [b.get('pos') for", "in self.geom.get_param_names()] for body in self.parts: param_names += body.get_param_names() return", "body, worldbody=False): self.xml = body self.worldbody = worldbody geom_xml =", "self.xml.get('pos').split()]) def update_point(self, p, new_params): return ((p - self.center) *", "def get_param_limits(self): return self.body.get_param_limits() def get_param_names(self): return self.body.get_param_names() def get_height(self):", "== '__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0 * np.array(robot.get_params()))", "new_params def update_point(self, p, new_params): pass def update_xml(self): pass def", "for b in body.findall('body')] pos = [b.get('pos') for b in", "= [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params()", "self.set_params(new_params) self.update_xml() def get_smallest_z(self): pass def get_param_limits(self): pass def get_param_names(self):", "self.zmin) self.xml.set(\"pos\", ' '.join(pos)) def update_xml(self): for body, pos in", "lfac = p.dot(self.axis) * self.axis rfac = p - lfac", "geom self.params = [] def get_params(self): return self.params.copy() def set_params(self,", "x in self.xml.get('pos').split()]) def update_point(self, p, new_params): return ((p -", "def get_param_limits(self): return [[self.min_radius], [self.max_radius]] def get_param_names(self): return ['radius'] def", "max_height def update_initial_position(self): pos = self.xml.get(\"pos\").split() pos[2] = str(self.get_height() +", "get_volumes(self): volumes = {} if len(self.joints) > 0: for j", "self.p2])])) self.xml.set('size', str(self.params[1])) # radius def set_params(self, new_params): p1 =", "names = [self.xml.get('name')] for body in self.parts: names += body.get_names()", "j in body.findall('joint') if 'ignore' not in j.get('name')] self.parts =", "pos = [b.get('pos') for b in body.findall('body')] self.part_positions = [np.array([float(x)", "return remaining_params def get_body_names(self): names = [self.xml.get('name')] for body in", "v2)) for body in self.parts: volumes.update(body.get_volumes()) return volumes class MuJoCoXmlRobot:", "ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'), worldbody=True) def get_params(self):", "return ['length','radius'] def get_volume(self): return 4./3. * np.pi * self.params[1]**3", "dictionary of legal geometry types def __init__(self, body, worldbody=False): self.xml", "computing p1, p2 self.p1 = p1 self.p2 = p2 super().set_params(new_params)", "np import xml.etree.ElementTree as ET class Geom(object): def __init__(self, geom):", "_ in range(10): env.reset() for _ in range(100): env.step(env.action_space.sample()) rgb", "get_volume(self): return 4./3. * np.pi * self.params[1]**3 + self.params[0] *", "range(100): env.step(env.action_space.sample()) rgb = env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg',", "get_params(self): return self.params.copy() def set_params(self, new_params): self.params = new_params def", "= self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j for j in body.findall('joint') if", "self.part_positions): max_height = max(max_height, body.get_height() - pos[2]) return max_height def", "if xml_file is None: xml_file = self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if", "zip(self.joints, self.joint_positions): joint.set('pos', ' '.join([str(x) for x in pos])) def", "= [float(self.xml.get('size'))] # radius self.center = np.array([float(x) for x in", "body.findall('joint') if 'ignore' not in j.get('name')] self.parts = [Body(b) for", "xml_file = self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if __name__ == '__main__': robot", "0.035 max_radius = 0.085 def __init__(self, geom): self.xml = geom", "name = self.xml.get('name') param_names = [name + '-' + p", "class Sphere(Geom): min_radius = .05 max_radius = .4 def __init__(self,", "np.sqrt(np.sum((self.p2 - self.p1) ** 2)) radius = float(self.xml.get('size')) self.params =", "- self.p1) ** 2)) radius = float(self.xml.get('size')) self.params = [length,", "None: xml_file = self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if __name__ == '__main__':", "list(.8 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params() == params print(robot.get_height())", "in pos])) for joint, pos in zip(self.joints, self.joint_positions): joint.set('pos', '", "in self.joints: v1 = self.geom.get_volume() v2 = sum([b.geom.get_volume() for b", "= p1 self.p2 = p2 super().set_params(new_params) def get_smallest_z(self): return min(self.p1[2],", "new_params): self.set_params(new_params) self.update_xml() def get_smallest_z(self): pass def get_param_limits(self): pass def", "def update_xml(self): self.xml.set('size', str(self.params[0])) def get_smallest_z(self): return self.center[2] - self.params[0]", "env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset() #env.render() import os from scipy.misc import", "- self.params[0] def get_param_limits(self): return [[self.min_radius], [self.max_radius]] def get_param_names(self): return", "self.part_positions): for j in body.joints: joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'), self.geom,", "x in p.split()]) for p in pos] self.n = len(self.geom.get_params())", "length = np.sqrt(np.sum((self.p2 - self.p1) ** 2)) radius = float(self.xml.get('size'))", "== self.n_all_params, \"Wrong number of parameters\" self.update(new_params[:self.n]) remaining_params = new_params[self.n:]", "= 0.8 min_radius = 0.035 max_radius = 0.085 def __init__(self,", "= str(self.get_height() + self.zmin) self.xml.set(\"pos\", ' '.join(pos)) def update_xml(self): for", "= len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2]) - self.get_height() def get_height(self): max_height", "get_volume(self): return 4./3. * np.pi * self.params[0] ** 3 class", "params assert robot.get_height() == .2 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml')", "= -self.geom.get_smallest_z() for body, pos in zip(self.parts, self.part_positions): max_height =", "body in self.parts: param_names += body.get_param_names() return param_names def update_params(self,", "def __init__(self, geom): self.xml = geom self.params = [float(self.xml.get('size'))] #", "body.findall('body')] self.part_positions = [np.array([float(x) for x in p.split()]) for p", "+ '-' + p for p in self.geom.get_param_names()] for body", "* (new_params[1] / self.params[1]) def update_xml(self): self.xml.set('fromto', ' '.join([str(x) for", "new_params[0] / self.params[0]) + self.center def update_xml(self): self.xml.set('size', str(self.params[0])) def", "p + lfac * (-1.0 + new_params[0] / self.params[0])# +", "self.update_xml() def get_params(self): params = self.geom.get_params() for body in self.parts:", "volumes = {} if len(self.joints) > 0: for j in", "def get_joints(self): return self.body.get_joints() def get_volumes(self): return self.body.get_volumes() def update(self,", "= np.array(fromto[:3]) self.p2 = np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2 - self.p1)", "body, pos in zip(self.parts, self.part_positions): body.xml.set('pos', ' '.join([str(x) for x", "def get_param_names(self): return ['radius'] def get_volume(self): return 4./3. * np.pi", "[float(self.xml.get('size'))] # radius self.center = np.array([float(x) for x in self.xml.get('pos').split()])", "** 3 class Capsule(Geom): min_length = 0.175 max_length = 0.8", "# assume only one geometry per body self.geom = self.geoms[geom_xml.get('type')](geom_xml)", "= MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params,", "x in pos])) def set_body_positions(self, new_params): for i, pos in", "* self.params[0] ** 3 class Capsule(Geom): min_length = 0.175 max_length", "__name__ == '__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0 *", "[self.max_radius]] def get_param_names(self): return ['radius'] def get_volume(self): return 4./3. *", "new_params[self.n:] for body in self.parts: remaining_params = body.update_params(remaining_params) if self.worldbody:", "max_radius = .4 def __init__(self, geom): self.xml = geom self.params", "in zip(self.parts, self.part_positions): max_height = max(max_height, body.get_height() - pos[2]) return", "scipy.misc import imsave import subprocess as sp outdir = 'xml_vid'", "p - lfac return p + lfac * (-1.0 +", "assume only one geometry per body self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints", "self.joints] self.joint_positions = [np.array([float(x) for x in p.split()]) for p", "def update_xml(self): pass def update(self, new_params): self.set_params(new_params) self.update_xml() def get_smallest_z(self):", "np.array([float(x) for x in self.xml.get('pos').split()]) def update_point(self, p, new_params): return", "self.body.get_param_limits() def get_param_names(self): return self.body.get_param_names() def get_height(self): return self.body.get_height() def", "in self.parts: param_names += body.get_param_names() return param_names def update_params(self, new_params):", "'mujoco_assets/hopper_test.xml') assert robot.get_params() == params #assert robot.get_height() == 1.31 print(robot.get_param_limits())", "= self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if __name__ == '__main__': robot =", "[float(x) for x in self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3]) self.p2 =", "2)) radius = float(self.xml.get('size')) self.params = [length, radius] self.axis =", "* np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params() == params #assert robot.get_height()", "= geom self.params = [float(self.xml.get('size'))] # radius self.center = np.array([float(x)", "{} for body,pos in zip(self.parts, self.part_positions): for j in body.joints:", "MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params()", "new_params): lfac = p.dot(self.axis) * self.axis rfac = p -", "model_xml): self.model_xml = model_xml self.tree = ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody')", "'mujoco_assets/humanoid_test.xml') assert robot.get_params() == params print(robot.get_height()) #assert robot.get_height() == .6085", "in range(10): env.reset() for _ in range(100): env.step(env.action_space.sample()) rgb =", "self.part_positions = [np.array([float(x) for x in p.split()]) for p in", "def get_param_names(self): return self.body.get_param_names() def get_height(self): return self.body.get_height() def get_joints(self):", "['radius'] def get_volume(self): return 4./3. * np.pi * self.params[0] **", "in pos] self.n = len(self.geom.get_params()) self.n_all_params = len(self.get_params()) self.zmin =", "x in p.split()]) for p in pos] pos = [j.get('pos')", "return [[self.min_length, self.min_radius], [self.max_length, self.max_radius]] def get_param_names(self): return ['length','radius'] def", "geom fromto = [float(x) for x in self.xml.get('fromto').split()] self.p1 =", "self.params[1]) def update_xml(self): self.xml.set('fromto', ' '.join([str(x) for x in np.concatenate([self.p1,", "os.makedirs(outdir, exist_ok=True) i = 0 for _ in range(10): env.reset()", "set_params(self, new_params): p1 = self.update_point(self.p1, new_params) p2 = self.update_point(self.p2, new_params)", "self.parts]) volumes[j.get('name')] = np.array((v1, v2)) for body in self.parts: volumes.update(body.get_volumes())", "enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos, new_params) for i, pos in enumerate(self.joint_positions):", "self.p2 = np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2 - self.p1) ** 2))", "rfac = p - lfac return p + lfac *", "/ length def update_point(self, p, new_params): lfac = p.dot(self.axis) *", "imsave import subprocess as sp outdir = 'xml_vid' os.makedirs(outdir, exist_ok=True)", "after computing p1, p2 self.p1 = p1 self.p2 = p2", "for p in pos] pos = [j.get('pos') for j in", "robot.get_height() == .6085 print(robot.get_param_limits()) print(robot.get_param_names()) import gym, roboschool env =", "self.joints = [j for j in body.findall('joint') if 'ignore' not", "== .6085 print(robot.get_param_limits()) print(robot.get_param_names()) import gym, roboschool env = gym.make(\"RoboschoolHopper-v1\")", "== .2 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8", "0.8 min_radius = 0.035 max_radius = 0.085 def __init__(self, geom):", "import xml.etree.ElementTree as ET class Geom(object): def __init__(self, geom): self.xml", "ET class Geom(object): def __init__(self, geom): self.xml = geom self.params", "= self.geom.get_param_limits() for body in self.parts: body_limits = body.get_param_limits() limits[0]", "fromto = [float(x) for x in self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3])", "update only after computing p1, p2 self.p1 = p1 self.p2", "roboschool env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset() #env.render() import", "1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2, .2,.06,.2,.06,.4,.06,", "sp outdir = 'xml_vid' os.makedirs(outdir, exist_ok=True) i = 0 for", "robot.get_params() == params #assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot", "class Capsule(Geom): min_length = 0.175 max_length = 0.8 min_radius =", "robot.get_params() == params assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot", "def get_volume(self): return 4./3. * np.pi * self.params[1]**3 + self.params[0]", "' '.join(pos)) def update_xml(self): for body, pos in zip(self.parts, self.part_positions):", "get_joints(self): return self.body.get_joints() def get_volumes(self): return self.body.get_volumes() def update(self, params,", "joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'), self.geom, body.geom, pos) joints.update(body.get_joints()) return joints", "in enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos, new_params) def update(self, new_params): self.set_body_positions(new_params)", "pass def update_xml(self): pass def update(self, new_params): self.set_params(new_params) self.update_xml() def", "= 0.085 def __init__(self, geom): self.xml = geom fromto =", "= float(self.xml.get(\"pos\").split()[2]) - self.get_height() def get_height(self): max_height = -self.geom.get_smallest_z() for", "[name + '-' + p for p in self.geom.get_param_names()] for", "> 0: for j in self.joints: v1 = self.geom.get_volume() v2", "geom self.params = [float(self.xml.get('size'))] # radius self.center = np.array([float(x) for", "def set_body_positions(self, new_params): for i, pos in enumerate(self.part_positions): self.part_positions[i] =", "Capsule} # dictionary of legal geometry types def __init__(self, body,", "== params print(robot.get_height()) #assert robot.get_height() == .6085 print(robot.get_param_limits()) print(robot.get_param_names()) import", "= body.get_param_limits() limits[0] += body_limits[0] limits[1] += body_limits[1] return limits", "only one geometry per body self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints =", "os from scipy.misc import imsave import subprocess as sp outdir", "def get_params(self): return self.body.get_params() def get_param_limits(self): return self.body.get_param_limits() def get_param_names(self):", "['length','radius'] def get_volume(self): return 4./3. * np.pi * self.params[1]**3 +", "params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params() == params assert", "self.joint_positions): joint.set('pos', ' '.join([str(x) for x in pos])) def set_body_positions(self,", "geom): self.xml = geom fromto = [float(x) for x in", "in pos])) def set_body_positions(self, new_params): for i, pos in enumerate(self.part_positions):", "j.get('name')] self.parts = [Body(b) for b in body.findall('body')] pos =", "self.p1) ** 2)) radius = float(self.xml.get('size')) self.params = [length, radius]", "worldbody=False): self.xml = body self.worldbody = worldbody geom_xml = body.find('geom')", "per body self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j for j", "i = 0 for _ in range(10): env.reset() for _", "** 2)) radius = float(self.xml.get('size')) self.params = [length, radius] self.axis", "return self.body.get_params() def get_param_limits(self): return self.body.get_param_limits() def get_param_names(self): return self.body.get_param_names()", "/ self.params[0]) + self.center def update_xml(self): self.xml.set('size', str(self.params[0])) def get_smallest_z(self):", "[Body(b) for b in body.findall('body')] pos = [b.get('pos') for b", "self.axis rfac = p - lfac return p + lfac", "in enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos, new_params) for i, pos in", "for body,pos in zip(self.parts, self.part_positions): for j in body.joints: joints[j.get('name')]", "= 'mujoco_assets/hopper_test.xml' env.reset() #env.render() import os from scipy.misc import imsave", "def __init__(self, geom): self.xml = geom fromto = [float(x) for", "get_param_limits(self): return [[self.min_length, self.min_radius], [self.max_length, self.max_radius]] def get_param_names(self): return ['length','radius']", "self.max_radius]] def get_param_names(self): return ['length','radius'] def get_volume(self): return 4./3. *", "print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert", "'-f', 'image2', '-i', os.path.join(outdir, '%05d.png'), '-vcodec', 'libx264', '-pix_fmt', 'yuv420p', os.path.join(outdir,", "body.get_height() - pos[2]) return max_height def update_initial_position(self): pos = self.xml.get(\"pos\").split()", "min_radius = .05 max_radius = .4 def __init__(self, geom): self.xml", "MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params() == params", "_ in range(100): env.step(env.action_space.sample()) rgb = env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb)", "+= body.get_param_names() return param_names def update_params(self, new_params): if self.worldbody: assert", "def get_height(self): max_height = -self.geom.get_smallest_z() for body, pos in zip(self.parts,", "body.xml.set('pos', ' '.join([str(x) for x in pos])) for joint, pos", "body in self.parts: params += body.get_params() return params def get_param_limits(self):", "length def update_point(self, p, new_params): lfac = p.dot(self.axis) * self.axis", "self.n_all_params = len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2]) - self.get_height() def get_height(self):", "= np.sqrt(np.sum((self.p2 - self.p1) ** 2)) radius = float(self.xml.get('size')) self.params", "in zip(self.parts, self.part_positions): for j in body.joints: joints[j.get('name')] = (self.xml.get('name'),", "body self.worldbody = worldbody geom_xml = body.find('geom') # assume only", "p in self.geom.get_param_names()] for body in self.parts: param_names += body.get_param_names()", "= .4 def __init__(self, geom): self.xml = geom self.params =", "self.body.get_param_names() def get_height(self): return self.body.get_height() def get_joints(self): return self.body.get_joints() def", "j in body.joints: joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'), self.geom, body.geom, pos)", "* np.pi * self.params[1]**2 class Body: geoms = {'sphere': Sphere,", "in self.parts: names += body.get_names() return names def get_joints(self): joints", "self.get_height() def get_height(self): max_height = -self.geom.get_smallest_z() for body, pos in", "gym, roboschool env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset() #env.render()", "sp.call(['ffmpeg', '-r', '60', '-f', 'image2', '-i', os.path.join(outdir, '%05d.png'), '-vcodec', 'libx264',", "__init__(self, model_xml): self.model_xml = model_xml self.tree = ET.parse(self.model_xml) worldbody =", "get_param_limits(self): pass def get_param_names(self): pass def get_volume(self): pass class Sphere(Geom):", "in p.split()]) for p in pos] pos = [j.get('pos') for", "+ self.center def update_xml(self): self.xml.set('size', str(self.params[0])) def get_smallest_z(self): return self.center[2]", "Capsule(Geom): min_length = 0.175 max_length = 0.8 min_radius = 0.035", "v2 = sum([b.geom.get_volume() for b in self.parts]) volumes[j.get('name')] = np.array((v1,", "pos = self.xml.get(\"pos\").split() pos[2] = str(self.get_height() + self.zmin) self.xml.set(\"pos\", '", "def set_params(self, new_params): self.params = new_params def update_point(self, p, new_params):", "'.join(pos)) def update_xml(self): for body, pos in zip(self.parts, self.part_positions): body.xml.set('pos',", "body_limits[0] limits[1] += body_limits[1] return limits def get_param_names(self): name =", "update(self, params, xml_file=None): if xml_file is None: xml_file = self.model_xml", "enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos, new_params) def update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params)", "p, new_params): return ((p - self.center) * new_params[0] / self.params[0])", "+ new_params[0] / self.params[0])# + rfac * (new_params[1] / self.params[1])", "new_params): self.params = new_params def update_point(self, p, new_params): pass def", "= [] def get_params(self): return self.params.copy() def set_params(self, new_params): self.params", "in self.parts: remaining_params = body.update_params(remaining_params) if self.worldbody: self.update_initial_position() else: return", "(self.xml.get('name'), body.xml.get('name'), self.geom, body.geom, pos) joints.update(body.get_joints()) return joints def get_volumes(self):", "lfac return p + lfac * (-1.0 + new_params[0] /", "self.xml.set('size', str(self.params[1])) # radius def set_params(self, new_params): p1 = self.update_point(self.p1,", "= model_xml self.tree = ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody') self.body =", "body.get_params() return params def get_param_limits(self): limits = self.geom.get_param_limits() for body", "Sphere(Geom): min_radius = .05 max_radius = .4 def __init__(self, geom):", "list(1.0 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params() == params #assert", "+ p for p in self.geom.get_param_names()] for body in self.parts:", "self.center) * new_params[0] / self.params[0]) + self.center def update_xml(self): self.xml.set('size',", "= ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'), worldbody=True) def", "= {} for body,pos in zip(self.parts, self.part_positions): for j in", "pos in zip(self.parts, self.part_positions): body.xml.set('pos', ' '.join([str(x) for x in", "print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06,", "= self.update_point(self.p2, new_params) # update only after computing p1, p2", "self.model_xml = model_xml self.tree = ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody') self.body", "return 4./3. * np.pi * self.params[1]**3 + self.params[0] * np.pi", "import os from scipy.misc import imsave import subprocess as sp", "((p - self.center) * new_params[0] / self.params[0]) + self.center def", "self.min_radius], [self.max_length, self.max_radius]] def get_param_names(self): return ['length','radius'] def get_volume(self): return", "self.update_point(self.p2, new_params) # update only after computing p1, p2 self.p1", "[np.array([float(x) for x in p.split()]) for p in pos] pos", "in self.parts: volumes.update(body.get_volumes()) return volumes class MuJoCoXmlRobot: def __init__(self, model_xml):", "#assert robot.get_height() == .6085 print(robot.get_param_limits()) print(robot.get_param_names()) import gym, roboschool env", "for _ in range(100): env.step(env.action_space.sample()) rgb = env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)),", "in self.parts: params += body.get_params() return params def get_param_limits(self): limits", "max(max_height, body.get_height() - pos[2]) return max_height def update_initial_position(self): pos =", "self.p2 = p2 super().set_params(new_params) def get_smallest_z(self): return min(self.p1[2], self.p2[2]) -", "self.parts: body_limits = body.get_param_limits() limits[0] += body_limits[0] limits[1] += body_limits[1]", "'-' + p for p in self.geom.get_param_names()] for body in", "= p - lfac return p + lfac * (-1.0", "params = list(.8 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params() ==", "get_param_limits(self): limits = self.geom.get_param_limits() for body in self.parts: body_limits =", "return 4./3. * np.pi * self.params[0] ** 3 class Capsule(Geom):", "* (-1.0 + new_params[0] / self.params[0])# + rfac * (new_params[1]", "parameters\" self.update(new_params[:self.n]) remaining_params = new_params[self.n:] for body in self.parts: remaining_params", "params += body.get_params() return params def get_param_limits(self): limits = self.geom.get_param_limits()", "for body in self.parts: names += body.get_names() return names def", "{} if len(self.joints) > 0: for j in self.joints: v1", "self.parts: volumes.update(body.get_volumes()) return volumes class MuJoCoXmlRobot: def __init__(self, model_xml): self.model_xml", "def get_smallest_z(self): pass def get_param_limits(self): pass def get_param_names(self): pass def", "in range(100): env.step(env.action_space.sample()) rgb = env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1", "def get_param_names(self): pass def get_volume(self): pass class Sphere(Geom): min_radius =", "assert len(new_params) == self.n_all_params, \"Wrong number of parameters\" self.update(new_params[:self.n]) remaining_params", "new_params[0] / self.params[0])# + rfac * (new_params[1] / self.params[1]) def", "np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params() == params print(robot.get_height()) #assert robot.get_height()", "get_body_names(self): names = [self.xml.get('name')] for body in self.parts: names +=", "self.worldbody = worldbody geom_xml = body.find('geom') # assume only one", "p1 = self.update_point(self.p1, new_params) p2 = self.update_point(self.p2, new_params) # update", ".05 max_radius = .4 def __init__(self, geom): self.xml = geom", "params def get_param_limits(self): limits = self.geom.get_param_limits() for body in self.parts:", "- self.p1) / length def update_point(self, p, new_params): lfac =", "__init__(self, geom): self.xml = geom fromto = [float(x) for x", "def get_smallest_z(self): return self.center[2] - self.params[0] def get_param_limits(self): return [[self.min_radius],", "volumes.update(body.get_volumes()) return volumes class MuJoCoXmlRobot: def __init__(self, model_xml): self.model_xml =", "p2 = self.update_point(self.p2, new_params) # update only after computing p1,", "= geom fromto = [float(x) for x in self.xml.get('fromto').split()] self.p1", ".4 def __init__(self, geom): self.xml = geom self.params = [float(self.xml.get('size'))]", "p in pos] pos = [j.get('pos') for j in self.joints]", "self.xml.get(\"pos\").split() pos[2] = str(self.get_height() + self.zmin) self.xml.set(\"pos\", ' '.join(pos)) def", "= sum([b.geom.get_volume() for b in self.parts]) volumes[j.get('name')] = np.array((v1, v2))", "self.body = Body(worldbody.find('body'), worldbody=True) def get_params(self): return self.body.get_params() def get_param_limits(self):", "import gym, roboschool env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset()", "np.array((v1, v2)) for body in self.parts: volumes.update(body.get_volumes()) return volumes class", "return names def get_joints(self): joints = {} for body,pos in", "get_param_limits(self): return [[self.min_radius], [self.max_radius]] def get_param_names(self): return ['radius'] def get_volume(self):", "limits def get_param_names(self): name = self.xml.get('name') param_names = [name +", "len(self.geom.get_params()) self.n_all_params = len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2]) - self.get_height() def", "def update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def get_params(self): params =", "self.params = [] def get_params(self): return self.params.copy() def set_params(self, new_params):", "for body in self.parts: volumes.update(body.get_volumes()) return volumes class MuJoCoXmlRobot: def", "[length, radius] self.axis = (self.p2 - self.p1) / length def", "get_param_names(self): return ['length','radius'] def get_volume(self): return 4./3. * np.pi *", "for joint, pos in zip(self.joints, self.joint_positions): joint.set('pos', ' '.join([str(x) for", "np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params() == params #assert robot.get_height() ==", "* np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params() == params print(robot.get_height()) #assert", "self.n_all_params, \"Wrong number of parameters\" self.update(new_params[:self.n]) remaining_params = new_params[self.n:] for", "def get_volume(self): pass class Sphere(Geom): min_radius = .05 max_radius =", "def get_param_limits(self): return [[self.min_length, self.min_radius], [self.max_length, self.max_radius]] def get_param_names(self): return", "for body, pos in zip(self.parts, self.part_positions): max_height = max(max_height, body.get_height()", "new_params) p2 = self.update_point(self.p2, new_params) # update only after computing", "self.geom.update(new_params) self.update_xml() def get_params(self): params = self.geom.get_params() for body in", "self.parts: remaining_params = body.update_params(remaining_params) if self.worldbody: self.update_initial_position() else: return remaining_params", "self.body.get_height() def get_joints(self): return self.body.get_joints() def get_volumes(self): return self.body.get_volumes() def", "pass class Sphere(Geom): min_radius = .05 max_radius = .4 def", "'capsule': Capsule} # dictionary of legal geometry types def __init__(self,", "# radius self.center = np.array([float(x) for x in self.xml.get('pos').split()]) def", "Body: geoms = {'sphere': Sphere, 'capsule': Capsule} # dictionary of", "for x in self.xml.get('pos').split()]) def update_point(self, p, new_params): return ((p", "= [self.xml.get('name')] for body in self.parts: names += body.get_names() return", "j in self.joints] self.joint_positions = [np.array([float(x) for x in p.split()])", "radius def set_params(self, new_params): p1 = self.update_point(self.p1, new_params) p2 =", "[self.xml.get('name')] for body in self.parts: names += body.get_names() return names", "new_params): p1 = self.update_point(self.p1, new_params) p2 = self.update_point(self.p2, new_params) #", "in zip(self.parts, self.part_positions): body.xml.set('pos', ' '.join([str(x) for x in pos]))", "worldbody=True) def get_params(self): return self.body.get_params() def get_param_limits(self): return self.body.get_param_limits() def", "self.update_initial_position() else: return remaining_params def get_body_names(self): names = [self.xml.get('name')] for", "limits[1] += body_limits[1] return limits def get_param_names(self): name = self.xml.get('name')", "body.update_params(remaining_params) if self.worldbody: self.update_initial_position() else: return remaining_params def get_body_names(self): names", "body in self.parts: volumes.update(body.get_volumes()) return volumes class MuJoCoXmlRobot: def __init__(self,", "self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3]) self.p2 = np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2", "[[self.min_radius], [self.max_radius]] def get_param_names(self): return ['radius'] def get_volume(self): return 4./3.", "joint.set('pos', ' '.join([str(x) for x in pos])) def set_body_positions(self, new_params):", "self.xml = geom fromto = [float(x) for x in self.xml.get('fromto').split()]", "p.split()]) for p in pos] self.n = len(self.geom.get_params()) self.n_all_params =", "Geom(object): def __init__(self, geom): self.xml = geom self.params = []", "geometry per body self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j for", "body.get_names() return names def get_joints(self): joints = {} for body,pos", "[np.array([float(x) for x in p.split()]) for p in pos] self.n", "- self.params[1] def get_param_limits(self): return [[self.min_length, self.min_radius], [self.max_length, self.max_radius]] def", "body.geom, pos) joints.update(body.get_joints()) return joints def get_volumes(self): volumes = {}", "= new_params def update_point(self, p, new_params): pass def update_xml(self): pass", "for body in self.parts: remaining_params = body.update_params(remaining_params) if self.worldbody: self.update_initial_position()", "self.p1) / length def update_point(self, p, new_params): lfac = p.dot(self.axis)", "robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params() == params assert robot.get_height() == .2", "np.array(fromto[:3]) self.p2 = np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2 - self.p1) **", "in np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1])) # radius def set_params(self, new_params):", "get_smallest_z(self): return self.center[2] - self.params[0] def get_param_limits(self): return [[self.min_radius], [self.max_radius]]", "= .05 max_radius = .4 def __init__(self, geom): self.xml =", "if 'ignore' not in j.get('name')] self.parts = [Body(b) for b", "radius = float(self.xml.get('size')) self.params = [length, radius] self.axis = (self.p2", "self.p2[2]) - self.params[1] def get_param_limits(self): return [[self.min_length, self.min_radius], [self.max_length, self.max_radius]]", "def set_params(self, new_params): p1 = self.update_point(self.p1, new_params) p2 = self.update_point(self.p2,", "in pos] pos = [j.get('pos') for j in self.joints] self.joint_positions", "pos in zip(self.parts, self.part_positions): max_height = max(max_height, body.get_height() - pos[2])", "get_joints(self): joints = {} for body,pos in zip(self.parts, self.part_positions): for", "self.xml.set('fromto', ' '.join([str(x) for x in np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1]))", "volumes class MuJoCoXmlRobot: def __init__(self, model_xml): self.model_xml = model_xml self.tree", "robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml')", "[[self.min_length, self.min_radius], [self.max_length, self.max_radius]] def get_param_names(self): return ['length','radius'] def get_volume(self):", "__init__(self, body, worldbody=False): self.xml = body self.worldbody = worldbody geom_xml", "update(self, new_params): self.set_params(new_params) self.update_xml() def get_smallest_z(self): pass def get_param_limits(self): pass", "assert robot.get_params() == params print(robot.get_height()) #assert robot.get_height() == .6085 print(robot.get_param_limits())", "i, pos in enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos, new_params) for i,", "robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06]", "xml_file=None): if xml_file is None: xml_file = self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file)", "np.pi * self.params[0] ** 3 class Capsule(Geom): min_length = 0.175", "4./3. * np.pi * self.params[1]**3 + self.params[0] * np.pi *", "pass def update(self, new_params): self.set_params(new_params) self.update_xml() def get_smallest_z(self): pass def", "MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert robot.get_params()", "'__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0 * np.array(robot.get_params())) robot.update(params,", "range(10): env.reset() for _ in range(100): env.step(env.action_space.sample()) rgb = env.render('rgb_array')", "self.params.copy() def set_params(self, new_params): self.params = new_params def update_point(self, p,", "self.body.get_params() def get_param_limits(self): return self.body.get_param_limits() def get_param_names(self): return self.body.get_param_names() def", "= MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert", "joint, pos in zip(self.joints, self.joint_positions): joint.set('pos', ' '.join([str(x) for x", "new_params) def update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def get_params(self): params", "def __init__(self, model_xml): self.model_xml = model_xml self.tree = ET.parse(self.model_xml) worldbody", "len(new_params) == self.n_all_params, \"Wrong number of parameters\" self.update(new_params[:self.n]) remaining_params =", "def get_param_names(self): name = self.xml.get('name') param_names = [name + '-'", "limits[0] += body_limits[0] limits[1] += body_limits[1] return limits def get_param_names(self):", "def get_smallest_z(self): return min(self.p1[2], self.p2[2]) - self.params[1] def get_param_limits(self): return", "param_names def update_params(self, new_params): if self.worldbody: assert len(new_params) == self.n_all_params,", "j in self.joints: v1 = self.geom.get_volume() v2 = sum([b.geom.get_volume() for", "self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j for j in body.findall('joint')", "= [j.get('pos') for j in self.joints] self.joint_positions = [np.array([float(x) for", "pos] self.n = len(self.geom.get_params()) self.n_all_params = len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2])", "= geom self.params = [] def get_params(self): return self.params.copy() def", "for x in p.split()]) for p in pos] pos =", "self.tree.write(xml_file) if __name__ == '__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params =", "pos in enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos, new_params) for i, pos", "return self.body.get_volumes() def update(self, params, xml_file=None): if xml_file is None:", "p for p in self.geom.get_param_names()] for body in self.parts: param_names", "self.geom.update_point(pos, new_params) def update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def get_params(self):", "self.axis = (self.p2 - self.p1) / length def update_point(self, p,", "4./3. * np.pi * self.params[0] ** 3 class Capsule(Geom): min_length", "def update_initial_position(self): pos = self.xml.get(\"pos\").split() pos[2] = str(self.get_height() + self.zmin)", "return max_height def update_initial_position(self): pos = self.xml.get(\"pos\").split() pos[2] = str(self.get_height()", "(self.p2 - self.p1) / length def update_point(self, p, new_params): lfac", "self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'), worldbody=True) def get_params(self): return self.body.get_params() def", "\"Wrong number of parameters\" self.update(new_params[:self.n]) remaining_params = new_params[self.n:] for body", "= Body(worldbody.find('body'), worldbody=True) def get_params(self): return self.body.get_params() def get_param_limits(self): return", "return ((p - self.center) * new_params[0] / self.params[0]) + self.center", "self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if __name__ == '__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml')", "(new_params[1] / self.params[1]) def update_xml(self): self.xml.set('fromto', ' '.join([str(x) for x", "remaining_params = body.update_params(remaining_params) if self.worldbody: self.update_initial_position() else: return remaining_params def", "str(self.get_height() + self.zmin) self.xml.set(\"pos\", ' '.join(pos)) def update_xml(self): for body,", "#assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params", "max_radius = 0.085 def __init__(self, geom): self.xml = geom fromto", "= np.array([float(x) for x in self.xml.get('pos').split()]) def update_point(self, p, new_params):", ".2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params() == params", "geom_xml = body.find('geom') # assume only one geometry per body", "b in body.findall('body')] self.part_positions = [np.array([float(x) for x in p.split()])", "np.pi * self.params[1]**3 + self.params[0] * np.pi * self.params[1]**2 class", "self.tree = ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'), worldbody=True)", "for body in self.parts: body_limits = body.get_param_limits() limits[0] += body_limits[0]", "zip(self.parts, self.part_positions): for j in body.joints: joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'),", "env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg', '-r', '60', '-f', 'image2',", "# dictionary of legal geometry types def __init__(self, body, worldbody=False):", "worldbody = self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'), worldbody=True) def get_params(self): return", "self.parts: params += body.get_params() return params def get_param_limits(self): limits =", "self.part_positions): body.xml.set('pos', ' '.join([str(x) for x in pos])) for joint,", "= {'sphere': Sphere, 'capsule': Capsule} # dictionary of legal geometry", "= MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/hopper_test.xml') assert", "assert robot.get_height() == .2 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params", "* np.pi * self.params[0] ** 3 class Capsule(Geom): min_length =", "p1, p2 self.p1 = p1 self.p2 = p2 super().set_params(new_params) def", "= self.xml.get('name') param_names = [name + '-' + p for", "print(robot.get_param_names()) import gym, roboschool env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml'", "pos])) for joint, pos in zip(self.joints, self.joint_positions): joint.set('pos', ' '.join([str(x)", "exist_ok=True) i = 0 for _ in range(10): env.reset() for", "new_params): if self.worldbody: assert len(new_params) == self.n_all_params, \"Wrong number of", "if self.worldbody: self.update_initial_position() else: return remaining_params def get_body_names(self): names =", "x in self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3]) self.p2 = np.array(fromto[3:]) length", "new_params) for i, pos in enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos, new_params)", "of parameters\" self.update(new_params[:self.n]) remaining_params = new_params[self.n:] for body in self.parts:", "import subprocess as sp outdir = 'xml_vid' os.makedirs(outdir, exist_ok=True) i", "self.params[0] * np.pi * self.params[1]**2 class Body: geoms = {'sphere':", "'60', '-f', 'image2', '-i', os.path.join(outdir, '%05d.png'), '-vcodec', 'libx264', '-pix_fmt', 'yuv420p',", "update_point(self, p, new_params): return ((p - self.center) * new_params[0] /", "assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params", "for p in pos] self.n = len(self.geom.get_params()) self.n_all_params = len(self.get_params())", "remaining_params = new_params[self.n:] for body in self.parts: remaining_params = body.update_params(remaining_params)", "get_height(self): return self.body.get_height() def get_joints(self): return self.body.get_joints() def get_volumes(self): return", "subprocess as sp outdir = 'xml_vid' os.makedirs(outdir, exist_ok=True) i =", "self.update_point(self.p1, new_params) p2 = self.update_point(self.p2, new_params) # update only after", "= new_params[self.n:] for body in self.parts: remaining_params = body.update_params(remaining_params) if", "return self.body.get_joints() def get_volumes(self): return self.body.get_volumes() def update(self, params, xml_file=None):", "len(self.joints) > 0: for j in self.joints: v1 = self.geom.get_volume()", "in body.findall('joint') if 'ignore' not in j.get('name')] self.parts = [Body(b)", "body.joints: joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'), self.geom, body.geom, pos) joints.update(body.get_joints()) return", "pass def get_volume(self): pass class Sphere(Geom): min_radius = .05 max_radius", "= self.geom.get_params() for body in self.parts: params += body.get_params() return", "p2 self.p1 = p1 self.p2 = p2 super().set_params(new_params) def get_smallest_z(self):", "__init__(self, geom): self.xml = geom self.params = [float(self.xml.get('size'))] # radius", "'mujoco_assets/hopper_test.xml' env.reset() #env.render() import os from scipy.misc import imsave import", "return p + lfac * (-1.0 + new_params[0] / self.params[0])#", "p in pos] self.n = len(self.geom.get_params()) self.n_all_params = len(self.get_params()) self.zmin", "self.geom.get_params() for body in self.parts: params += body.get_params() return params", "min_radius = 0.035 max_radius = 0.085 def __init__(self, geom): self.xml", "def get_params(self): return self.params.copy() def set_params(self, new_params): self.params = new_params", "for i, pos in enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos, new_params) def", "== params #assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot =", "== 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06]", "return self.body.get_height() def get_joints(self): return self.body.get_joints() def get_volumes(self): return self.body.get_volumes()", "self.params[0]) + self.center def update_xml(self): self.xml.set('size', str(self.params[0])) def get_smallest_z(self): return", "__init__(self, geom): self.xml = geom self.params = [] def get_params(self):", "self.worldbody: assert len(new_params) == self.n_all_params, \"Wrong number of parameters\" self.update(new_params[:self.n])", "params = self.geom.get_params() for body in self.parts: params += body.get_params()", "class MuJoCoXmlRobot: def __init__(self, model_xml): self.model_xml = model_xml self.tree =", "for x in pos])) for joint, pos in zip(self.joints, self.joint_positions):", "xml.etree.ElementTree as ET class Geom(object): def __init__(self, geom): self.xml =", "max_height = -self.geom.get_smallest_z() for body, pos in zip(self.parts, self.part_positions): max_height", "number of parameters\" self.update(new_params[:self.n]) remaining_params = new_params[self.n:] for body in", "set_params(self, new_params): self.params = new_params def update_point(self, p, new_params): pass", "joints def get_volumes(self): volumes = {} if len(self.joints) > 0:", "np.pi * self.params[1]**2 class Body: geoms = {'sphere': Sphere, 'capsule':", "super().set_params(new_params) def get_smallest_z(self): return min(self.p1[2], self.p2[2]) - self.params[1] def get_param_limits(self):", "legal geometry types def __init__(self, body, worldbody=False): self.xml = body", "assert robot.get_params() == params #assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names())", "'.join([str(x) for x in pos])) def set_body_positions(self, new_params): for i,", "= body.update_params(remaining_params) if self.worldbody: self.update_initial_position() else: return remaining_params def get_body_names(self):", "xml_file is None: xml_file = self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if __name__", "numpy as np import xml.etree.ElementTree as ET class Geom(object): def", "self.xml.set(\"pos\", ' '.join(pos)) def update_xml(self): for body, pos in zip(self.parts,", "self.parts: param_names += body.get_param_names() return param_names def update_params(self, new_params): if", "self.p1 = p1 self.p2 = p2 super().set_params(new_params) def get_smallest_z(self): return", "min(self.p1[2], self.p2[2]) - self.params[1] def get_param_limits(self): return [[self.min_length, self.min_radius], [self.max_length,", "radius self.center = np.array([float(x) for x in self.xml.get('pos').split()]) def update_point(self,", "for x in self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3]) self.p2 = np.array(fromto[3:])", "* self.params[1]**2 class Body: geoms = {'sphere': Sphere, 'capsule': Capsule}", "robot.get_params() == params print(robot.get_height()) #assert robot.get_height() == .6085 print(robot.get_param_limits()) print(robot.get_param_names())", "p.split()]) for p in pos] pos = [j.get('pos') for j", "body.get_param_names() return param_names def update_params(self, new_params): if self.worldbody: assert len(new_params)", "pass def get_param_names(self): pass def get_volume(self): pass class Sphere(Geom): min_radius", "new_params): for i, pos in enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos, new_params)", "return self.center[2] - self.params[0] def get_param_limits(self): return [[self.min_radius], [self.max_radius]] def", "print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml')", "self.xml.set('size', str(self.params[0])) def get_smallest_z(self): return self.center[2] - self.params[0] def get_param_limits(self):", "return limits def get_param_names(self): name = self.xml.get('name') param_names = [name", "print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06,", "self.body.get_joints() def get_volumes(self): return self.body.get_volumes() def update(self, params, xml_file=None): if", "rfac * (new_params[1] / self.params[1]) def update_xml(self): self.xml.set('fromto', ' '.join([str(x)", "in body.findall('body')] self.part_positions = [np.array([float(x) for x in p.split()]) for", "pos] pos = [j.get('pos') for j in self.joints] self.joint_positions =", "* self.params[1]**3 + self.params[0] * np.pi * self.params[1]**2 class Body:", "self.joints: v1 = self.geom.get_volume() v2 = sum([b.geom.get_volume() for b in", "def get_param_limits(self): pass def get_param_names(self): pass def get_volume(self): pass class", "robot.get_height() == .2 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params =", "return volumes class MuJoCoXmlRobot: def __init__(self, model_xml): self.model_xml = model_xml", "0.085 def __init__(self, geom): self.xml = geom fromto = [float(x)", "for j in body.findall('joint') if 'ignore' not in j.get('name')] self.parts", "min_length = 0.175 max_length = 0.8 min_radius = 0.035 max_radius", "i, pos in enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos, new_params) def update(self,", "self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def get_params(self): params = self.geom.get_params() for body", "robot.get_params() == params assert robot.get_height() == .2 print(robot.get_param_limits()) print(robot.get_param_names()) robot", "for b in self.parts]) volumes[j.get('name')] = np.array((v1, v2)) for body", "= 0.035 max_radius = 0.085 def __init__(self, geom): self.xml =", "'.join([str(x) for x in pos])) for joint, pos in zip(self.joints,", "* self.axis rfac = p - lfac return p +", "* np.pi * self.params[1]**3 + self.params[0] * np.pi * self.params[1]**2", "class Geom(object): def __init__(self, geom): self.xml = geom self.params =", "sum([b.geom.get_volume() for b in self.parts]) volumes[j.get('name')] = np.array((v1, v2)) for", "new_params): return ((p - self.center) * new_params[0] / self.params[0]) +", "max_length = 0.8 min_radius = 0.035 max_radius = 0.085 def", "in self.parts: body_limits = body.get_param_limits() limits[0] += body_limits[0] limits[1] +=", "for b in body.findall('body')] self.part_positions = [np.array([float(x) for x in", "self.geom.get_param_names()] for body in self.parts: param_names += body.get_param_names() return param_names", "if __name__ == '__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params = list(1.0", "print(robot.get_param_limits()) print(robot.get_param_names()) import gym, roboschool env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml =", "zip(self.parts, self.part_positions): body.xml.set('pos', ' '.join([str(x) for x in pos])) for", "p, new_params): lfac = p.dot(self.axis) * self.axis rfac = p", "return [[self.min_radius], [self.max_radius]] def get_param_names(self): return ['radius'] def get_volume(self): return", "pos in zip(self.joints, self.joint_positions): joint.set('pos', ' '.join([str(x) for x in", "= [j for j in body.findall('joint') if 'ignore' not in", "joints = {} for body,pos in zip(self.parts, self.part_positions): for j", "= self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'), worldbody=True) def get_params(self): return self.body.get_params()", "def get_volume(self): return 4./3. * np.pi * self.params[0] ** 3", "- lfac return p + lfac * (-1.0 + new_params[0]", "for i, pos in enumerate(self.part_positions): self.part_positions[i] = self.geom.update_point(pos, new_params) for", "p.dot(self.axis) * self.axis rfac = p - lfac return p", "params #assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml')", ".2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params() == params assert robot.get_height() ==", "body in self.parts: remaining_params = body.update_params(remaining_params) if self.worldbody: self.update_initial_position() else:", "body in self.parts: names += body.get_names() return names def get_joints(self):", "names def get_joints(self): joints = {} for body,pos in zip(self.parts,", "robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params =", "+ self.zmin) self.xml.set(\"pos\", ' '.join(pos)) def update_xml(self): for body, pos", "in self.parts]) volumes[j.get('name')] = np.array((v1, v2)) for body in self.parts:", "{'sphere': Sphere, 'capsule': Capsule} # dictionary of legal geometry types", "def get_params(self): params = self.geom.get_params() for body in self.parts: params", "assert robot.get_params() == params assert robot.get_height() == .2 print(robot.get_param_limits()) print(robot.get_param_names())", "for x in pos])) def set_body_positions(self, new_params): for i, pos", "x in pos])) for joint, pos in zip(self.joints, self.joint_positions): joint.set('pos',", "env.reset() #env.render() import os from scipy.misc import imsave import subprocess", "+= body.get_names() return names def get_joints(self): joints = {} for", "model_xml self.tree = ET.parse(self.model_xml) worldbody = self.tree.getroot().find('worldbody') self.body = Body(worldbody.find('body'),", "x in np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1])) # radius def set_params(self,", "for body, pos in zip(self.parts, self.part_positions): body.xml.set('pos', ' '.join([str(x) for", "in j.get('name')] self.parts = [Body(b) for b in body.findall('body')] pos", "= self.geom.update_point(pos, new_params) def update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def", "= 0 for _ in range(10): env.reset() for _ in", "= (self.xml.get('name'), body.xml.get('name'), self.geom, body.geom, pos) joints.update(body.get_joints()) return joints def", "#env.render() import os from scipy.misc import imsave import subprocess as", "= [float(x) for x in self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3]) self.p2", "geom): self.xml = geom self.params = [] def get_params(self): return", "self.joint_positions = [np.array([float(x) for x in p.split()]) for p in", "= MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params() ==", "in p.split()]) for p in pos] self.n = len(self.geom.get_params()) self.n_all_params", "= [np.array([float(x) for x in p.split()]) for p in pos]", "= self.xml.get(\"pos\").split() pos[2] = str(self.get_height() + self.zmin) self.xml.set(\"pos\", ' '.join(pos))", "== params assert robot.get_height() == .2 print(robot.get_param_limits()) print(robot.get_param_names()) robot =", "return self.params.copy() def set_params(self, new_params): self.params = new_params def update_point(self,", "3 class Capsule(Geom): min_length = 0.175 max_length = 0.8 min_radius", "class Body: geoms = {'sphere': Sphere, 'capsule': Capsule} # dictionary", "'image2', '-i', os.path.join(outdir, '%05d.png'), '-vcodec', 'libx264', '-pix_fmt', 'yuv420p', os.path.join(outdir, 'out.mp4')])", "= list(.8 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params() == params", "# update only after computing p1, p2 self.p1 = p1", "body self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j for j in", "b in self.parts]) volumes[j.get('name')] = np.array((v1, v2)) for body in", "self.params[0] def get_param_limits(self): return [[self.min_radius], [self.max_radius]] def get_param_names(self): return ['radius']", "return ['radius'] def get_volume(self): return 4./3. * np.pi * self.params[0]", "self.p1 = np.array(fromto[:3]) self.p2 = np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2 -", "' '.join([str(x) for x in pos])) for joint, pos in", "robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params()", "v1 = self.geom.get_volume() v2 = sum([b.geom.get_volume() for b in self.parts])", "def __init__(self, body, worldbody=False): self.xml = body self.worldbody = worldbody", "self.zmin = float(self.xml.get(\"pos\").split()[2]) - self.get_height() def get_height(self): max_height = -self.geom.get_smallest_z()", "update_point(self, p, new_params): pass def update_xml(self): pass def update(self, new_params):", "self.center def update_xml(self): self.xml.set('size', str(self.params[0])) def get_smallest_z(self): return self.center[2] -", "geom): self.xml = geom self.params = [float(self.xml.get('size'))] # radius self.center", "self.xml = geom self.params = [float(self.xml.get('size'))] # radius self.center =", "def get_param_limits(self): limits = self.geom.get_param_limits() for body in self.parts: body_limits", "env.reset() for _ in range(100): env.step(env.action_space.sample()) rgb = env.render('rgb_array') imsave(os.path.join(outdir,", "joints.update(body.get_joints()) return joints def get_volumes(self): volumes = {} if len(self.joints)", "as np import xml.etree.ElementTree as ET class Geom(object): def __init__(self,", "0: for j in self.joints: v1 = self.geom.get_volume() v2 =", "Sphere, 'capsule': Capsule} # dictionary of legal geometry types def", "[b.get('pos') for b in body.findall('body')] self.part_positions = [np.array([float(x) for x", "update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml() def get_params(self): params = self.geom.get_params()", "= body.find('geom') # assume only one geometry per body self.geom", "body.findall('body')] pos = [b.get('pos') for b in body.findall('body')] self.part_positions =", "pos in enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos, new_params) def update(self, new_params):", "update_params(self, new_params): if self.worldbody: assert len(new_params) == self.n_all_params, \"Wrong number", "- pos[2]) return max_height def update_initial_position(self): pos = self.xml.get(\"pos\").split() pos[2]", "'-r', '60', '-f', 'image2', '-i', os.path.join(outdir, '%05d.png'), '-vcodec', 'libx264', '-pix_fmt',", "self.update_xml() def get_smallest_z(self): pass def get_param_limits(self): pass def get_param_names(self): pass", "p2 super().set_params(new_params) def get_smallest_z(self): return min(self.p1[2], self.p2[2]) - self.params[1] def", "robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8 * np.array(robot.get_params())) robot.update(params, 'mujoco_assets/humanoid_test.xml')", "get_param_names(self): return self.body.get_param_names() def get_height(self): return self.body.get_height() def get_joints(self): return", "from scipy.misc import imsave import subprocess as sp outdir =", "as sp outdir = 'xml_vid' os.makedirs(outdir, exist_ok=True) i = 0", "self.center[2] - self.params[0] def get_param_limits(self): return [[self.min_radius], [self.max_radius]] def get_param_names(self):", "in self.xml.get('pos').split()]) def update_point(self, p, new_params): return ((p - self.center)", "get_param_names(self): name = self.xml.get('name') param_names = [name + '-' +", "Body(worldbody.find('body'), worldbody=True) def get_params(self): return self.body.get_params() def get_param_limits(self): return self.body.get_param_limits()", "-self.geom.get_smallest_z() for body, pos in zip(self.parts, self.part_positions): max_height = max(max_height,", "= max(max_height, body.get_height() - pos[2]) return max_height def update_initial_position(self): pos", "self.parts = [Body(b) for b in body.findall('body')] pos = [b.get('pos')", "self.geom.get_volume() v2 = sum([b.geom.get_volume() for b in self.parts]) volumes[j.get('name')] =", "str(self.params[0])) def get_smallest_z(self): return self.center[2] - self.params[0] def get_param_limits(self): return", "= 0.175 max_length = 0.8 min_radius = 0.035 max_radius =", "= [length, radius] self.axis = (self.p2 - self.p1) / length", "= float(self.xml.get('size')) self.params = [length, radius] self.axis = (self.p2 -", "== 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2,", "' '.join([str(x) for x in pos])) def set_body_positions(self, new_params): for", "+= body.get_params() return params def get_param_limits(self): limits = self.geom.get_param_limits() for", "is None: xml_file = self.model_xml self.body.update_params(list(params)) self.tree.write(xml_file) if __name__ ==", "def update_point(self, p, new_params): return ((p - self.center) * new_params[0]", "+= body_limits[0] limits[1] += body_limits[1] return limits def get_param_names(self): name", "for p in self.geom.get_param_names()] for body in self.parts: param_names +=", "i+=1 sp.call(['ffmpeg', '-r', '60', '-f', 'image2', '-i', os.path.join(outdir, '%05d.png'), '-vcodec',", "def get_volumes(self): return self.body.get_volumes() def update(self, params, xml_file=None): if xml_file", "volumes[j.get('name')] = np.array((v1, v2)) for body in self.parts: volumes.update(body.get_volumes()) return", "return self.body.get_param_names() def get_height(self): return self.body.get_height() def get_joints(self): return self.body.get_joints()", "'ignore' not in j.get('name')] self.parts = [Body(b) for b in", "[self.max_length, self.max_radius]] def get_param_names(self): return ['length','radius'] def get_volume(self): return 4./3.", "worldbody geom_xml = body.find('geom') # assume only one geometry per", "in body.findall('body')] pos = [b.get('pos') for b in body.findall('body')] self.part_positions", "[j.get('pos') for j in self.joints] self.joint_positions = [np.array([float(x) for x", "1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/walker2d.xml') params = [.4,.04,.5,.05,.55,.055,.6,.06,.5,.05,.55,.055,.6,.06] robot.update(params,", "print(robot.get_height()) #assert robot.get_height() == .6085 print(robot.get_param_limits()) print(robot.get_param_names()) import gym, roboschool", "update_xml(self): for body, pos in zip(self.parts, self.part_positions): body.xml.set('pos', ' '.join([str(x)", "limits = self.geom.get_param_limits() for body in self.parts: body_limits = body.get_param_limits()", "pos) joints.update(body.get_joints()) return joints def get_volumes(self): volumes = {} if", "body in self.parts: body_limits = body.get_param_limits() limits[0] += body_limits[0] limits[1]", "return joints def get_volumes(self): volumes = {} if len(self.joints) >", "env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset() #env.render() import os", "def get_joints(self): joints = {} for body,pos in zip(self.parts, self.part_positions):", "= [b.get('pos') for b in body.findall('body')] self.part_positions = [np.array([float(x) for", "body_limits[1] return limits def get_param_names(self): name = self.xml.get('name') param_names =", "env.step(env.action_space.sample()) rgb = env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg', '-r',", "- self.get_height() def get_height(self): max_height = -self.geom.get_smallest_z() for body, pos", "one geometry per body self.geom = self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j", "robot.update(params, 'mujoco_assets/walker2d_test.xml') assert robot.get_params() == params assert robot.get_height() == 1.31", "if len(self.joints) > 0: for j in self.joints: v1 =", "params print(robot.get_height()) #assert robot.get_height() == .6085 print(robot.get_param_limits()) print(robot.get_param_names()) import gym,", "= gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml = 'mujoco_assets/hopper_test.xml' env.reset() #env.render() import os from", "= np.array((v1, v2)) for body in self.parts: volumes.update(body.get_volumes()) return volumes", "MuJoCoXmlRobot('mujoco_assets/ant.xml') params = [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml')", "get_params(self): return self.body.get_params() def get_param_limits(self): return self.body.get_param_limits() def get_param_names(self): return", "pos[2]) return max_height def update_initial_position(self): pos = self.xml.get(\"pos\").split() pos[2] =", ".2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params() == params assert robot.get_height()", "= np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2 - self.p1) ** 2)) radius", "'{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg', '-r', '60', '-f', 'image2', '-i', os.path.join(outdir,", "only after computing p1, p2 self.p1 = p1 self.p2 =", "get_volumes(self): return self.body.get_volumes() def update(self, params, xml_file=None): if xml_file is", "for x in np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1])) # radius def", "self.n = len(self.geom.get_params()) self.n_all_params = len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2]) -", "0.175 max_length = 0.8 min_radius = 0.035 max_radius = 0.085", "pos[2] = str(self.get_height() + self.zmin) self.xml.set(\"pos\", ' '.join(pos)) def update_xml(self):", "lfac * (-1.0 + new_params[0] / self.params[0])# + rfac *", "'mujoco_assets/walker2d_test.xml') assert robot.get_params() == params assert robot.get_height() == 1.31 print(robot.get_param_limits())", "geometry types def __init__(self, body, worldbody=False): self.xml = body self.worldbody", "in body.joints: joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'), self.geom, body.geom, pos) joints.update(body.get_joints())", "update_initial_position(self): pos = self.xml.get(\"pos\").split() pos[2] = str(self.get_height() + self.zmin) self.xml.set(\"pos\",", "self.geoms[geom_xml.get('type')](geom_xml) self.joints = [j for j in body.findall('joint') if 'ignore'", "= p.dot(self.axis) * self.axis rfac = p - lfac return", "def get_body_names(self): names = [self.xml.get('name')] for body in self.parts: names", "self.params = [length, radius] self.axis = (self.p2 - self.p1) /", "assert robot.get_params() == params assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names())", ".2 print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8 *", ".6085 print(robot.get_param_limits()) print(robot.get_param_names()) import gym, roboschool env = gym.make(\"RoboschoolHopper-v1\") env.unwrapped.model_xml", "def update_point(self, p, new_params): pass def update_xml(self): pass def update(self,", "self.body.get_volumes() def update(self, params, xml_file=None): if xml_file is None: xml_file", "def __init__(self, geom): self.xml = geom self.params = [] def", "self.xml = geom self.params = [] def get_params(self): return self.params.copy()", "def update(self, new_params): self.set_params(new_params) self.update_xml() def get_smallest_z(self): pass def get_param_limits(self):", "get_param_names(self): pass def get_volume(self): pass class Sphere(Geom): min_radius = .05", "= (self.p2 - self.p1) / length def update_point(self, p, new_params):", "+= body_limits[1] return limits def get_param_names(self): name = self.xml.get('name') param_names", "of legal geometry types def __init__(self, body, worldbody=False): self.xml =", "params, xml_file=None): if xml_file is None: xml_file = self.model_xml self.body.update_params(list(params))", "print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8 * np.array(robot.get_params())) robot.update(params,", "names += body.get_names() return names def get_joints(self): joints = {}", "# radius def set_params(self, new_params): p1 = self.update_point(self.p1, new_params) p2", "for j in body.joints: joints[j.get('name')] = (self.xml.get('name'), body.xml.get('name'), self.geom, body.geom,", "== params assert robot.get_height() == 1.31 print(robot.get_param_limits()) print(robot.get_param_names()) robot =", "body.xml.get('name'), self.geom, body.geom, pos) joints.update(body.get_joints()) return joints def get_volumes(self): volumes", "/ self.params[1]) def update_xml(self): self.xml.set('fromto', ' '.join([str(x) for x in", "params = [.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert", "robot.update(params, 'mujoco_assets/humanoid_test.xml') assert robot.get_params() == params print(robot.get_height()) #assert robot.get_height() ==", "pos])) def set_body_positions(self, new_params): for i, pos in enumerate(self.part_positions): self.part_positions[i]", "body,pos in zip(self.parts, self.part_positions): for j in body.joints: joints[j.get('name')] =", "self.joint_positions[i] = self.geom.update_point(pos, new_params) def update(self, new_params): self.set_body_positions(new_params) self.geom.update(new_params) self.update_xml()", "rgb = env.render('rgb_array') imsave(os.path.join(outdir, '{:05d}.png'.format(i)), rgb) i+=1 sp.call(['ffmpeg', '-r', '60',", "* new_params[0] / self.params[0]) + self.center def update_xml(self): self.xml.set('size', str(self.params[0]))", "remaining_params def get_body_names(self): names = [self.xml.get('name')] for body in self.parts:", "= len(self.geom.get_params()) self.n_all_params = len(self.get_params()) self.zmin = float(self.xml.get(\"pos\").split()[2]) - self.get_height()", "get_smallest_z(self): pass def get_param_limits(self): pass def get_param_names(self): pass def get_volume(self):", "[j for j in body.findall('joint') if 'ignore' not in j.get('name')]", "return params def get_param_limits(self): limits = self.geom.get_param_limits() for body in", "+ rfac * (new_params[1] / self.params[1]) def update_xml(self): self.xml.set('fromto', '", "[.2, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params() ==", "self.geom, body.geom, pos) joints.update(body.get_joints()) return joints def get_volumes(self): volumes =", "'xml_vid' os.makedirs(outdir, exist_ok=True) i = 0 for _ in range(10):", "not in j.get('name')] self.parts = [Body(b) for b in body.findall('body')]", "'-i', os.path.join(outdir, '%05d.png'), '-vcodec', 'libx264', '-pix_fmt', 'yuv420p', os.path.join(outdir, 'out.mp4')]) env.close()", "geoms = {'sphere': Sphere, 'capsule': Capsule} # dictionary of legal", "new_params) # update only after computing p1, p2 self.p1 =", "self.body.update_params(list(params)) self.tree.write(xml_file) if __name__ == '__main__': robot = MuJoCoXmlRobot('mujoco_assets/hopper.xml') params", "= body self.worldbody = worldbody geom_xml = body.find('geom') # assume", "self.part_positions[i] = self.geom.update_point(pos, new_params) for i, pos in enumerate(self.joint_positions): self.joint_positions[i]", "for j in self.joints: v1 = self.geom.get_volume() v2 = sum([b.geom.get_volume()", "return self.body.get_param_limits() def get_param_names(self): return self.body.get_param_names() def get_height(self): return self.body.get_height()", "self.geom.update_point(pos, new_params) for i, pos in enumerate(self.joint_positions): self.joint_positions[i] = self.geom.update_point(pos,", "else: return remaining_params def get_body_names(self): names = [self.xml.get('name')] for body", "= self.geom.update_point(pos, new_params) for i, pos in enumerate(self.joint_positions): self.joint_positions[i] =", "pos = [j.get('pos') for j in self.joints] self.joint_positions = [np.array([float(x)", ".2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06, .2,.06,.2,.06,.4,.06] robot.update(params, 'mujoco_assets/ant_test.xml') assert robot.get_params() == params assert", "for body in self.parts: param_names += body.get_param_names() return param_names def", "in self.xml.get('fromto').split()] self.p1 = np.array(fromto[:3]) self.p2 = np.array(fromto[3:]) length =", "body.find('geom') # assume only one geometry per body self.geom =", "zip(self.parts, self.part_positions): max_height = max(max_height, body.get_height() - pos[2]) return max_height", "[] def get_params(self): return self.params.copy() def set_params(self, new_params): self.params =", "update_xml(self): self.xml.set('fromto', ' '.join([str(x) for x in np.concatenate([self.p1, self.p2])])) self.xml.set('size',", "(-1.0 + new_params[0] / self.params[0])# + rfac * (new_params[1] /", "= 'xml_vid' os.makedirs(outdir, exist_ok=True) i = 0 for _ in", "print(robot.get_param_limits()) print(robot.get_param_names()) robot = MuJoCoXmlRobot('mujoco_assets/humanoid.xml') params = list(.8 * np.array(robot.get_params()))", "self.params[1] def get_param_limits(self): return [[self.min_length, self.min_radius], [self.max_length, self.max_radius]] def get_param_names(self):", "np.concatenate([self.p1, self.p2])])) self.xml.set('size', str(self.params[1])) # radius def set_params(self, new_params): p1", "float(self.xml.get('size')) self.params = [length, radius] self.axis = (self.p2 - self.p1)", "def update(self, params, xml_file=None): if xml_file is None: xml_file =", "np.array(fromto[3:]) length = np.sqrt(np.sum((self.p2 - self.p1) ** 2)) radius =", "= worldbody geom_xml = body.find('geom') # assume only one geometry", "float(self.xml.get(\"pos\").split()[2]) - self.get_height() def get_height(self): max_height = -self.geom.get_smallest_z() for body,", "return min(self.p1[2], self.p2[2]) - self.params[1] def get_param_limits(self): return [[self.min_length, self.min_radius],", "get_params(self): params = self.geom.get_params() for body in self.parts: params +=", "pass def get_param_limits(self): pass def get_param_names(self): pass def get_volume(self): pass", "= {} if len(self.joints) > 0: for j in self.joints:" ]
[ "Route Executes ''' pass def load_user(self, request): ''' Load user", "import Auth class LoadUserMiddleware: ''' Middleware class which loads the", "Auth class LoadUserMiddleware: ''' Middleware class which loads the current", "''' Load User Middleware''' from masonite.facades.Auth import Auth class LoadUserMiddleware:", "return self.request def after(self): ''' Run This Middleware After The", "This Middleware After The Route Executes ''' pass def load_user(self,", "class which loads the current user into the request '''", "__init__(self, Request): ''' Inject Any Dependencies From The Service Container", "self.load_user(self.request) return self.request def after(self): ''' Run This Middleware After", "current user into the request ''' def __init__(self, Request): '''", "before(self): ''' Run This Middleware Before The Route Executes '''", "Middleware After The Route Executes ''' pass def load_user(self, request):", "The Service Container ''' self.request = Request def before(self): '''", "User Middleware''' from masonite.facades.Auth import Auth class LoadUserMiddleware: ''' Middleware", "Middleware class which loads the current user into the request", "From The Service Container ''' self.request = Request def before(self):", "Load User Middleware''' from masonite.facades.Auth import Auth class LoadUserMiddleware: '''", "def after(self): ''' Run This Middleware After The Route Executes", "Run This Middleware After The Route Executes ''' pass def", "user into the request ''' def __init__(self, Request): ''' Inject", "from masonite.facades.Auth import Auth class LoadUserMiddleware: ''' Middleware class which", "''' Middleware class which loads the current user into the", "into the request ''' def __init__(self, Request): ''' Inject Any", "The Route Executes ''' pass def load_user(self, request): ''' Load", "Run This Middleware Before The Route Executes ''' self.load_user(self.request) return", "which loads the current user into the request ''' def", "masonite.facades.Auth import Auth class LoadUserMiddleware: ''' Middleware class which loads", "Dependencies From The Service Container ''' self.request = Request def", "''' def __init__(self, Request): ''' Inject Any Dependencies From The", "Inject Any Dependencies From The Service Container ''' self.request =", "Executes ''' pass def load_user(self, request): ''' Load user into", "Service Container ''' self.request = Request def before(self): ''' Run", "def before(self): ''' Run This Middleware Before The Route Executes", "Container ''' self.request = Request def before(self): ''' Run This", "<filename>app/http/middleware/LoadUserMiddleware.py ''' Load User Middleware''' from masonite.facades.Auth import Auth class", "load_user(self, request): ''' Load user into the request ''' request.set_user(Auth(request).user())", "def load_user(self, request): ''' Load user into the request '''", "After The Route Executes ''' pass def load_user(self, request): '''", "''' Run This Middleware Before The Route Executes ''' self.load_user(self.request)", "class LoadUserMiddleware: ''' Middleware class which loads the current user", "The Route Executes ''' self.load_user(self.request) return self.request def after(self): '''", "the request ''' def __init__(self, Request): ''' Inject Any Dependencies", "''' pass def load_user(self, request): ''' Load user into the", "Request def before(self): ''' Run This Middleware Before The Route", "Before The Route Executes ''' self.load_user(self.request) return self.request def after(self):", "= Request def before(self): ''' Run This Middleware Before The", "self.request def after(self): ''' Run This Middleware After The Route", "after(self): ''' Run This Middleware After The Route Executes '''", "''' self.load_user(self.request) return self.request def after(self): ''' Run This Middleware", "def __init__(self, Request): ''' Inject Any Dependencies From The Service", "This Middleware Before The Route Executes ''' self.load_user(self.request) return self.request", "Executes ''' self.load_user(self.request) return self.request def after(self): ''' Run This", "''' Run This Middleware After The Route Executes ''' pass", "LoadUserMiddleware: ''' Middleware class which loads the current user into", "Request): ''' Inject Any Dependencies From The Service Container '''", "''' Inject Any Dependencies From The Service Container ''' self.request", "Middleware Before The Route Executes ''' self.load_user(self.request) return self.request def", "request ''' def __init__(self, Request): ''' Inject Any Dependencies From", "Route Executes ''' self.load_user(self.request) return self.request def after(self): ''' Run", "Middleware''' from masonite.facades.Auth import Auth class LoadUserMiddleware: ''' Middleware class", "Any Dependencies From The Service Container ''' self.request = Request", "pass def load_user(self, request): ''' Load user into the request", "''' self.request = Request def before(self): ''' Run This Middleware", "the current user into the request ''' def __init__(self, Request):", "self.request = Request def before(self): ''' Run This Middleware Before", "loads the current user into the request ''' def __init__(self," ]
[ "Player2\", team=\"blue\") player3 = fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2,", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches", "team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1,", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request(", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True)", "fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2,", "when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self):", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input,", "Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)}) when(self.db).get(any).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(any, times=0)", "900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel,", "self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "not found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\",", "from merciful_elo_limit import * class MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin() setup_cvars({", "}) setup_game_in_progress() self.plugin = merciful_elo_limit() self.reply_channel = mocked_channel() self.plugin.database =", "799)}) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func) patch(time.sleep,", "900), (player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any)", "assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123, 455]", "Player2.*is below.*, but has.*8.*application matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 =", "elo in player_elos: ratings[player.steam_id] = {gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"] =", "unittest from mockito import * from mockito.matchers import * from", "from redis import Redis from merciful_elo_limit import * class MercifulEloLimitTests(unittest.TestCase):", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))", "player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\")", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) self.plugin.announced_player_elos = [456] patch(minqlx.next_frame,", "{} for player, elo in player_elos: ratings[player.steam_id] = {gametype: {'elo':", "\"Fake Player3\", team=\"red\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 799),", "test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 =", "assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "player2, player3) self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)})", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db,", "minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake", "self.setup_balance_ratings({(player1, 900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id:", "self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player", "import unittest from mockito import * from mockito.matchers import *", "> 0: gametype = self.plugin.game.type_short ratings = {} for player,", "patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill", "assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self):", "= [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None)", "player3 = fake_player(789, \"Fake Player3\", team=\"blue\") connected_players(player, player1, player2, player3)", "but has.*8.*application matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123, \"Fake", "test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self):", "fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)})", "int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has", "player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_start_with_no_balance_plugin(self): player1", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None)", "class MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\",", "players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids =", "fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"red\")", "1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL )", "when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda", "= None if len(player_elos) > 0: gametype = self.plugin.game.type_short ratings", "= mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123, 455]", "minqlx_plugin_test import * import logging import unittest from mockito import", "verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123, \"Fake", "ratings}) def setup_no_balance_plugin(self): if \"balance\" in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def", "player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request(", "when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any) def", "warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1", "[123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1 =", "matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches", "minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\"))", "self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel() player = fake_player(666, \"Cmd using", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1 =", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123, \"Fake", "when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo))", "= self.plugin.game.type_short ratings = {} for player, elo in player_elos:", "801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application", "merciful_elo_limit() self.reply_channel = mocked_channel() self.plugin.database = Redis self.db = mock(Redis)", "\\(elo: 799\\):.*7.*application matches \" \"left\")) def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL =", "{player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self): setup_no_game()", "self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game()", "CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any,", "<reponame>mgaertne/minqlx-plugin-tests from minqlx_plugin_test import * import logging import unittest from", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) patch(minqlx.next_frame, lambda func:", "player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123,", "patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*,", "Redis from merciful_elo_limit import * class MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin()", "using Player\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "player = fake_player(666, \"Cmd using Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)}) when(self.db).get(any).thenReturn(None)", "any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func: func) when(self.db).delete(any).thenReturn(None)", "player2) self.setup_balance_ratings({(player1, 900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca',", "verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any) def", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\",", "test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger)", "= fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900),", "(player2, 799)}) self.plugin.announced_player_elos = [456] patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread,", "plugin not found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game() player1 = fake_player(123, \"Fake", "def tearDown(self): unstub() def setup_balance_ratings(self, player_elos): gametype = None if", "{connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([])", "mock({'ratings': ratings}) def setup_no_balance_plugin(self): if \"balance\" in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"]", "player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1 =", "application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "= merciful_elo_limit() self.reply_channel = mocked_channel() self.plugin.database = Redis self.db =", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input)", "self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123, \"Fake Player1\",", "fake_player(456, \"Fake Player2\", team=\"blue\") connecting_player = fake_player(789, \"Connecting Player\") connected_players(player1,", "801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1", "team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id)", "team=\"blue\") connected_players(player, player1, player2, player3) self.setup_balance_ratings({(player, 1400), (player1, 801), (player2,", "verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123, \"Fake", "func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3],", "(player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self):", "(player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel)", "mocked_channel() self.plugin.database = Redis self.db = mock(Redis) self.plugin._db_instance = self.db", "\"Fake Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") player3", "import * from mockito.matchers import * from hamcrest import *", "verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "minqlx.CHAT_CHANNEL = mocked_channel() player = fake_player(666, \"Cmd using Player\") player1", "self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({})", "verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL )", "player = fake_player(666, \"Cmd using Player\") player1 = fake_player(123, \"Fake", "900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None)", "test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids,", "'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123, \"Fake", "verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "matches \" \"left\")) def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel def", "def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "(player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db,", "fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 1200)})", "int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches", "Player\") connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)})", "def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def", "(player2, 1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL", "(player2, 799)}) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func)", "def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) def", "\"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1,", "when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub() def setup_balance_ratings(self, player_elos): gametype = None", "left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1 =", "test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666, \"Cmd using Player\") player1 = fake_player(123,", "799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"],", "using Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)}) when(self.db).get(any).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(any,", "team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"red\") connected_players(player1, player2, player3)", "10 application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123, \"Fake Player1\",", "any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123, \"Fake Player1\",", "self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game() player1", "verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) verify(player3,", "self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def", "self.plugin.game.type_short ratings = {} for player, elo in player_elos: ratings[player.steam_id]", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\",", "below.*, but has.*8.*application matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123,", "def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "\"qlx_owner\": \"42\" }) setup_game_in_progress() self.plugin = merciful_elo_limit() self.reply_channel = mocked_channel()", "is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"],", "func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is", "verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123, \"Fake", "fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Speccing Player\", team=\"spectator\")", "\"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def", "mock(Plugin) mybalance_plugin.exceptions = [player.steam_id for player in players] self.plugin._loaded_plugins[\"mybalance\"] =", "MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\":", "900), (player2, 799)}) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func:", "player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\")", "1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Fake", "when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\")", "self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func) patch(time.sleep,", "matches.*\")) verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123,", "setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self):", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False)", "= fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2,", "self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings}) def setup_no_balance_plugin(self): if \"balance\" in self.plugin._loaded_plugins:", "any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)", "assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\")", "test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "(player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self):", "ratings[player.steam_id] = {gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings}) def", "def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1", "\"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123,", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\",", "def setup_exception_list(self, players): mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions = [player.steam_id for", "any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any,", "matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2", "\"Connecting Player\") connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player,", "(player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL", "(player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def", "Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL)", "\"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"blue\") connected_players(player,", "(player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL)", "left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "= mocked_channel() self.plugin.database = Redis self.db = mock(Redis) self.plugin._db_instance =", "verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) patch(minqlx.next_frame, lambda", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True)", "verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\",", "mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not found.*\")) def", "unstub() def setup_balance_ratings(self, player_elos): gametype = None if len(player_elos) >", "player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self): setup_no_game() player1 =", "minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\"))", "(player2, 1200), (player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'},", "* from mockito.matchers import * from hamcrest import * from", "when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of", "self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "matches \" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel()", "found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3,", "(player2, 799), (player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread,", ") def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda", "self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))", "matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches left.*\"))", "Player2\", team=\"blue\") connected_players(player1, player2) mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin()", "assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL,", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) patch(minqlx.next_frame, lambda func: func)", "\\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo:", "self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123, \"Fake Player1\",", "test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda", "10 application matches.*\")) verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1", "player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application", "times=0).add_request(any, any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any,", "801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1", "when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1", "verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "plugin not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666, \"Cmd using", "799)}) self.plugin.announced_player_elos = [456] patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda", "test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player =", "setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\":", "from mockito.matchers import * from hamcrest import * from redis", "player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None)", "Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"blue\") connected_players(player, player1,", "mock(Redis) self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub() def setup_balance_ratings(self,", "Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2)", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True)", "player3) self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id:", "test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False)", "player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456, \"Fake", "verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123, \"Fake", "connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3])", ") def test_callback_ratings_with_no_game_running(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos,", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) self.plugin.announced_player_elos = [456]", "self.plugin.callback_ratings, CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self): setup_no_game() player1 = fake_player(123, \"Fake", "900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))", "func) patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\")", "when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1", "def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "self.reply_channel = mocked_channel() self.plugin.database = Redis self.db = mock(Redis) self.plugin._db_instance", "verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)", "= fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900),", "assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application matches left.*\"), times=0) def", "player2) mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance", "player3) self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\")", "\" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel() player", "player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread,", "warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) verify(player3, times=0).center_print(any) verify(player3,", "\"balance\" in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players): mybalance_plugin =", "fake_player(789, \"Connecting Player\") connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1, 900), (player2, 1200),", "player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) self.plugin.announced_player_elos = [456] patch(minqlx.next_frame, lambda", "test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_start_with_no_balance_plugin(self):", "team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)", "connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)}) self.plugin.handle_round_countdown(4)", "func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2,", "when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 =", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) mocked_logger =", "self.db = mock(Redis) self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub()", "(player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda", "minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel() player = fake_player(666, \"Cmd using Player\")", "self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123,", "verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "from mockito import * from mockito.matchers import * from hamcrest", "lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill", "verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\",", "left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 =", "when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 =", "any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "0: gametype = self.plugin.game.type_short ratings = {} for player, elo", "lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but", "Player\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches", "times=0).add_request(any, any, any) def test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123, \"Fake Player1\",", "logging import unittest from mockito import * from mockito.matchers import", "hamcrest import * from redis import Redis from merciful_elo_limit import", "assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1", "setup_exception_list(self, players): mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions = [player.steam_id for player", "when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game()", "lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2],", "'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 =", "minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self):", "(player1, 801), (player2, 799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None)", "import * from redis import Redis from merciful_elo_limit import *", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123,", "connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def", "matches left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\",", "= [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players()", "when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123, \"Fake", "test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666, \"Cmd using Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)})", "connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([]))", "'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self): setup_no_game() player1", "verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self):", "player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame,", "verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123,", "def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "merciful_elo_limit import * class MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\":", "self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players): mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions = [player.steam_id", "*args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)", "from hamcrest import * from redis import Redis from merciful_elo_limit", "player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application matches left.*\"),", "10 application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123, \"Fake Player1\",", "self.plugin.database = Redis self.db = mock(Redis) self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\")", "* from redis import Redis from merciful_elo_limit import * class", "799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self):", "player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1", "spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame,", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\")", "CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\",", "when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123,", "has 8 application matches left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 =", "self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10", "(player2, 799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player,", "when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123,", "import Redis from merciful_elo_limit import * class MercifulEloLimitTests(unittest.TestCase): def setUp(self):", "(connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def", "but has 8 application matches left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1", "player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1", "None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill", "when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application", "not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666, \"Cmd using Player\")", "mocked_channel() player = fake_player(666, \"Cmd using Player\") player1 = fake_player(123,", "\"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\"))", "when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1", "Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL", "= fake_player(666, \"Cmd using Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)}) when(self.db).get(any).thenReturn(None) self.plugin.cmd_mercis(player,", "900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func: func)", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\")", "Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any,", "900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id))", "self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of", "matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches", "799), (player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))", "verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self):", "(player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db,", "in player_elos: ratings[player.steam_id] = {gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings':", "\"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\" }) setup_game_in_progress() self.plugin", "test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin", "799), (player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda", "(player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings,", "fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2,", "when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 =", "self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "(player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self):", "self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))", "minqlx.CHAT_CHANNEL = original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666, \"Cmd using", "self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\",", "mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any,", "fake_player(666, \"Cmd using Player\") player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "[\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches", "\"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\" }) setup_game_in_progress() self.plugin =", "connected_players(player1, player2) mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger,", "{gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings}) def setup_no_balance_plugin(self): if", "\\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo:", "900), (player2, 1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings,", "application matches left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake", "self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\"))", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123,", "= original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666, \"Cmd using Player\")", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) self.plugin.announced_player_elos", "\"30\", \"qlx_owner\": \"42\" }) setup_game_in_progress() self.plugin = merciful_elo_limit() self.reply_channel =", "self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123, \"Fake", "fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"blue\")", "= fake_player(789, \"Fake Player3\", team=\"blue\") connected_players(player, player1, player2, player3) self.setup_balance_ratings({(player,", "= fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1)", "any, any) def test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not found.*\")) def test_handle_round_countdown_with_no_game(self):", "when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123,", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id:", "900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def", "verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123,", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None)", "799\\):.*7.*application matches \" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL =", "self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake", "= mocked_channel() player = fake_player(666, \"Cmd using Player\") player1 =", "\"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel() player =", "import * from hamcrest import * from redis import Redis", "matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel,", "times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake", "600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id))", "\"42\" }) setup_game_in_progress() self.plugin = merciful_elo_limit() self.reply_channel = mocked_channel() self.plugin.database", "reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666,", "any, any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func:", "test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\"))", "patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1,", "799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any)", "self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub() def setup_balance_ratings(self, player_elos):", "self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL )", "(player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func:", "self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\")", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1", "self.plugin.callback_ratings, CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any,", "self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123, \"Fake", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 =", "when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill", "verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\",", "verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\")) def", "test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger)", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1", "test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "= [player.steam_id for player in players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 = fake_player(123,", "= fake_player(456, \"Fake Player2\", team=\"blue\") connecting_player = fake_player(789, \"Connecting Player\")", "\"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123, \"Fake Player1\",", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application", "self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123, \"Fake", "self.plugin.announced_player_elos = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self):", "connecting_player) self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id:", "900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id))", "for player in players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players()", "[456] patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func) patch(time.sleep,", "ratings = {} for player, elo in player_elos: ratings[player.steam_id] =", "team=\"red\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)})", "= fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\",", "setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\")", "times=0).delete(any) verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake", "original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666, \"Cmd using Player\") connected_players(player)", "has.*8.*application matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123, \"Fake Player1\",", "(player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def", "verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({})", ") def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)", "[player.steam_id for player in players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self):", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake", "self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application matches", "lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*,", "when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123, \"Fake", "verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1", "team=\"blue\") player3 = fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3)", "455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos", "func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL)", "minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 =", "def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "8 application matches left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123,", "players): mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions = [player.steam_id for player in", "455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123,", "mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not", "patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL) verify(player2,", "times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self):", "self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 =", "application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill", "Player2\", team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(3)", "any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123, \"Fake", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1", "600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func)", "\"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db,", "799\\):.*7.*application matches \" \"left\")) def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel", "def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "team=\"blue\") connected_players(player1, player2) mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5)", "\"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\"))", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Speccing", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None)", "def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel() player = fake_player(666,", "self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 =", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self):", "{'elo': elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings}) def setup_no_balance_plugin(self): if \"balance\"", "times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "= mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not found.*\"))", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\")", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None)", "= {gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings}) def setup_no_balance_plugin(self):", "connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self):", "\"Fake Player2\", team=\"blue\") connecting_player = fake_player(789, \"Connecting Player\") connected_players(player1, player2,", "player3 = fake_player(789, \"Fake Player3\", team=\"red\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1,", "connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self):", "connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([]))", "self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_start_with_no_balance_plugin(self): player1 =", "test_callback_ratings_with_no_game_running(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "= self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub() def setup_balance_ratings(self, player_elos): gametype", "Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2", "any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin()", "def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "\" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \"", "player3 = fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({})", "self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players): mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None)", "799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1", "fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any,", "verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666,", "in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players): mybalance_plugin = mock(Plugin)", "def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance", "player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches left.*\")) def", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123, \"Fake", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2)", "(player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def", "None if len(player_elos) > 0: gametype = self.plugin.game.type_short ratings =", "minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\",", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1,", "= fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([],", "player3 = fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1,", "\"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 1200),", "(player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self):", "def test_handle_round_countdown_with_no_game(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "def setup_no_balance_plugin(self): if \"balance\" in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self,", "Player2\", team=\"blue\") connecting_player = fake_player(789, \"Connecting Player\") connected_players(player1, player2, connecting_player)", "self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "lambda int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches", "times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self):", "Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self):", "\"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\" }) setup_game_in_progress()", "player_elos): gametype = None if len(player_elos) > 0: gametype =", "test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "1400), (player1, 801), (player2, 799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\")", "player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self):", "self.plugin = merciful_elo_limit() self.reply_channel = mocked_channel() self.plugin.database = Redis self.db", "= fake_player(789, \"Fake Player3\", team=\"red\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900),", "minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8 application matches left.*\"), times=0)", "when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake", "Player3\", team=\"blue\") connected_players(player, player1, player2, player3) self.setup_balance_ratings({(player, 1400), (player1, 801),", "def test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func: func)", "assert_that(self.plugin.tracked_player_sids, has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is", "\" \"left\")) def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self):", "below.*, but has 8 application matches left.*\"), times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self):", "func) patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(None)", "= mock(Redis) self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub() def", "{player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1", "fake_player(666, \"Cmd using Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)}) when(self.db).get(any).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"],", "Redis self.db = mock(Redis) self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self):", "= mock({'ratings': ratings}) def setup_no_balance_plugin(self): if \"balance\" in self.plugin._loaded_plugins: del", "\"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any,", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda", "player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\")", "matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def reset_chat_channel(self, original_chat_channel):", "1200), (player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'}, self.plugin.callback_ratings,", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) self.plugin.announced_player_elos = [456] patch(minqlx.next_frame, lambda func:", "patch(minqlx.next_frame, lambda func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any,", "player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application", "\"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\"", "self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10", "when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db, times=0).incr(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)) def test_handle_round_start_starts_tracking_for_low_elo_player(self):", "tearDown(self): unstub() def setup_balance_ratings(self, player_elos): gametype = None if len(player_elos)", "times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self):", "test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self):", "self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger)", "None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\"))", "Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123, \"Fake", "Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any)", "player1, player2, player3) self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799), (player3,", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123,", "mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\"))", "spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\")) def", "verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches", "\"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\" }) setup_game_in_progress() self.plugin = merciful_elo_limit()", "self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True)", "def test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "func: func) patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda int: None)", "\"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\" }) setup_game_in_progress() self.plugin = merciful_elo_limit() self.reply_channel", "player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids,", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None)", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None)", "= {} for player, elo in player_elos: ratings[player.steam_id] = {gametype:", "lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2],", "warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1", "= fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"],", "mockito import * from mockito.matchers import * from hamcrest import", "= [456] patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func: func)", "func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2, player3], minqlx.CHAT_CHANNEL)", "player2, player3], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10", "func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))", "test_handle_round_start_increases_application_games_for_untracked_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "(player2, 799), (player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "setup_balance_ratings(self, player_elos): gametype = None if len(player_elos) > 0: gametype", "when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def", "lambda func: func) patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda int:", "has_item(player2.steam_id)) def test_handle_round_start_resets_above_games_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "= mock(Plugin) mybalance_plugin.exceptions = [player.steam_id for player in players] self.plugin._loaded_plugins[\"mybalance\"]", "int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\"))", "player, elo in player_elos: ratings[player.steam_id] = {gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"]", "def test_handle_map_change_fetches_elos_of_connected_players(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo:", "self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False)", "setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\",", "Player3\", team=\"red\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3,", "None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application", "application matches.*\")) verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 =", "\"Cmd using Player\") connected_players(player) self.setup_balance_ratings({(player, 1400)}) when(self.db).get(any).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.CHAT_CHANNEL)", "setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\":", "fake_player(789, \"Speccing Player\", team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL)", "[\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches", "when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player(self): player1 =", "setup_game_in_progress() self.plugin = merciful_elo_limit() self.reply_channel = mocked_channel() self.plugin.database = Redis", "when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of", "connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player)", "mockito.matchers import * from hamcrest import * from redis import", "player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1", "elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings}) def setup_no_balance_plugin(self): if \"balance\" in", "None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Player.*is below.*, but has 8", "assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel,", "fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)})", "lambda func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any)", "times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "= fake_player(789, \"Connecting Player\") connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1, 900), (player2,", "any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connecting_player = fake_player(789, \"Connecting", "from minqlx_plugin_test import * import logging import unittest from mockito", "times=0).add_request(any, any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123, \"Fake Player1\",", "player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1", "900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def", "900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL,", "mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123, 455] self.plugin.handle_map_change(\"campgrounds\",", "when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application", "team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(3) when(self.db).delete(any).thenReturn(None)", "team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789,", "if \"balance\" in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players): mybalance_plugin", "original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666, \"Cmd", "self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_with_unsupported_game_type(self): setup_game_in_progress(\"unsupported\") player1 = fake_player(123,", "times=0).center_print(any) verify(player3, times=0).tell(any) def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123, \"Fake Player1\",", "801)}) when(self.db).get(any).thenReturn(\"11\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self):", "self.plugin.fetch_elos_of_players([]) verify(mocked_logger).warning(matches(\"Balance plugin not found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game() player1 =", "\"left\")) def reset_chat_channel(self, original_chat_channel): minqlx.CHAT_CHANNEL = original_chat_channel def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player", "self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {connecting_player.steam_id: 'ca'},", "team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def", "= mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not", "team=\"blue\") connecting_player = fake_player(789, \"Connecting Player\") connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1,", "self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player =", "verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123,", "def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "def test_callback_ratings_with_no_game_running(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id))", "team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def", "player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any,", "fake_player(789, \"Fake Player3\", team=\"blue\") connected_players(player, player1, player2, player3) self.setup_balance_ratings({(player, 1400),", "= fake_player(456, \"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Speccing Player\",", "team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) mocked_logger", "\"Fake Player3\", team=\"blue\") connected_players(player, player1, player2, player3) self.setup_balance_ratings({(player, 1400), (player1,", "\\(elo: 799\\):.*7.*application matches \" \"left\")) def test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL", "self.plugin.tracked_player_sids = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self):", "\"Fake Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1,", "'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"],", "* from hamcrest import * from redis import Redis from", "\"Cmd using Player\") player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900),", "left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) verify(player3, times=0).center_print(any) verify(player3, times=0).tell(any)", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any,", "def setup_balance_ratings(self, player_elos): gametype = None if len(player_elos) > 0:", "setup_no_balance_plugin(self): if \"balance\" in self.plugin._loaded_plugins: del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players):", "times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) verify(player3, times=0).center_print(any)", "\" \"left,.*6.*matches above.*\")) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \"", "for player, elo in player_elos: ratings[player.steam_id] = {gametype: {'elo': elo}}", "900), (player2, 799)}) self.plugin.announced_player_elos = [456] patch(minqlx.next_frame, lambda func: func)", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger)", "is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123, 455] self.plugin.handle_map_change(\"campgrounds\",", "None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*8.*matches left.*\")) verify(player2).tell(matches(\".*Skill", "found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666, \"Cmd using Player\") player1", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.plugin.tracked_player_sids.append(player2.steam_id) self.setup_balance_ratings({(player1, 900), (player2, 799)})", "Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connecting_player =", "lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2],", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None)", "def test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") player3 =", "900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\", \"ca\") verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id: 'ca'},", "self.plugin.handle_round_start(1) verify(self.db, times=0).delete(any) verify(self.db, times=0).delete(any) def test_handle_round_start_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") player1 =", "verify(mocked_logger).warning(matches(\"Balance plugin not found.*\")) def test_handle_round_countdown_with_no_game(self): setup_no_game() player1 = fake_player(123,", "def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "patch(minqlx.PlayerInfo, lambda *args: mock(spec=minqlx.PlayerInfo)) patch(minqlx.next_frame, lambda func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1,", "def test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "connecting_player = fake_player(789, \"Connecting Player\") connected_players(player1, player2, connecting_player) self.setup_balance_ratings({(player1, 900),", "team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"blue\") connected_players(player, player1, player2,", "connected_players(player, player1, player2, player3) self.setup_balance_ratings({(player, 1400), (player1, 801), (player2, 799),", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any)", "lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2,", "test_handle_round_countdown_fetches_elos_of_players_in_teams(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "def test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666, \"Cmd using Player\") player1 =", "self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger =", "Warning.*qlstats.*below.*800.*10.*of 10 application matches.*\")) def test_callback_ratings_bans_low_elo_players_that_used_up_their_application_games(self): player1 = fake_player(123, \"Fake", "fake_player(789, \"Fake Player3\", team=\"red\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2,", "\"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\", \"qlx_mercifulelo_daysbanned\": \"30\", \"qlx_owner\": \"42\" })", "self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \"", "gametype = self.plugin.game.type_short ratings = {} for player, elo in", "self.plugin.announced_player_elos = [456] patch(minqlx.next_frame, lambda func: func) patch(minqlx.thread, lambda func:", "atleast=1).warning(matches(\"Balance plugin not found.*\")) def test_cmd_mercis_shows_currently_connected_merciful_players(self): player = fake_player(666, \"Cmd", "def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\")", "test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "patch(minqlx.thread, lambda func: func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1,", "self.plugin.callback_ratings, CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123, \"Fake Player1\",", "assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def reset_chat_channel(self,", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({}) self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any,", "player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1)", "801), (player2, 799), (player3, 900)}) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player1.steam_id)).thenReturn(\"2\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)).thenReturn(\"3\") when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None)", "when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but has.*8.*application matches", "import * import logging import unittest from mockito import *", "matches left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "test_cmd_mercis_replies_to_main_cbannel_instead_of_team_chat(self): self.addCleanup(self.reset_chat_channel, minqlx.CHAT_CHANNEL) minqlx.CHAT_CHANNEL = mocked_channel() player = fake_player(666, \"Cmd", "len(player_elos) > 0: gametype = self.plugin.game.type_short ratings = {} for", "def setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\": \"10\", \"qlx_mercifulelo_abovegames\": \"10\",", "self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([])", "self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) assert_that(self.plugin.tracked_player_sids,", "self.db when(self.db).__getitem__(any).thenReturn(\"42\") def tearDown(self): unstub() def setup_balance_ratings(self, player_elos): gametype =", "self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.announced_player_elos =", "900), (player2, 1200), (player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca', player2.steam_id:", "= Redis self.db = mock(Redis) self.plugin._db_instance = self.db when(self.db).__getitem__(any).thenReturn(\"42\") def", "verify(player2).tell(matches(\".*Skill Warning.*qlstats.*below.*800.*8.*of 10 application matches.*\")) def test_callback_ratings_announces_information_to_other_players(self): player1 = fake_player(123,", "test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None)", "when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_starts_tracking_of_above_elo_players_for_application_games_player(self): player1 =", "801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application", "= fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\",", "mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions = [player.steam_id for player in players]", "fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\")", "mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.handle_round_start(5) verify(mocked_logger, atleast=1).warning(matches(\"Balance plugin", "int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake Player2.*is below.*, but", "above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player2 \\(elo: 799\\):.*7.*application matches \" \"left\")) def", "900), (player2, 801)}) when(self.db).get(any).thenReturn(\"1\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def", "def test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "import logging import unittest from mockito import * from mockito.matchers", "team=\"spectator\") connected_players(player1, player2, player3) self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)})", "= fake_player(666, \"Cmd using Player\") player1 = fake_player(123, \"Fake Player1\",", "if len(player_elos) > 0: gametype = self.plugin.game.type_short ratings = {}", "self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) patch(minqlx.next_frame, lambda func:", "\"Fake Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"red\") connected_players(player1,", "any) def test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "def test_handle_round_start_removes_minelo_db_entries_for_above_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) self.plugin.announced_player_elos =", "verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(True) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123,", "Player2\", team=\"blue\") player3 = fake_player(789, \"Fake Player3\", team=\"red\") connected_players(player1, player2,", "test_handle_round_countdown_with_no_game(self): setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "test_handle_round_start_starts_tracking_for_low_elo_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None) patch(minqlx.PlayerInfo, lambda *args:", "* import logging import unittest from mockito import * from", "mybalance_plugin.exceptions = [player.steam_id for player in players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin", "def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "CHAT_CHANNEL ) def test_handle_player_connect_fetches_elo_of_connecting_player(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None) when(self.db).exists(any).thenReturn(False) when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) def", "left.*\")) def test_callback_ratings_announces_information_to_other_players_just_once_per_connect(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).delete(\"minqlx:players:{}:minelo:freegames\".format(player2.steam_id)) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_skips_already_tracked_player(self): player1 = fake_player(123, \"Fake", "setup_no_game() player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 = fake_player(456,", "del self.plugin._loaded_plugins[\"balance\"] def setup_exception_list(self, players): mybalance_plugin = mock(Plugin) mybalance_plugin.exceptions =", "times=0) def test_callback_ratings_makes_exception_for_player_in_exception_list(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2", "900), (player2, 799)}) when(self.db).get(any).thenReturn(\"11\") spy2(minqlx.COMMANDS.handle_input) when2(minqlx.COMMANDS.handle_input, any, any, any).thenReturn(None) patch(minqlx.PlayerInfo,", "team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({})", "any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger) self.setup_no_balance_plugin() self.plugin.fetch_elos_of_players([])", "self.setup_balance_ratings([]) self.plugin.announced_player_elos = [123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.announced_player_elos, is_([])) def", "when(self.db).get(\"minqlx:players:{}:minelo:abovegames\".format(player1.steam_id)).thenReturn(\"6\") when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player.steam_id)).thenReturn(None) when(self.db).get(\"minqlx:players:{}:minelo:freegames\".format(player3.steam_id)).thenReturn(None) self.plugin.cmd_mercis(player, [\"!mercis\"], minqlx.BLUE_TEAM_CHAT_CHANNEL) assert_channel_was_replied(minqlx.CHAT_CHANNEL, matches(\"Fake Player1 \\(elo:", "times=0).add_request(any, any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger = mock(spec=logging.Logger) spy2(minqlx.get_logger) when(minqlx).get_logger(self.plugin).thenReturn(mocked_logger)", "func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(\"2\") self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) assert_plugin_sent_to_console(matches(\"Fake", "func) patch(time.sleep, lambda int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2,", "player_elos: ratings[player.steam_id] = {gametype: {'elo': elo}} self.plugin._loaded_plugins[\"balance\"] = mock({'ratings': ratings})", "\"Fake Player1\", team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connecting_player", "= fake_player(456, \"Fake Player2\", team=\"blue\") connected_players(player1, player2) mocked_logger = mock(spec=logging.Logger)", "def test_cmd_mercis_shows_no_mercis_if_no_player_using_their_application_matches(self): player = fake_player(666, \"Cmd using Player\") connected_players(player) self.setup_balance_ratings({(player,", "* class MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\", \"qlx_mercifulelo_applicationgames\":", "func: func) when(self.db).delete(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(minqlx.COMMANDS).handle_input(any, any, any) verify(self.db).delete(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id))", "redis import Redis from merciful_elo_limit import * class MercifulEloLimitTests(unittest.TestCase): def", "def test_fetch_elos_of_players_with_no_game_setup(self): setup_no_game() self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def", "self.plugin.cmd_mercis(player, [\"!mercis\"], self.reply_channel) assert_channel_was_replied(self.reply_channel, matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \"", "'ca'}, self.plugin.callback_ratings, CHAT_CHANNEL ) def test_callback_ratings_with_no_game_running(self): setup_no_game() player1 = fake_player(123,", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 1200)}) self.plugin.handle_map_change(\"thunderstruck\",", "gametype = None if len(player_elos) > 0: gametype = self.plugin.game.type_short", "self.plugin.handle_round_start(2) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_start_with_no_balance_plugin(self): player1 = fake_player(123,", "in players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids", "verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_players_with_unsupported_gametype(self): setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"],", "def test_callback_ratings_warns_low_elo_player_when_application_games_not_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\") player2 =", "player2, connecting_player) self.setup_balance_ratings({(player1, 900), (player2, 1200), (connecting_player, 1542)}) self.plugin.handle_player_connect(connecting_player) verify(self.plugin._loaded_plugins[\"balance\"]).add_request(", "when(self.db).incr(any).thenReturn(None) self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123, \"Fake Player1\",", "matches(\"Fake Player1 \\(elo: 801\\):.*8.*application matches \" \"left,.*6.*matches above.*\")) assert_channel_was_replied(self.reply_channel, matches(\"Fake", "self.setup_balance_ratings({}) self.plugin.callback_ratings([], minqlx.CHAT_CHANNEL) verify(self.db, times=0).get(any) def test_callback_ratings_warns_low_elo_player(self): player1 = fake_player(123,", "player2, player3) self.setup_balance_ratings({}) self.plugin.handle_round_countdown(1) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_handle_round_countdown_fetches_elos_of_players_in_teams(self):", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) when(self.db).get(any).thenReturn(\"3\")", "import * class MercifulEloLimitTests(unittest.TestCase): def setUp(self): setup_plugin() setup_cvars({ \"qlx_mercifulelo_minelo\": \"800\",", "player in players] self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([])", "self.plugin._loaded_plugins[\"mybalance\"] = mybalance_plugin def test_handle_map_change_resets_tracked_player_ids(self): connected_players() self.setup_balance_ratings([]) self.plugin.tracked_player_sids = [123,", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 799)}) patch(minqlx.next_frame,", "[123, 455] self.plugin.handle_map_change(\"campgrounds\", \"ca\") assert_that(self.plugin.tracked_player_sids, is_([])) def test_handle_map_change_resets_announced_player_ids(self): connected_players() self.setup_balance_ratings([])", "int: None) when(self.db).get(any).thenReturn(None) self.plugin.callback_ratings([player1, player2], minqlx.CHAT_CHANNEL) verify(player2, times=12).center_print(matches(\".*Skill warning.*10.*matches left.*\"))", "\"Fake Player2\", team=\"blue\") connected_players(player1, player2) self.setup_balance_ratings({(player1, 900), (player2, 801)}) when(self.db).get(any).thenReturn(\"3\")", "team=\"red\") player2 = fake_player(456, \"Fake Player2\", team=\"blue\") connecting_player = fake_player(789,", "self.plugin.handle_round_start(1) verify(self.db).incr(\"minqlx:players:{}:minelo:abovegames\".format(player2.steam_id)) def test_handle_round_start_increases_above_games_for_application_games_player_with_no_aobve_games_set(self): player1 = fake_player(123, \"Fake Player1\", team=\"red\")", "self.setup_balance_ratings({(player1, 900), (player2, 1200), (player3, 1600)}) self.plugin.handle_round_countdown(4) verify(self.plugin._loaded_plugins[\"balance\"]).add_request( {player1.steam_id: 'ca',", "player3) self.setup_balance_ratings({(player1, 900), (player2, 799), (player3, 600)}) self.setup_exception_list([player3]) when(self.db).get(any).thenReturn(\"3\") when(self.db).delete(any).thenReturn(None)", "setup_game_in_progress(\"unsupported\") self.setup_balance_ratings({}) self.plugin.fetch_elos_of_players([]) verify(self.plugin._loaded_plugins[\"balance\"], times=0).add_request(any, any, any) def test_fetch_elos_of_player_with_no_balance_plugin(self): mocked_logger" ]
[ "SmsSDK(accId, accToken, appId) tid = '1' # 我们发送短信的模板,值 只能是 1", "SmsSDK from celery_tasks.main import app # 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 #", "= SmsSDK(accId, accToken, appId) tid = '1' # 我们发送短信的模板,值 只能是", "任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile, sms_code): accId = '<KEY>' accToken =", "= '1' # 我们发送短信的模板,值 只能是 1 因为我们是测试用户 mobile = '%s'", "# 您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5 分钟内输入 # 9.2. 发送短信 sdk.sendMessage(tid,", "1 因为我们是测试用户 mobile = '%s' % mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号", "任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile, sms_code): accId = '<KEY>'", "tid = '1' # 我们发送短信的模板,值 只能是 1 因为我们是测试用户 mobile =", "10) # ('变量1', '变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5", "def celery_send_sms_code(mobile, sms_code): accId = '<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f' appId", "datas = (sms_code, 10) # ('变量1', '变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2}", "= '<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>' # 9.1.", "# '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code, 10) # ('变量1', '变量2')", "创建荣联云 实例对象 sdk = SmsSDK(accId, accToken, appId) tid = '1'", "'<KEY>' # 9.1. 创建荣联云 实例对象 sdk = SmsSDK(accId, accToken, appId)", "'514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>' # 9.1. 创建荣联云 实例对象 sdk =", "from celery_tasks.main import app # 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。)", "# 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile, sms_code): accId = '<KEY>' accToken", "我们发送短信的模板,值 只能是 1 因为我们是测试用户 mobile = '%s' % mobile #", "= '%s' % mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code,", "= (sms_code, 10) # ('变量1', '变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入", "accToken, appId) tid = '1' # 我们发送短信的模板,值 只能是 1 因为我们是测试用户", "sdk = SmsSDK(accId, accToken, appId) tid = '1' # 我们发送短信的模板,值", "实例对象 sdk = SmsSDK(accId, accToken, appId) tid = '1' #", "% mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code, 10) #", "@app.task def celery_send_sms_code(mobile, sms_code): accId = '<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f'", "mobile = '%s' % mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas =", "accToken = '514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>' # 9.1. 创建荣联云 实例对象", "celery_send_sms_code(mobile, sms_code): accId = '<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f' appId =", "appId) tid = '1' # 我们发送短信的模板,值 只能是 1 因为我们是测试用户 mobile", "= '514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>' # 9.1. 创建荣联云 实例对象 sdk", "# 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile, sms_code): accId =", "accId = '<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>' #", "appId = '<KEY>' # 9.1. 创建荣联云 实例对象 sdk = SmsSDK(accId,", "'手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code, 10) # ('变量1', '变量2') 涉及到模板的变量", "'<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>' # 9.1. 创建荣联云", "分钟内输入 # 您的验证码为666999,请于5 分钟内输入 # 9.2. 发送短信 sdk.sendMessage(tid, mobile, datas)", "('变量1', '变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5 分钟内输入 #", "ronglian_sms_sdk import SmsSDK from celery_tasks.main import app # 写我们的任务(函数) #", "'1' # 我们发送短信的模板,值 只能是 1 因为我们是测试用户 mobile = '%s' %", "app # 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile,", "只能是 1 因为我们是测试用户 mobile = '%s' % mobile # '手机号1,手机号2'", "import app # 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def", "'%s' % mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code, 10)", "sms_code): accId = '<KEY>' accToken = '514a8783b8c2481ebbeb6a814434796f' appId = '<KEY>'", "celery_tasks.main import app # 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task", "# 我们发送短信的模板,值 只能是 1 因为我们是测试用户 mobile = '%s' % mobile", "from ronglian_sms_sdk import SmsSDK from celery_tasks.main import app # 写我们的任务(函数)", "9.1. 创建荣联云 实例对象 sdk = SmsSDK(accId, accToken, appId) tid =", "mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code, 10) # ('变量1',", "(sms_code, 10) # ('变量1', '变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入 #", "您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5 分钟内输入 # 9.2. 发送短信 sdk.sendMessage(tid, mobile,", "因为我们是测试用户 mobile = '%s' % mobile # '手机号1,手机号2' 给哪些手机号发送验证码,只能是测试手机号 datas", "# 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile, sms_code):", "'变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5 分钟内输入 # 9.2.", "# ('变量1', '变量2') 涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5 分钟内输入", "= '<KEY>' # 9.1. 创建荣联云 实例对象 sdk = SmsSDK(accId, accToken,", "涉及到模板的变量 # 您的验证码为{1},请于{2} 分钟内输入 # 您的验证码为666999,请于5 分钟内输入 # 9.2. 发送短信", "给哪些手机号发送验证码,只能是测试手机号 datas = (sms_code, 10) # ('变量1', '变量2') 涉及到模板的变量 #", "写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰 # 任务包的任务需要celery调用自检检查函数。(在main里面写。) @app.task def celery_send_sms_code(mobile, sms_code): accId", "# 9.1. 创建荣联云 实例对象 sdk = SmsSDK(accId, accToken, appId) tid", "import SmsSDK from celery_tasks.main import app # 写我们的任务(函数) # 任务必须要celery的实例对象装饰器task装饰" ]
[ "visibility(self): return self._visibility @visibility.setter def visibility(self, value): self._visibility = value", "has_implementation(self): return self._has_implementation @has_implementation.setter def has_implementation(self, value): self._has_implementation = value", "value @property def params(self): return self._params @params.setter def params(self, value):", "{ \"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel',", "return None def params(region): params_region = view.find_by_selector( 'meta.function.parameters.delphi') param_name_region =", "def params(self, value): self._params = value @property def methodclass(self): return", "value @property def publishedregion(self): return self._publishedregion @publishedregion.setter def publishedregion(self, value):", "self._publishedregion @publishedregion.setter def publishedregion(self, value): self._publishedregion = value class DelphiIdeCommand(sublime_plugin.TextCommand):", "method.methodregion = [r for r in selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname", "@property def methodregion(self): return self._methodregion @methodregion.setter def methodregion(self, value): self._methodregion", "return view.substr(functionnamefiltered[0]) # has_implementation # has_interface # methodname # methodregion", "classregion(self, value): self._classregion = value @property def privateregion(self): return self._privateregion", "method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) # has_implementation # has_interface # methodname #", "n for n in functionname if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) #", "method = MethodDeclaration() selector = view.find_by_selector method.methodregion = [r for", "def methodregion(self, value): self._methodregion = value @property def visibility(self): return", "\"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel', #", "@property def publishedregion(self): return self._publishedregion @publishedregion.setter def publishedregion(self, value): self._publishedregion", "return self._methodregion @methodregion.setter def methodregion(self, value): self._methodregion = value @property", "DelphiIdeCommand(sublime_plugin.TextCommand): # // { \"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\": {\"teste\":", "functionname = view.find_by_selector('entity.name.function') functionnamefiltered = [ n for n in", "value): self._has_interface = value @property def methodname(self): return self._methodname @methodname.setter", "self._visibility = value @property def params(self): return self._params @params.setter def", "x in params_region_filt] return x except: return [] def getFunctionName():", "return [] def getFunctionName(): functionname = view.find_by_selector('entity.name.function') functionnamefiltered = [", "AttributeError: raise NotImplementedError(\"Class `{}` does not implement `{}`\". format(self.__class__.__name__, teste))", "@protectedregion.setter def protectedregion(self, value): self._protectedregion = value @property def publicregion(self):", "sublime_plugin class MethodDeclaration(object): \"\"\"docstring for MethodDeclaration\"\"\" def __init__(self): self._methodclass =", "return self._visibility @visibility.setter def visibility(self, value): self._visibility = value @property", "def publicregion(self): return self._publicregion @publicregion.setter def publicregion(self, value): self._publicregion =", "params_region = view.find_by_selector( 'meta.function.parameters.delphi') param_name_region = view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt =", "value @property def protectedregion(self): return self._protectedregion @protectedregion.setter def protectedregion(self, value):", "try: params_region_filt = params(region) x = [view.substr(x) for x in", "return self._publicregion @publicregion.setter def publicregion(self, value): self._publicregion = value @property", "None def params(region): params_region = view.find_by_selector( 'meta.function.parameters.delphi') param_name_region = view.find_by_selector(", "False self.has_interface = False @property def has_implementation(self): return self._has_implementation @has_implementation.setter", "= value @property def privateregion(self): return self._privateregion @privateregion.setter def privateregion(self,", "s for s in param_name_region if params_region_filt[0].contains(s)] return params_region_filt def", "self._has_interface @has_interface.setter def has_interface(self, value): self._has_interface = value @property def", "= view.sel()[0] cursor_pt = view.sel()[0].begin() if not view.match_selector(cursor_pt, 'function.implementation.delphi'): #", "# view.window().run_command('show_panel', # args={\"panel\": 'output.find_results', \"toggle\": True}) def run(self, edit,", "class DelphiIdeCommand(sublime_plugin.TextCommand): # // { \"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\":", "value @property def has_interface(self): return self._has_interface @has_interface.setter def has_interface(self, value):", "try: method = getattr(self, teste) except AttributeError: raise NotImplementedError(\"Class `{}`", "\"\"\"docstring for ClassDeclaration\"\"\" @property def classname(self): return self._classname @classname.setter def", "format(self.__class__.__name__, teste)) method() def delphimethodnav(self): print('vai doido') def getMethodInformation(self): view", "self._classname @classname.setter def classname(self, value): self._classname = value @property def", "def delphimethodnav(self): print('vai doido') def getMethodInformation(self): view = self.view cursor_region", "view.find_by_selector( 'meta.function.parameters.delphi') param_name_region = view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt = [ s", "@property def classregion(self): return self._classregion @classregion.setter def classregion(self, value): self._classregion", "@property def methodclass(self): return self._methodclass @methodclass.setter def methodclass(self, value): self._methodclass", "def protectedregion(self, value): self._protectedregion = value @property def publicregion(self): return", "getattr(self, teste) except AttributeError: raise NotImplementedError(\"Class `{}` does not implement", "= value @property def classregion(self): return self._classregion @classregion.setter def classregion(self,", "@has_interface.setter def has_interface(self, value): self._has_interface = value @property def methodname(self):", "= view.sel()[0].begin() if not view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit because it", "visibility(self, value): self._visibility = value @property def params(self): return self._params", "params(region) x = [view.substr(x) for x in params_region_filt] return x", "def has_implementation(self): return self._has_implementation @has_implementation.setter def has_implementation(self, value): self._has_implementation =", "value): self._protectedregion = value @property def publicregion(self): return self._publicregion @publicregion.setter", "def methodname(self): return self._methodname @methodname.setter def methodname(self, value): self._methodname =", "return self._privateregion @privateregion.setter def privateregion(self, value): self._privateregion = value @property", "value): self._methodclass = value class ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\" @property", "params(self, value): self._params = value @property def methodclass(self): return self._methodclass", "ClassDeclaration\"\"\" @property def classname(self): return self._classname @classname.setter def classname(self, value):", "x except: return [] def getFunctionName(): functionname = view.find_by_selector('entity.name.function') functionnamefiltered", "methodregion # visibility # params # methodclass method = MethodDeclaration()", "value): self._classregion = value @property def privateregion(self): return self._privateregion @privateregion.setter", "= getFunctionName() method.params = self.paramsFromRegion(method.methodregion[0]) return method def getClassInformation(self): pass", "value @property def privateregion(self): return self._privateregion @privateregion.setter def privateregion(self, value):", "does not implement `{}`\". format(self.__class__.__name__, teste)) method() def delphimethodnav(self): print('vai", "value): self._methodregion = value @property def visibility(self): return self._visibility @visibility.setter", "method = None try: method = getattr(self, teste) except AttributeError:", "teste) method = None try: method = getattr(self, teste) except", "= value @property def protectedregion(self): return self._protectedregion @protectedregion.setter def protectedregion(self,", "doido') def getMethodInformation(self): view = self.view cursor_region = view.sel()[0] cursor_pt", "self._publishedregion = value class DelphiIdeCommand(sublime_plugin.TextCommand): # // { \"keys\": [\"ctrl+shift+x\"],", "return self._has_implementation @has_implementation.setter def has_implementation(self, value): self._has_implementation = value @property", "= None try: method = getattr(self, teste) except AttributeError: raise", "s for s in params_region if region.contains(s)] params_region_filt = [", "publicregion(self): return self._publicregion @publicregion.setter def publicregion(self, value): self._publicregion = value", "for n in functionname if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) # has_implementation", "= value @property def methodregion(self): return self._methodregion @methodregion.setter def methodregion(self,", "self._params = value @property def methodclass(self): return self._methodclass @methodclass.setter def", "run(self, edit, teste): print('teste[0]:%s' % teste) method = None try:", "view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt = [ s for s in params_region", "value @property def publicregion(self): return self._publicregion @publicregion.setter def publicregion(self, value):", "print('vai doido') def getMethodInformation(self): view = self.view cursor_region = view.sel()[0]", "None try: method = getattr(self, teste) except AttributeError: raise NotImplementedError(\"Class", "[ n for n in functionname if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0])", "__init__(self): self._methodclass = None self.has_implementation = False self.has_interface = False", "return self._publishedregion @publishedregion.setter def publishedregion(self, value): self._publishedregion = value class", "@methodclass.setter def methodclass(self, value): self._methodclass = value class ClassDeclaration(object): \"\"\"docstring", "in params_region if region.contains(s)] params_region_filt = [ s for s", "def has_interface(self, value): self._has_interface = value @property def methodname(self): return", "in functionname if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) # has_implementation # has_interface", "# has_interface # methodname # methodregion # visibility # params", "has_interface # methodname # methodregion # visibility # params #", "params(region): params_region = view.find_by_selector( 'meta.function.parameters.delphi') param_name_region = view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt", "methodregion(self, value): self._methodregion = value @property def visibility(self): return self._visibility", "protectedregion(self): return self._protectedregion @protectedregion.setter def protectedregion(self, value): self._protectedregion = value", "raise NotImplementedError(\"Class `{}` does not implement `{}`\". format(self.__class__.__name__, teste)) method()", "def methodclass(self): return self._methodclass @methodclass.setter def methodclass(self, value): self._methodclass =", "return self._params @params.setter def params(self, value): self._params = value @property", "\"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel', # args={\"panel\": 'output.find_results', \"toggle\":", "self._methodclass = value class ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\" @property def", "return self._methodname @methodname.setter def methodname(self, value): self._methodname = value @property", "if not view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit because it is not", "= view.find_by_selector('entity.name.function') functionnamefiltered = [ n for n in functionname", "for s in param_name_region if params_region_filt[0].contains(s)] return params_region_filt def paramsFromRegion(region):", "return self._has_interface @has_interface.setter def has_interface(self, value): self._has_interface = value @property", "value): self._publicregion = value @property def publishedregion(self): return self._publishedregion @publishedregion.setter", "@publishedregion.setter def publishedregion(self, value): self._publishedregion = value class DelphiIdeCommand(sublime_plugin.TextCommand): #", "methodname(self): return self._methodname @methodname.setter def methodname(self, value): self._methodname = value", "value): self._params = value @property def methodclass(self): return self._methodclass @methodclass.setter", "# methodname # methodregion # visibility # params # methodclass", "if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) # has_implementation # has_interface # methodname", "def methodname(self, value): self._methodname = value @property def methodregion(self): return", "x = [view.substr(x) for x in params_region_filt] return x except:", "def has_implementation(self, value): self._has_implementation = value @property def has_interface(self): return", "[ s for s in param_name_region if params_region_filt[0].contains(s)] return params_region_filt", "def classregion(self, value): self._classregion = value @property def privateregion(self): return", "getFunctionName(): functionname = view.find_by_selector('entity.name.function') functionnamefiltered = [ n for n", "@classregion.setter def classregion(self, value): self._classregion = value @property def privateregion(self):", "`{}` does not implement `{}`\". format(self.__class__.__name__, teste)) method() def delphimethodnav(self):", "[view.substr(x) for x in params_region_filt] return x except: return []", "it is not in a method return None def params(region):", "@methodname.setter def methodname(self, value): self._methodname = value @property def methodregion(self):", "= view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt = [ s for s in", "# exit because it is not in a method return", "selector = view.find_by_selector method.methodregion = [r for r in selector('meta.function.delphi')", "[r for r in selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname = getFunctionName()", "teste) except AttributeError: raise NotImplementedError(\"Class `{}` does not implement `{}`\".", "def run(self, edit, teste): print('teste[0]:%s' % teste) method = None", "class MethodDeclaration(object): \"\"\"docstring for MethodDeclaration\"\"\" def __init__(self): self._methodclass = None", "functionnamefiltered = [ n for n in functionname if method.methodregion[0].contains(n)]", "region.contains(s)] params_region_filt = [ s for s in param_name_region if", "= False self.has_interface = False @property def has_implementation(self): return self._has_implementation", "{\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel', # args={\"panel\": 'output.find_results', \"toggle\": True}) def", "value): self._visibility = value @property def params(self): return self._params @params.setter", "methodname # methodregion # visibility # params # methodclass method", "exit because it is not in a method return None", "in selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname = getFunctionName() method.params = self.paramsFromRegion(method.methodregion[0])", "= [ n for n in functionname if method.methodregion[0].contains(n)] return", "def has_interface(self): return self._has_interface @has_interface.setter def has_interface(self, value): self._has_interface =", "value @property def methodclass(self): return self._methodclass @methodclass.setter def methodclass(self, value):", "except AttributeError: raise NotImplementedError(\"Class `{}` does not implement `{}`\". format(self.__class__.__name__,", "if cursor_region.intersects(r)] method.methodname = getFunctionName() method.params = self.paramsFromRegion(method.methodregion[0]) return method", "for s in params_region if region.contains(s)] params_region_filt = [ s", "import sublime_plugin class MethodDeclaration(object): \"\"\"docstring for MethodDeclaration\"\"\" def __init__(self): self._methodclass", "def privateregion(self): return self._privateregion @privateregion.setter def privateregion(self, value): self._privateregion =", "a method return None def params(region): params_region = view.find_by_selector( 'meta.function.parameters.delphi')", "# methodregion # visibility # params # methodclass method =", "NotImplementedError(\"Class `{}` does not implement `{}`\". format(self.__class__.__name__, teste)) method() def", "def getMethodInformation(self): view = self.view cursor_region = view.sel()[0] cursor_pt =", "in a method return None def params(region): params_region = view.find_by_selector(", "self._methodclass @methodclass.setter def methodclass(self, value): self._methodclass = value class ClassDeclaration(object):", "self._has_implementation = value @property def has_interface(self): return self._has_interface @has_interface.setter def", "in param_name_region if params_region_filt[0].contains(s)] return params_region_filt def paramsFromRegion(region): try: params_region_filt", "\"toggle\": True}) def run(self, edit, teste): print('teste[0]:%s' % teste) method", "publishedregion(self, value): self._publishedregion = value class DelphiIdeCommand(sublime_plugin.TextCommand): # // {", "cursor_pt = view.sel()[0].begin() if not view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit because", "\"args\": {\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel', # args={\"panel\": 'output.find_results', \"toggle\": True})", "has_implementation # has_interface # methodname # methodregion # visibility #", "value class ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\" @property def classname(self): return", "args={\"panel\": 'output.find_results', \"toggle\": True}) def run(self, edit, teste): print('teste[0]:%s' %", "cursor_region.intersects(r)] method.methodname = getFunctionName() method.params = self.paramsFromRegion(method.methodregion[0]) return method def", "self.has_interface = False @property def has_implementation(self): return self._has_implementation @has_implementation.setter def", "def methodclass(self, value): self._methodclass = value class ClassDeclaration(object): \"\"\"docstring for", "@classname.setter def classname(self, value): self._classname = value @property def classregion(self):", "view.window().run_command('show_panel', # args={\"panel\": 'output.find_results', \"toggle\": True}) def run(self, edit, teste):", "params_region_filt def paramsFromRegion(region): try: params_region_filt = params(region) x = [view.substr(x)", "s in param_name_region if params_region_filt[0].contains(s)] return params_region_filt def paramsFromRegion(region): try:", "methodname(self, value): self._methodname = value @property def methodregion(self): return self._methodregion", "= None self.has_implementation = False self.has_interface = False @property def", "'meta.function.parameters.delphi') param_name_region = view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt = [ s for", "implement `{}`\". format(self.__class__.__name__, teste)) method() def delphimethodnav(self): print('vai doido') def", "def classname(self, value): self._classname = value @property def classregion(self): return", "None self.has_implementation = False self.has_interface = False @property def has_implementation(self):", "if params_region_filt[0].contains(s)] return params_region_filt def paramsFromRegion(region): try: params_region_filt = params(region)", "\"\"\"docstring for MethodDeclaration\"\"\" def __init__(self): self._methodclass = None self.has_implementation =", "'variable.parameter.function.delphi') params_region_filt = [ s for s in params_region if", "edit, teste): print('teste[0]:%s' % teste) method = None try: method", "value): self._classname = value @property def classregion(self): return self._classregion @classregion.setter", "def params(region): params_region = view.find_by_selector( 'meta.function.parameters.delphi') param_name_region = view.find_by_selector( 'variable.parameter.function.delphi')", "value): self._has_implementation = value @property def has_interface(self): return self._has_interface @has_interface.setter", "def privateregion(self, value): self._privateregion = value @property def protectedregion(self): return", "view.sel()[0] cursor_pt = view.sel()[0].begin() if not view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit", "@property def has_implementation(self): return self._has_implementation @has_implementation.setter def has_implementation(self, value): self._has_implementation", "value @property def methodname(self): return self._methodname @methodname.setter def methodname(self, value):", "value): self._methodname = value @property def methodregion(self): return self._methodregion @methodregion.setter", "@property def visibility(self): return self._visibility @visibility.setter def visibility(self, value): self._visibility", "self._classregion @classregion.setter def classregion(self, value): self._classregion = value @property def", "methodclass(self): return self._methodclass @methodclass.setter def methodclass(self, value): self._methodclass = value", "return self._methodclass @methodclass.setter def methodclass(self, value): self._methodclass = value class", "view = self.view cursor_region = view.sel()[0] cursor_pt = view.sel()[0].begin() if", "not implement `{}`\". format(self.__class__.__name__, teste)) method() def delphimethodnav(self): print('vai doido')", "is not in a method return None def params(region): params_region", "= value @property def params(self): return self._params @params.setter def params(self,", "visibility # params # methodclass method = MethodDeclaration() selector =", "self._methodregion @methodregion.setter def methodregion(self, value): self._methodregion = value @property def", "value @property def visibility(self): return self._visibility @visibility.setter def visibility(self, value):", "= value class ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\" @property def classname(self):", "= value @property def visibility(self): return self._visibility @visibility.setter def visibility(self,", "def visibility(self): return self._visibility @visibility.setter def visibility(self, value): self._visibility =", "self._methodname = value @property def methodregion(self): return self._methodregion @methodregion.setter def", "[] def getFunctionName(): functionname = view.find_by_selector('entity.name.function') functionnamefiltered = [ n", "def paramsFromRegion(region): try: params_region_filt = params(region) x = [view.substr(x) for", "self._has_implementation @has_implementation.setter def has_implementation(self, value): self._has_implementation = value @property def", "MethodDeclaration(object): \"\"\"docstring for MethodDeclaration\"\"\" def __init__(self): self._methodclass = None self.has_implementation", "= value @property def has_interface(self): return self._has_interface @has_interface.setter def has_interface(self,", "= view.find_by_selector method.methodregion = [r for r in selector('meta.function.delphi') if", "def getFunctionName(): functionname = view.find_by_selector('entity.name.function') functionnamefiltered = [ n for", "\"command\": \"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel', # args={\"panel\": 'output.find_results',", "return self._protectedregion @protectedregion.setter def protectedregion(self, value): self._protectedregion = value @property", "paramsFromRegion(region): try: params_region_filt = params(region) x = [view.substr(x) for x", "False @property def has_implementation(self): return self._has_implementation @has_implementation.setter def has_implementation(self, value):", "has_interface(self, value): self._has_interface = value @property def methodname(self): return self._methodname", "classregion(self): return self._classregion @classregion.setter def classregion(self, value): self._classregion = value", "= value @property def publicregion(self): return self._publicregion @publicregion.setter def publicregion(self,", "# methodclass method = MethodDeclaration() selector = view.find_by_selector method.methodregion =", "= [ s for s in params_region if region.contains(s)] params_region_filt", "self._publicregion @publicregion.setter def publicregion(self, value): self._publicregion = value @property def", "@property def classname(self): return self._classname @classname.setter def classname(self, value): self._classname", "except: return [] def getFunctionName(): functionname = view.find_by_selector('entity.name.function') functionnamefiltered =", "def classname(self): return self._classname @classname.setter def classname(self, value): self._classname =", "n in functionname if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) # has_implementation #", "@property def protectedregion(self): return self._protectedregion @protectedregion.setter def protectedregion(self, value): self._protectedregion", "view.find_by_selector('entity.name.function') functionnamefiltered = [ n for n in functionname if", "getMethodInformation(self): view = self.view cursor_region = view.sel()[0] cursor_pt = view.sel()[0].begin()", "self._params @params.setter def params(self, value): self._params = value @property def", "self._methodname @methodname.setter def methodname(self, value): self._methodname = value @property def", "params_region_filt[0].contains(s)] return params_region_filt def paramsFromRegion(region): try: params_region_filt = params(region) x", "value): self._publishedregion = value class DelphiIdeCommand(sublime_plugin.TextCommand): # // { \"keys\":", "return self._classname @classname.setter def classname(self, value): self._classname = value @property", "% teste) method = None try: method = getattr(self, teste)", "print('teste[0]:%s' % teste) method = None try: method = getattr(self,", "@publicregion.setter def publicregion(self, value): self._publicregion = value @property def publishedregion(self):", "not in a method return None def params(region): params_region =", "self._protectedregion @protectedregion.setter def protectedregion(self, value): self._protectedregion = value @property def", "method.methodname = getFunctionName() method.params = self.paramsFromRegion(method.methodregion[0]) return method def getClassInformation(self):", "for x in params_region_filt] return x except: return [] def", "def publishedregion(self, value): self._publishedregion = value class DelphiIdeCommand(sublime_plugin.TextCommand): # //", "method = getattr(self, teste) except AttributeError: raise NotImplementedError(\"Class `{}` does", "self._methodregion = value @property def visibility(self): return self._visibility @visibility.setter def", "@property def has_interface(self): return self._has_interface @has_interface.setter def has_interface(self, value): self._has_interface", "self._methodclass = None self.has_implementation = False self.has_interface = False @property", "= self.view cursor_region = view.sel()[0] cursor_pt = view.sel()[0].begin() if not", "self._classname = value @property def classregion(self): return self._classregion @classregion.setter def", "in params_region_filt] return x except: return [] def getFunctionName(): functionname", "params_region_filt] return x except: return [] def getFunctionName(): functionname =", "self._has_interface = value @property def methodname(self): return self._methodname @methodname.setter def", "value @property def methodregion(self): return self._methodregion @methodregion.setter def methodregion(self, value):", "return params_region_filt def paramsFromRegion(region): try: params_region_filt = params(region) x =", "def methodregion(self): return self._methodregion @methodregion.setter def methodregion(self, value): self._methodregion =", "def protectedregion(self): return self._protectedregion @protectedregion.setter def protectedregion(self, value): self._protectedregion =", "delphimethodnav(self): print('vai doido') def getMethodInformation(self): view = self.view cursor_region =", "def publishedregion(self): return self._publishedregion @publishedregion.setter def publishedregion(self, value): self._publishedregion =", "value @property def classregion(self): return self._classregion @classregion.setter def classregion(self, value):", "self.view cursor_region = view.sel()[0] cursor_pt = view.sel()[0].begin() if not view.match_selector(cursor_pt,", "view.substr(functionnamefiltered[0]) # has_implementation # has_interface # methodname # methodregion #", "self._classregion = value @property def privateregion(self): return self._privateregion @privateregion.setter def", "def publicregion(self, value): self._publicregion = value @property def publishedregion(self): return", "= False @property def has_implementation(self): return self._has_implementation @has_implementation.setter def has_implementation(self,", "'function.implementation.delphi'): # exit because it is not in a method", "selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname = getFunctionName() method.params = self.paramsFromRegion(method.methodregion[0]) return", "value): self._privateregion = value @property def protectedregion(self): return self._protectedregion @protectedregion.setter", "methodclass(self, value): self._methodclass = value class ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\"", "classname(self): return self._classname @classname.setter def classname(self, value): self._classname = value", "self._visibility @visibility.setter def visibility(self, value): self._visibility = value @property def", "= [r for r in selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname =", "params(self): return self._params @params.setter def params(self, value): self._params = value", "cursor_region = view.sel()[0] cursor_pt = view.sel()[0].begin() if not view.match_selector(cursor_pt, 'function.implementation.delphi'):", "# has_implementation # has_interface # methodname # methodregion # visibility", "def visibility(self, value): self._visibility = value @property def params(self): return", "value class DelphiIdeCommand(sublime_plugin.TextCommand): # // { \"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\",", "method return None def params(region): params_region = view.find_by_selector( 'meta.function.parameters.delphi') param_name_region", "@params.setter def params(self, value): self._params = value @property def methodclass(self):", "privateregion(self): return self._privateregion @privateregion.setter def privateregion(self, value): self._privateregion = value", "self.has_implementation = False self.has_interface = False @property def has_implementation(self): return", "classname(self, value): self._classname = value @property def classregion(self): return self._classregion", "def __init__(self): self._methodclass = None self.has_implementation = False self.has_interface =", "r in selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname = getFunctionName() method.params =", "has_implementation(self, value): self._has_implementation = value @property def has_interface(self): return self._has_interface", "= MethodDeclaration() selector = view.find_by_selector method.methodregion = [r for r", "`{}`\". format(self.__class__.__name__, teste)) method() def delphimethodnav(self): print('vai doido') def getMethodInformation(self):", "= value class DelphiIdeCommand(sublime_plugin.TextCommand): # // { \"keys\": [\"ctrl+shift+x\"], \"command\":", "params_region_filt = [ s for s in params_region if region.contains(s)]", "if region.contains(s)] params_region_filt = [ s for s in param_name_region", "@visibility.setter def visibility(self, value): self._visibility = value @property def params(self):", "# // { \"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}}", "has_interface(self): return self._has_interface @has_interface.setter def has_interface(self, value): self._has_interface = value", "method() def delphimethodnav(self): print('vai doido') def getMethodInformation(self): view = self.view", "view.sel()[0].begin() if not view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit because it is", "s in params_region if region.contains(s)] params_region_filt = [ s for", "@has_implementation.setter def has_implementation(self, value): self._has_implementation = value @property def has_interface(self):", "privateregion(self, value): self._privateregion = value @property def protectedregion(self): return self._protectedregion", "True}) def run(self, edit, teste): print('teste[0]:%s' % teste) method =", "def classregion(self): return self._classregion @classregion.setter def classregion(self, value): self._classregion =", "[\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}} # view.window().run_command('show_panel', # args={\"panel\":", "params_region_filt = [ s for s in param_name_region if params_region_filt[0].contains(s)]", "methodclass method = MethodDeclaration() selector = view.find_by_selector method.methodregion = [r", "@property def params(self): return self._params @params.setter def params(self, value): self._params", "view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit because it is not in a", "param_name_region if params_region_filt[0].contains(s)] return params_region_filt def paramsFromRegion(region): try: params_region_filt =", "methodregion(self): return self._methodregion @methodregion.setter def methodregion(self, value): self._methodregion = value", "// { \"keys\": [\"ctrl+shift+x\"], \"command\": \"delphi_ide\", \"args\": {\"teste\": \"delphimethodnav\"}} #", "# params # methodclass method = MethodDeclaration() selector = view.find_by_selector", "= [ s for s in param_name_region if params_region_filt[0].contains(s)] return", "for ClassDeclaration\"\"\" @property def classname(self): return self._classname @classname.setter def classname(self,", "# args={\"panel\": 'output.find_results', \"toggle\": True}) def run(self, edit, teste): print('teste[0]:%s'", "class ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\" @property def classname(self): return self._classname", "return x except: return [] def getFunctionName(): functionname = view.find_by_selector('entity.name.function')", "@methodregion.setter def methodregion(self, value): self._methodregion = value @property def visibility(self):", "MethodDeclaration\"\"\" def __init__(self): self._methodclass = None self.has_implementation = False self.has_interface", "protectedregion(self, value): self._protectedregion = value @property def publicregion(self): return self._publicregion", "\"delphimethodnav\"}} # view.window().run_command('show_panel', # args={\"panel\": 'output.find_results', \"toggle\": True}) def run(self,", "= value @property def publishedregion(self): return self._publishedregion @publishedregion.setter def publishedregion(self,", "MethodDeclaration() selector = view.find_by_selector method.methodregion = [r for r in", "teste)) method() def delphimethodnav(self): print('vai doido') def getMethodInformation(self): view =", "view.find_by_selector method.methodregion = [r for r in selector('meta.function.delphi') if cursor_region.intersects(r)]", "because it is not in a method return None def", "= view.find_by_selector( 'meta.function.parameters.delphi') param_name_region = view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt = [", "params_region_filt = params(region) x = [view.substr(x) for x in params_region_filt]", "params_region if region.contains(s)] params_region_filt = [ s for s in", "self._privateregion = value @property def protectedregion(self): return self._protectedregion @protectedregion.setter def", "return self._classregion @classregion.setter def classregion(self, value): self._classregion = value @property", "@property def methodname(self): return self._methodname @methodname.setter def methodname(self, value): self._methodname", "[ s for s in params_region if region.contains(s)] params_region_filt =", "self._protectedregion = value @property def publicregion(self): return self._publicregion @publicregion.setter def", "params # methodclass method = MethodDeclaration() selector = view.find_by_selector method.methodregion", "= value @property def methodname(self): return self._methodname @methodname.setter def methodname(self,", "param_name_region = view.find_by_selector( 'variable.parameter.function.delphi') params_region_filt = [ s for s", "def params(self): return self._params @params.setter def params(self, value): self._params =", "self._privateregion @privateregion.setter def privateregion(self, value): self._privateregion = value @property def", "'output.find_results', \"toggle\": True}) def run(self, edit, teste): print('teste[0]:%s' % teste)", "ClassDeclaration(object): \"\"\"docstring for ClassDeclaration\"\"\" @property def classname(self): return self._classname @classname.setter", "self._publicregion = value @property def publishedregion(self): return self._publishedregion @publishedregion.setter def", "@property def publicregion(self): return self._publicregion @publicregion.setter def publicregion(self, value): self._publicregion", "teste): print('teste[0]:%s' % teste) method = None try: method =", "# visibility # params # methodclass method = MethodDeclaration() selector", "publishedregion(self): return self._publishedregion @publishedregion.setter def publishedregion(self, value): self._publishedregion = value", "for r in selector('meta.function.delphi') if cursor_region.intersects(r)] method.methodname = getFunctionName() method.params", "not view.match_selector(cursor_pt, 'function.implementation.delphi'): # exit because it is not in", "= value @property def methodclass(self): return self._methodclass @methodclass.setter def methodclass(self,", "@privateregion.setter def privateregion(self, value): self._privateregion = value @property def protectedregion(self):", "= getattr(self, teste) except AttributeError: raise NotImplementedError(\"Class `{}` does not", "= [view.substr(x) for x in params_region_filt] return x except: return", "for MethodDeclaration\"\"\" def __init__(self): self._methodclass = None self.has_implementation = False", "@property def privateregion(self): return self._privateregion @privateregion.setter def privateregion(self, value): self._privateregion", "publicregion(self, value): self._publicregion = value @property def publishedregion(self): return self._publishedregion", "functionname if method.methodregion[0].contains(n)] return view.substr(functionnamefiltered[0]) # has_implementation # has_interface #", "= params(region) x = [view.substr(x) for x in params_region_filt] return" ]
[ "= weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'],", "self).tearDown() def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self): with self.test_session(): #", "tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) process = subprocess.Popen( ['tensorflowjs_converter', '-v'],", "model = _createKerasModel('MergedDenseForCLI', h5_path) model_json = model.to_json() # 2. Convert", "in layer names between different test methods. h5_path: Optional string", "2.0 (the \"License\"); # you may not use this file", "Python API of the pip package.\"\"\" @classmethod def setUpClass(cls): cls.class_tmp_dir", "def _create_hub_module(save_path): \"\"\"Create a TensorFlow Hub module for testing. Args:", "exceed the 4-MB shard size limit. Therefore, there should #", "* root.v2 * x) to_save = root.f.get_concrete_function(input_data) save(root, save_path, to_save)", "'keras', model_json_path, new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load", "os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not run this test from the", "self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter' ],", "'float32', 'shape': [], 'name': 'StatefulPartitionedCall/mul' }] }] # Load the", "= model.to_json() # 2. Convert the HDF5 file to tensorflowjs", "the loaded model with the original one. model2_weight_values = model2.get_weights()", "10) # 1. Create a model for testing. model =", "# avoid picking up source files. if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')):", "the keras saved model to tfjs_layers_model format. layers_model_output_dir = os.path.join(self._tmp_dir,", "self.assertEqual(0, process.returncode) # 3. Convert the tensorflowjs artifacts back to", "weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check the content of the output", "tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json = model_2.to_json() self.assertEqual(model_json,", "model def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for testing.", "self.fail('Do not run this test from the Python source directory.", "License. # ============================================================================== \"\"\"Test the Python API and shell binary", "sharded weight files and their sizes. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir,", "= keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor) output", "'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self): # Use separate tf.Graph and", "tf.compat.v1.Session(): # 6. Load the keras model and check the", "tf.Graph and tf.compat.v1.Session contexts to prevent name collision. with tf.Graph().as_default(),", "def testVersion(self): process = subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout,", "weight_file_sizes[0]) # 5. Convert the sharded tfjs_layers_model back into a", "'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes',", "a model for testing. model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4]))", "sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4])", "'keras_h5', 'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI', h5_path) model_json", "[{ 'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32', 'name': 'w', 'shape': [2,", "= tf.Graph() with graph.as_default(): spec = hub.create_module_spec(double_module_fn) m = hub.Module(spec)", "close to # before. new_model = keras.models.load_model(new_h5_path) new_y = new_model.predict(x)", "Args: name_scope: Name scope to create the model under. This", "def testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "source files. if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not run this", "keras saved model to tfjs_layers_model format. layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers')", "self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tensorflowjs", "= model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras", "= os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI',", "'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0)", "License for the specific language governing permissions and # limitations", "keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model def", "of # the layers should have weight sizes exceeding the", "process.communicate() self.assertEqual(0, process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session(): # 6. Load the", "'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path,", "weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel'", "= [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32', 'name': 'w', 'shape':", "weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ]))", "the tensorflowjs pip package.\"\"\" from __future__ import absolute_import from __future__", "def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from", "import json import os import shutil import subprocess import sys", "process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype':", "4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph = tf.Graph() with", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir ])", "def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "one. None of # the layers should have weight sizes", "the sharded tfjs_layers_model back into a keras h5 file. new_h5_path", "process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) process", "with tf.Graph().as_default(), tf.compat.v1.Session(): # Load the model from saved artifacts.", "h5_path: Optional string path for a HDF5 (.h5) file to", "sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',", "= json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) # Briefly check the weights manifest.", "process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir,", "# Verify that there are two weight groups due to", "stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn( b'The --signature_name", "process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "topology. with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f: json_content = json.load(f)", "file is not being run from the source directory, to", "json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config'])", "# Run the initializer on `w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING],", "os.path.join(self._tmp_dir, 'model_2.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras',", "2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen( [ 'tensorflowjs_converter',", "4-MB shard size # limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def", "self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'],", "= subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate()", "h5 file. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter',", "keras.Input(shape=[8]) input2 = keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1, input2]) y =", "import tempfile import unittest import numpy as np import tensorflow", "tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ])", "4 keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved model", "def testSaveKerasModel(self): with self.test_session(): # First create a toy keras", "'--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ])", "= keras.layers.Concatenate()([input1, input2]) y = keras.layers.Dense(4, activation='softmax')(y) model = keras.Model([input1,", "def testLoadKerasModel(self): # Use separate tf.Graph and tf.compat.v1.Session contexts to", "self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there is only one weight", "= np.random.randn(4, 10) # 1. Run the model.predict(), store the", "'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session(): model", "= _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values = model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session():", "testLoadKerasModel(self): # Use separate tf.Graph and tf.compat.v1.Session contexts to prevent", "for testing. Args: layer_name_prefix: A prefix string for layer names.", "tf.compat.v1.nn.softmax(y) init_op = w.initializer # Create a builder. builder =", "= process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout))", "OF ANY KIND, either express or implied. # See the", "= tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph = tf.Graph() with graph.as_default(): spec", "tensorflowjs artifacts back to HDF5. new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5') process", "See the License for the specific language governing permissions and", "tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly check the model topology. with open(os.path.join(self._tmp_dir,", "y = tf.compat.v1.matmul(x, w) output = tf.compat.v1.nn.softmax(y) init_op = w.initializer", "tf.Graph() with graph.as_default(): spec = hub.create_module_spec(double_module_fn) m = hub.Module(spec) #", "and their sizes. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4)", "to in writing, software # distributed under the License is", "methods. save_path: The directory path in which to save the", "model. \"\"\" # Module function that doubles its input. def", "A prefix string for layer names. This helps avoid clashes", "conversion. sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "or agreed to in writing, software # distributed under the", "weight file and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files = sorted(", "self.test_session(): # First create a toy keras model. model =", "model under. This helps avoid op and variable name clashes", "\"\"\"Create a TensorFlow Hub module for testing. Args: save_path: The", "keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor) output =", "tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use explicit --output_format", "'model.json'), 'rt') as f: json_content = json.load(f) model_json = json_content['modelTopology']", "sharded tfjs_layers_model back into a keras h5 file. new_h5_path =", "keras saved model to tfjs_layers_model format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')", "= new_model.predict(x) self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x", "a SavedModel. model = self._createNestedSequentialModel() y = model.predict(x) weights =", "--signature_name flag is applicable only to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir ]) process.communicate()", "if h5_path: model.save(h5_path) return model def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a", "new HDF5 file and compare with the # original model.", "'--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, layers_model_output_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "compliance with the License. # You may obtain a copy", "# 2. Convert the keras saved model to tfjs format.", "# --split_weights_by_layer behavior. The model is a small one. None", "variables from tensorflow.python.training.tracking import tracking from tensorflow.python.saved_model.save import save import", "topology. with open(os.path.join(self._tmp_dir, 'model.json')) as f: json_content = json.load(f) model_json", "= keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path = os.path.join(self._tmp_dir,", "limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen(", "avoid clashes in layer names between different test methods. h5_path:", "-23.0], [1.0, 4.0]]) w = tf.compat.v1.get_variable('w', shape=[2, 2]) y =", "for model1_weight_value, model2_weight_value in zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) #", "model_json['model_config']['config']) weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) # Briefly check the", "file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer', h5_path, self._tmp_dir ]) process.communicate()", "sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) if __name__ == '__main__': tf.test.main()", "tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph = tf.Graph()", "not use this file except in compliance with the License.", "being run from the source directory, to # avoid picking", "'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "should have weight sizes exceeding the 4-MB shard size #", "# Load the model from saved artifacts. model2 = tfjs.converters.load_keras_model(", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ])", "a toy keras model. model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values", "= model.get_weights() total_weight_bytes = sum(np.size(w) for w in weights) *", "you may not use this file except in compliance with", "self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format',", "self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'dtype':", "# be only one weight file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*'))))", "the model # as a SavedModel. model = self._createNestedSequentialModel() y", "% tfjs.__version__), tf.compat.as_bytes(stdout)) process = subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "= process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(),", "= tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as sess: # Run the initializer", "tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self):", "keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1, input2]) y = keras.layers.Dense(4, activation='softmax')(y) model", "'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate()", "in which to save the model. \"\"\" input_data = constant_op.constant(1.,", "shard size limit. Therefore, there should # be only one", "string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights) #", "tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use incorrect --input_format", "'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there is only one", "}] # Load the saved weights as a JSON string.", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "--split_weights_by_layer behavior. The model is a small one. None of", "model = self._createNestedSequentialModel() y = model.predict(x) weights = model.get_weights() total_weight_bytes", "to # avoid picking up source files. if os.path.isdir( os.path.join(os.path.dirname(__file__),", "Therefore, there should # be only one weight file. self.assertEqual(", "for weight in manifest_item['weights']: weight_name = weight['name'] weight_shapes[weight_name] = weight['shape']", "artifacts. model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) # Compare the loaded", "'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path ]) process.communicate() self.assertEqual(0, process.returncode) with tf.Graph().as_default(),", "self.assertEqual(0, process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session(): # 6. Load the keras", "check the model topology. with open(os.path.join(self._tmp_dir, 'model.json')) as f: json_content", "weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'],", "the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self):", "one, which # does not exceed the 4-MB shard size", "os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir ])", "the model back from the new HDF5 file and compare", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes),", "'tfjs_graph_model', self.tf_saved_model_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{", "tensorflow import keras from tensorflow.python.eager import def_function from tensorflow.python.framework import", "self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check the content of the", "sess: # Run the initializer on `w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess,", "[ 'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode,", "= model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved", "avoid picking up source files. if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do", "def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) #", "model topology. with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f: json_content =", "and weight file and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files =", "_, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self):", "os.path.join(self._tmp_dir, 'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model',", "self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): #", "weights = model.get_weights() total_weight_bytes = sum(np.size(w) for w in weights)", "'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes',", "tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1. Run the model.predict(),", "'rt') as f: json_content = json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'],", "the new HDF5 file and compare with the # original", "this file is not being run from the source directory,", "'float32', 'name': 'w', 'shape': [2, 2]}]}] # Load the saved", "stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s'", "def testInvalidInputFormatRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir,", "'float32' }] }] # Load the saved weights as a", "create a toy keras model. model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir)", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertIn( b'Expected path to", "'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the", "variables.Variable(2.) root.f = def_function.function(lambda x: root.v1 * root.v2 * x)", "to_save) def _create_hub_module(save_path): \"\"\"Create a TensorFlow Hub module for testing.", "= tf.compat.v1.nn.softmax(y) init_op = w.initializer # Create a builder. builder", "with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path) model_2_json = model_2.to_json() self.assertEqual(model_json,", "[tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\": output}) }, assets_collection=None)", "for a HDF5 (.h5) file to save the model in.", "= subprocess.Popen( [ 'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr =", "the model in. Returns: An instance of keras.Model. \"\"\" input_tensor", "sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths'])", "only one weight file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self):", "\"\"\" # Module function that doubles its input. def double_module_fn():", "tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as sess: # Run the initializer on", "'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0)", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model',", "x = np.random.randn(8, 10) # 1. Run the model.predict(), store", "the # original model. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path)", "# the layers should have weight sizes exceeding the 4-MB", "self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) #", "'float32') # Verify that there are two weight groups due", "and compare with the # original model. with tf.Graph().as_default(), tf.compat.v1.Session():", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes', '2',", "output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create a", "keras saved model to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs')", "'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there are two weight", "_createNestedSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return model", "json import os import shutil import subprocess import sys import", "This helps avoid op and variable name clashes between different", "import absolute_import from __future__ import division from __future__ import print_function", "self.assertEqual(weight_file_size, total_weight_bytes // 2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8, 10)", "self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check the content of the output directory.", "# 1. Run the model.predict(), store the result. Then saved", "and variable name clashes between different test methods. save_path: The", "with open(os.path.join(self._tmp_dir, 'model.json')) as f: json_content = json.load(f) model_json =", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ])", "'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32', 'name': 'w', 'shape': [2, 2]}]}]", "file except in compliance with the License. # You may", "tf.Graph().as_default(), tf.compat.v1.Session(): # Load the model from saved artifacts. model2", "tensorflowjs as tfjs def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a Keras model", "layer names between different test methods. h5_path: Optional string path", "is only one weight group due to the default #", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'),", "# Create a builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as", "3. Convert the tfjs_layers_model to another tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir,", "source directory, to # avoid picking up source files. if", "'keras', h5_path, layers_model_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert", "self.assertIn('layers', model_json['model_config']['config']) weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) # Briefly check", "and assert on the equality of the predict # results.", "tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10)", "print_function import glob import json import os import shutil import", "= sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes = [os.path.getsize(f) for", "= os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir,", "]) process.communicate() self.assertEqual(0, process.returncode) # 3. Load the tensorflowjs artifacts", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir", "which to save the model. \"\"\" # Module function that", "to a directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x", "self.assertEqual(0, process.returncode) # 4. Check the model.json and weight file", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'),", "check the weights manifest. weight_shapes = dict() weight_dtypes = dict()", "builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\": output})", "def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self): with self.test_session(): # First", "tf.compat.v1.Session(): x1 = np.random.randn(4, 8) x2 = np.random.randn(4, 10) #", "to point to an HDF5 file, ' b'but it points", "weight sizes exceeding the 4-MB shard size # limit. self.assertEqual(", "model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model def _createNestedSequentialModel(self):", "self.tf_saved_model_v1_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths':", "# 4. Load the model back from the new HDF5", "def _createNestedSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return", "with the original one. model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for", "for testing. model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid'))", "Keras model for testing. Args: layer_name_prefix: A prefix string for", "testInvalidInputFormatRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir", "testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create a toy keras model and save", "KIND, either express or implied. # See the License for", "import glob import json import os import shutil import subprocess", "]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the quantized weight", "return model def _createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8]) input2 = keras.Input(shape=[10])", "'--input_format', 'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3.", "self._createFunctionalModelWithWeights() y = model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert", "model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testVersion(self): process = subprocess.Popen(", "= keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model", "model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly check the model", "[{ 'shape': [2], 'name': 'module/Variable', 'dtype': 'float32' }] }] #", "reflect the uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes // 2) def testConvertTfjsLayersModelToTfjsGraphModel(self):", "Run the initializer on `w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={", "(the \"License\"); # you may not use this file except", "tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import", "and tf.compat.v1.Session contexts to prevent name collision. with tf.Graph().as_default(), tf.compat.v1.Session():", "of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): # 1.", "], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format',", "shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self): with", "'model_2.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir,", "it points to a directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(),", "import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes", "import tracking from tensorflow.python.saved_model.save import save import tensorflow_hub as hub", "open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights) # Check the content of", "clashes between different test methods. save_path: The directory path in", "to_save = root.f.get_concrete_function(input_data) save(root, save_path, to_save) def _create_hub_module(save_path): \"\"\"Create a", "Args: layer_name_prefix: A prefix string for layer names. This helps", "_, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self):", "--input_format value: keras process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras',", "# # Unless required by applicable law or agreed to", "'tensorflowjs_converter', '--input_format', 'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output') ],", "'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert", "and shell binary of the tensorflowjs pip package.\"\"\" from __future__", "size limit. Therefore, there should # be only one weight", "results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1, x2]) self.assertAllClose(y, new_y)", "total_weight_bytes = sum(np.size(w) for w in weights) * 4 keras.experimental.export_saved_model(model,", "Verify that there are two weight groups due to the", "from __future__ import print_function import glob import json import os", "tfjs_layers_model format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit value of", "Name scope to create the model under. This helps avoid", "= np.random.randn(8, 10) # 1. Create a model for testing.", "_createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8]) input2 = keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1,", "as tfjs def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a Keras model for", "use_bias=False, kernel_initializer='ones', name=layer_name_prefix + '2')(dense1) model = keras.models.Model(inputs=[input_tensor], outputs=[output]) if", "'--split_weights_by_layer', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # Briefly check", "b'Expected path to point to an HDF5 file, ' b'but", "to be run on pip install.') self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest,", "'dtype': 'float32', 'shape': [], 'name': 'StatefulPartitionedCall/mul' }] }] # Load", "weights) # Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir,", "file to tensorflowjs format. process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras',", "import numpy as np import tensorflow as tf from tensorflow", "def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def testVersionString(self): self.assertEqual(2,", "implied. # See the License for the specific language governing", "'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'],", "= tf.Graph() with graph.as_default(): with tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0, -23.0],", "name_scope: Name scope to create the model under. This helps", "the optional flag # --split_weights_by_layer behavior. The model is a", "'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert the tfjs model to keras", "the keras saved model to tfjs_layers_model format. tfjs_output_dir = os.path.join(self._tmp_dir,", "self.assertEqual(0, process.returncode) # 3. Convert the tfjs_layers_model to another tfjs_layers_model,", "np.random.randn(8, 10) # 1. Create a model for testing. model", "'name': 'w', 'shape': [2, 2]}]}] # Load the saved weights", "weight_files = sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) if __name__ ==", "model. model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values = model1.get_weights() with", "\"\"\" input_data = constant_op.constant(1., shape=[1]) root = tracking.AutoTrackable() root.v1 =", "os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode,", "tf.compat.v1.Session contexts to prevent name collision. with tf.Graph().as_default(), tf.compat.v1.Session(): #", "__future__ import division from __future__ import print_function import glob import", "tf.Graph() with graph.as_default(): with tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0, -23.0], [1.0,", "cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir)", "tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.'))", "'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate() self.assertEqual(0,", "_, stderr = process.communicate() self.assertIn( b'Expected path to point to", "into a keras h5 file. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process", "graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',", "output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest),", "'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr", "install.') self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def tearDown(self): if os.path.isdir(self._tmp_dir):", "tf.compat.v1.Session(): # First create a toy keras model. model1 =", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "3. Convert the tensorflowjs artifacts back to HDF5. new_h5_path =", "in which to save the model. \"\"\" graph = tf.Graph()", "2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8, 10) # 1. Create", "model. \"\"\" graph = tf.Graph() with graph.as_default(): with tf.compat.v1.name_scope(name_scope): x", "keras model. model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values = model1.get_weights()", "'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights) # Check the content of the", "'tfjs') # Implicit value of --output_format: tfjs_layers_model process = subprocess.Popen([", "def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) #", "assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for", "directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create a toy", "tf.compat.v1.Session(): # Load the model from saved artifacts. model2 =", "0) self.assertIn( b'The --signature_name flag is applicable only to', tf.compat.as_bytes(stderr))", "Unless required by applicable law or agreed to in writing,", "= hub.Module(spec) # Export the module. with tf.compat.v1.Session(graph=graph) as sess:", "tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values = model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session(): # Load", "process.returncode) # 3. Convert the tfjs_layers_model to another tfjs_graph_model. graph_model_dir", "the specific language governing permissions and # limitations under the", "--output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, layers_model_output_dir", "tensorflow as tf from tensorflow import keras from tensorflow.python.eager import", "'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "= np.random.randn(8, 10) # 1. Run the model.predict(), store the", "6. Load the keras model and check the predict() output", "'weights': [{ 'shape': [2], 'name': 'module/Variable', 'dtype': 'float32' }] }]", "Convert the HDF5 file to tensorflowjs format. process = subprocess.Popen([", "self).setUp() self._tmp_dir = tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest,", "= process.communicate() self.assertGreater(process.returncode, 0) self.assertIn( b'The --signature_name flag is applicable", "process.communicate() self.assertEqual(0, process.returncode) # 3. Load the tensorflowjs artifacts as", "Briefly check the model topology. with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as", "'--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4])", "testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy keras", "its size. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size", "model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved model", "_create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self): # Make sure", "'weights': [{ 'dtype': 'float32', 'shape': [], 'name': 'StatefulPartitionedCall/mul' }] }]", "# 4. Check the sharded weight files and their sizes.", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir ]) process.communicate()", "Check the sharded weight files and their sizes. weight_files =", "# before. new_model = keras.models.load_model(new_h5_path) new_y = new_model.predict(x) self.assertAllClose(new_y, y)", "graph.as_default(): with tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]]) w", "weights as a JSON string. output_json = json.load( open(os.path.join(output_dir, 'model.json'),", "Compare the loaded model with the original one. model2_weight_values =", "tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\": output}) }, assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope,", "'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter',", "on the equality of the predict # results. model_prime =", "save the model. \"\"\" graph = tf.Graph() with graph.as_default(): with", "model = keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return model def", "= tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, layers_model_output_dir ]) process.communicate()", "x}, outputs={\"output\": output}) }, assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create", "}] }] # Load the saved weights as a JSON", "model for testing. Args: layer_name_prefix: A prefix string for layer", "sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\":", "= os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert the tfjs model", "os.path.join(self._tmp_dir, 'tfjs') # Use incorrect --input_format value: keras process =", "np.random.randn(8, 10) # 1. Run the model.predict(), store the result.", "'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights", "shard size # limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self):", "# First create a toy keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path", "path to point to an HDF5 file, ' b'but it", "create a toy keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir,", "]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tfjs_layers_model to", "= json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights) # Check the", "def testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', '--signature_name',", "model.predict(x) weights = model.get_weights() total_weight_bytes = sum(np.size(w) for w in", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir,", "before. new_model = keras.models.load_model(new_h5_path) new_y = new_model.predict(x) self.assertAllClose(new_y, y) def", "w.initializer # Create a builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session()", "a HDF5 (.h5) file to save the model in. Returns:", "= model_prime.predict([x1, x2]) self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "sizes. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes =", "unittest import numpy as np import tensorflow as tf from", "# Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*')))", "tf.compat.v1.get_variable('w', shape=[2, 2]) y = tf.compat.v1.matmul(x, w) output = tf.compat.v1.nn.softmax(y)", "], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path',", "'--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "shard size, there ought to be 4 shards after conversion.", "============================================================================== \"\"\"Test the Python API and shell binary of the", "weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel',", "= int(total_weight_bytes * 0.3) # Due to the shard size,", "self.assertEqual(0, process.returncode) # 3. Load the tensorflowjs artifacts as a", "keras from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from", "TensorFlow SavedModel for testing. Args: name_scope: Name scope to create", "tfjs model to keras h5 format. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5')", "dict() weight_dtypes = dict() for manifest_item in weights_manifest: for weight", "'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there are", "limitations under the License. # ============================================================================== \"\"\"Test the Python API", "# Export the module. with tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path,", "'--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr =", "len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format',", "5. Convert the sharded tfjs_layers_model back into a keras h5", "the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir)", "Convert the keras saved model to tfjs format. tfjs_output_dir =", "of --output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path,", "absolute_import from __future__ import division from __future__ import print_function import", "= os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir =", "# Copyright 2018 Google LLC # # Licensed under the", "2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix + '2')(dense1) model = keras.models.Model(inputs=[input_tensor], outputs=[output])", "['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0, process.returncode)", "weight files and their sizes. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin')))", "testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model',", "def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir = tempfile.mkdtemp() def tearDown(self): if", "the uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes // 2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x", "of the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self): process =", "'tfjs_layers_model', '--output_format', 'keras', model_json_path, new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) #", "keras.layers.Input((3, )) dense1 = keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix", "for layer names. This helps avoid clashes in layer names", "process.returncode) # Briefly check the model topology. with open(os.path.join(self._tmp_dir, 'model.json'),", "testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8, 10) # 1. Create a model", "Convert the tfjs_layers_model to another tfjs_layers_model, # with sharded weights.", "'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras',", "x2 = np.random.randn(4, 10) # 1. Run the model.predict(), store", "= subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'),", "self.assertAllClose(model1_weight_value, model2_weight_value) # Check the content of the output directory.", "import variables from tensorflow.python.training.tracking import tracking from tensorflow.python.saved_model.save import save", "'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert", "'group*-*'))) def testInvalidInputFormatRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'nonsensical_format',", "= [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'shape': [2], 'name': 'module/Variable',", "path in which to save the model. \"\"\" graph =", "to save the model in. Returns: An instance of keras.Model.", "You may obtain a copy of the License at #", "def setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir", "directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process =", "new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',", "model to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit", "of the predict # results. model_prime = keras.models.load_model(new_h5_path) new_y =", "= os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit value of --output_format: tfjs_layers_model process", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path ]) process.communicate() self.assertEqual(0,", "model = self._createNestedSequentialModel() y = model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) # 2.", "self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5. Convert the", "# The size of the weight file should reflect the", "tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testVersion(self):", "from tensorflow.python.saved_model.save import save import tensorflow_hub as hub import tensorflowjs", "x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph = tf.Graph() with graph.as_default():", "'--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ]) process.communicate() self.assertEqual(0,", "root.v2 = variables.Variable(2.) root.f = def_function.function(lambda x: root.v1 * root.v2", "activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path = os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) #", "import save import tensorflow_hub as hub import tensorflowjs as tfjs", "= hub.create_module_spec(double_module_fn) m = hub.Module(spec) # Export the module. with", "self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir)", "b'The --signature_name flag is applicable only to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self):", "# results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1, x2]) self.assertAllClose(y,", "manifest_item['weights']: weight_name = weight['name'] weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] = weight['dtype']", "class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir = tempfile.mkdtemp() def", "is close to # before. new_model = keras.models.load_model(new_h5_path) new_y =", "the source directory, to # avoid picking up source files.", "h5_path, layers_model_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the", "file is intended to be run on pip install.') self._tmp_dir", "with tf.Graph().as_default(), tf.compat.v1.Session(): # 6. Load the keras model and", "]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the model.json and", "cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module')", "saved artifacts. model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) # Compare the", "_createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values = model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session(): #", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self):", "keras.layers.Dense(4, activation='softmax')(y) model = keras.Model([input1, input2], y) return model def", "TensorFlow Hub module for testing. Args: save_path: The directory path", "subprocess.Popen( [ 'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate()", "\"\"\" graph = tf.Graph() with graph.as_default(): with tf.compat.v1.name_scope(name_scope): x =", "the original one. model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value,", "activation='softmax')(y) model = keras.Model([input1, input2], y) return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self):", "total_weight_bytes // 2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8, 10) #", "directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process =", "w) output = tf.compat.v1.nn.softmax(y) init_op = w.initializer # Create a", "self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([", "`w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x},", "w in weights) * 4 keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert", "model for testing. model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1,", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ]) process.communicate()", "tfjs_layers_model back into a keras h5 file. new_h5_path = os.path.join(self._tmp_dir,", "results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict(x) self.assertAllClose(y, new_y) def", "of the pip package.\"\"\" @classmethod def setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp()", "'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer',", "tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter' ], stdout=subprocess.PIPE,", "'model.json'))) weight_files = sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) if __name__", "save import tensorflow_hub as hub import tensorflowjs as tfjs def", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "'1')(input_tensor) output = keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix + '2')(dense1)", "'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path", "= keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1, input2]) y = keras.layers.Dense(4, activation='softmax')(y)", "License. # You may obtain a copy of the License", "keras.Model. \"\"\" input_tensor = keras.layers.Input((3, )) dense1 = keras.layers.Dense( 4,", "setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir =", "= tracking.AutoTrackable() root.v1 = variables.Variable(3.) root.v2 = variables.Variable(2.) root.f =", "from tensorflow.python.training.tracking import tracking from tensorflow.python.saved_model.save import save import tensorflow_hub", "self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load the model back and", "file to save the model in. Returns: An instance of", "from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework", "sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes = [os.path.getsize(f) for f", "setUp(self): # Make sure this file is not being run", "4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32')", "self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files = sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) if", "as np import tensorflow as tf from tensorflow import keras", "governing permissions and # limitations under the License. # ==============================================================================", "tf.Graph().as_default(), tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI', h5_path) model_json = model.to_json() #", "import subprocess import sys import tempfile import unittest import numpy", "weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) #", "tfjs.__version__.count('.')) def testSaveKerasModel(self): with self.test_session(): # First create a toy", "cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def", "model is a small one. None of # the layers", "directory path in which to save the model. \"\"\" #", "x) to_save = root.f.get_concrete_function(input_data) save(root, save_path, to_save) def _create_hub_module(save_path): \"\"\"Create", "'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', model_json_path, new_h5_path]) process.communicate() self.assertEqual(0, process.returncode)", "# 3. Convert the tensorflowjs artifacts back to HDF5. new_h5_path", "# 3. Convert the tfjs model to keras h5 format.", "for f in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2])", "source directory. ' 'This file is intended to be run", "saved model to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') #", "_ = process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__),", "input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path = os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) # 2.", "os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir,", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir ]) process.communicate() self.assertEqual(0,", "os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) # 2. Convert the keras saved model", "format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use explicit --output_format value:", "x = tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]]) w = tf.compat.v1.get_variable('w', shape=[2,", "keras h5 format. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([", "[ 'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _,", "'--input_format', 'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # Briefly", "Convert the keras saved model to tfjs_layers_model format. layers_model_output_dir =", "model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model def _createNestedSequentialModel(self): model = keras.Sequential()", "from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.ops", "keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return model def _createFunctionalModelWithWeights(self): input1", "keras process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir, tfjs_output_dir", "'--output_format', 'keras', model_json_path, new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4.", "def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) #", "= model_2.to_json() self.assertEqual(model_json, model_2_json) def testVersion(self): process = subprocess.Popen( ['tensorflowjs_converter',", "self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # Briefly check the model", "\"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\": output}) }, assets_collection=None) builder.save() def", "h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # Briefly check the", "self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def", "= os.path.getsize(weight_files[0]) # The size of the weight file should", "root.v1 = variables.Variable(3.) root.v2 = variables.Variable(2.) root.f = def_function.function(lambda x:", "clashes in layer names between different test methods. h5_path: Optional", "[ 'tensorflowjs_converter', '--input_format', 'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output')", "self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32')", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check", "process.returncode) model_json_path = os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert the", "files. if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not run this test", "_createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid'))", "between different test methods. h5_path: Optional string path for a", "its input. def double_module_fn(): w = tf.Variable([2.0, 4.0]) x =", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "]) process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights':", "the default # non-split_weights_by_layer behavior. The model is a small", "os.path.join(self._tmp_dir, 'model.json')) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testVersion(self): process", "self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertIn(", "self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen( [", "Implicit value of --output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5.", "as an HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5',", "process.returncode) # 4. Check the model.json and weight file and", "output = tf.compat.v1.nn.softmax(y) init_op = w.initializer # Create a builder.", "], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertIn( b'Expected path", "def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy", "language governing permissions and # limitations under the License. #", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path ]) process.communicate()", "tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown()", "tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy keras model. model1", "required by applicable law or agreed to in writing, software", "weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check the content", "and its size. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1)", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "SavedModel for testing. Args: name_scope: Name scope to create the", "'This file is intended to be run on pip install.')", "= os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir", "one. model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value, model2_weight_value in", "there should # be only one weight file. self.assertEqual( 1,", "stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def", "builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as sess: # Run", "due to the default # non-split_weights_by_layer behavior. The model is", "keras model. model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly check", "'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4.", "_createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir", "test methods. save_path: The directory path in which to save", "tfjs_layers_model format. layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit value of", "agreed to in writing, software # distributed under the License", "directory. ' 'This file is intended to be run on", "with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy keras model.", "'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate()", "files and their sizes. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files),", "]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tensorflowjs artifacts", "process.communicate() self.assertEqual(0, process.returncode) # 4. Check the quantized weight file", "distributed under the License is distributed on an \"AS IS\"", "h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer', h5_path, self._tmp_dir", "a builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as sess: #", "ought to be 4 shards after conversion. sharded_model_dir = os.path.join(self._tmp_dir,", "after conversion. sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter',", "run this test from the Python source directory. ' 'This", "'--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights =", "tf.compat.v1.matmul(x, w) output = tf.compat.v1.nn.softmax(y) init_op = w.initializer # Create", "'tfjs_layers') # Implicit value of --output_format: tfjs_layers_model process = subprocess.Popen([", "'--input_format', 'tfjs_layers_model', '--output_format', 'keras', model_json_path, new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path))", "there is only one weight group due to the default", "[4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32')", "str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4.", "in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0])", "def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy", "model2_weight_value in zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) # Check the", "model_2_json) def testVersion(self): process = subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "x = np.random.randn(8, 10) # 1. Create a model for", "size. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size =", "to tfjs_layers_model format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit value", "toy keras model. model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values =", "os.path.join(self._tmp_dir, 'tfjs') # Implicit value of --output_format: tfjs_layers_model process =", "'--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) # 4.", "x2]) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved model", "'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create a toy keras model", "tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self): model =", "Check the quantized weight file and its size. weight_files =", "= keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path: model.save(h5_path) return model def _createTensorFlowSavedModelV1(name_scope,", "the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir)", "'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self): # Use separate", "class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the Python API of the pip", "to another tfjs_layers_model, # with uint16 quantization. weight_shard_size_bytes = int(total_weight_bytes", "[4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self):", "process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs", "model.to_json() # 2. Convert the HDF5 file to tensorflowjs format.", "self.assertEqual(0, process.returncode) # 4. Load the model back from the", "string for layer names. This helps avoid clashes in layer", "= self._createNestedSequentialModel() y = model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert", "The model is a small one. None of # the", "a JSON string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest", "be 4 shards after conversion. sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded') process", "model_json_path = os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert the tfjs", "y = model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the", "signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\": output}) }, assets_collection=None) builder.save()", "HDF5 file and compare with the # original model. with", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', model_json_path, new_h5_path]) process.communicate() self.assertEqual(0,", "--output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir", "from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework", "small one. None of # the layers should have weight", "not exceed the 4-MB shard size limit. Therefore, there should", "an HDF5 file, ' b'but it points to a directory',", "layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit value of --output_format: tfjs_layers_model", "import tensorflowjs as tfjs def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a Keras", "model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) # Compare the loaded model", "model = keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return", "directory, to # avoid picking up source files. if os.path.isdir(", "weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check", "weight_shapes = dict() weight_dtypes = dict() for manifest_item in weights_manifest:", "subprocess import sys import tempfile import unittest import numpy as", "keras.models.load_model(new_h5_path) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1.", "2]) y = tf.compat.v1.matmul(x, w) output = tf.compat.v1.nn.softmax(y) init_op =", "Check the model.json and weight file and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir,", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir", "OR CONDITIONS OF ANY KIND, either express or implied. #", "avoid op and variable name clashes between different test methods.", "activation='relu')) model.add(self._createSimpleSequentialModel()) return model def _createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8]) input2", "format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit value of --output_format:", "[1.0, 4.0]]) w = tf.compat.v1.get_variable('w', shape=[2, 2]) y = tf.compat.v1.matmul(x,", "the License is distributed on an \"AS IS\" BASIS, #", "tensor_spec from tensorflow.python.ops import variables from tensorflow.python.training.tracking import tracking from", "'--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path =", "name=layer_name_prefix + '1')(input_tensor) output = keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir", "len(model2_weight_values)) for model1_weight_value, model2_weight_value in zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value)", "# Use explicit --output_format value: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter',", "the weight file should reflect the uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes", "def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self): model", "process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process = subprocess.Popen(", "uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes // 2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x =", "law or agreed to in writing, software # distributed under", "os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check", "'nonsensical_format', self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate()", "scope to create the model under. This helps avoid op", "as sess: # Run the initializer on `w`. sess.run(init_op) builder.add_meta_graph_and_variables(", "open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f: json_content = json.load(f) model_json =", "model to keras h5 format. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process", "Due to the shard size, there ought to be 4", "os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Reshape([2,", "from tensorflow.python.framework import tensor_spec from tensorflow.python.ops import variables from tensorflow.python.training.tracking", "return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8,", "= tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest,", "keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI',", "tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]]) w = tf.compat.v1.get_variable('w',", "shape=[2, 2]) y = tf.compat.v1.matmul(x, w) output = tf.compat.v1.nn.softmax(y) init_op", "of --output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir,", "tfjs def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a Keras model for testing.", "tfjs_layers_model, # with uint16 quantization. weight_shard_size_bytes = int(total_weight_bytes * 0.3)", "'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr", "= dict() for manifest_item in weights_manifest: for weight in manifest_item['weights']:", "may obtain a copy of the License at # #", "def _createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1,", "@classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self): # Make sure this", "as a SavedModel. model = self._createNestedSequentialModel() y = model.predict(x) keras.experimental.export_saved_model(model,", "// 2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8, 10) # 1.", "a keras.Model instance. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir,", "process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tensorflowjs artifacts back", "y) def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10)", "may not use this file except in compliance with the", "'rt')) weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0] < 3:", "'--input_format', 'keras', h5_path, layers_model_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3.", "'--input_format', 'keras', '--split_weights_by_layer', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "the quantized weight file and its size. weight_files = sorted(", "model_prime.predict(x) self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x1 =", "name=layer_name_prefix + '2')(dense1) model = keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path: model.save(h5_path)", "this file except in compliance with the License. # You", "import division from __future__ import print_function import glob import json", "Convert the sharded tfjs_layers_model back into a keras h5 file.", "model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value, model2_weight_value in zip( model1_weight_values, model2_weight_values):", "self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights'])", "def testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "model # as a SavedModel. model = self._createNestedSequentialModel() y =", "= self._createFunctionalModelWithWeights() y = model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir) # 2.", "2018 Google LLC # # Licensed under the Apache License,", "the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self):", "process.communicate() self.assertGreater(process.returncode, 0) self.assertIn( b'The --signature_name flag is applicable only", "= [os.path.getsize(f) for f in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1])", "import shutil import subprocess import sys import tempfile import unittest", "Make sure this file is not being run from the", "# # Licensed under the Apache License, Version 2.0 (the", "stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn( b'The --signature_name flag is", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "layers_model_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tfjs_layers_model", "from saved artifacts. model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) # Compare", "intended to be run on pip install.') self._tmp_dir = tempfile.mkdtemp()", "'foo.h5'), os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate()", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn( b'The", "4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32')", "only to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process =", "outputs=x*w) graph = tf.Graph() with graph.as_default(): spec = hub.create_module_spec(double_module_fn) m", "subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0,", "the model # as a SavedModel. model = self._createFunctionalModelWithWeights() y", "import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec", "self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'shape':", "[{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'shape': [2], 'name': 'module/Variable', 'dtype':", "names. This helps avoid clashes in layer names between different", "as a SavedModel. model = self._createFunctionalModelWithWeights() y = model.predict([x1, x2])", "= dict() weight_dtypes = dict() for manifest_item in weights_manifest: for", "input2 = keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1, input2]) y = keras.layers.Dense(4,", "self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') #", "= os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir)", "'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir ]) process.communicate() self.assertEqual(0,", "model_json_path, new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load the", "Load the model back from the new HDF5 file and", "as a SavedModel. model = self._createNestedSequentialModel() y = model.predict(x) weights", "'model.json'), new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) # 4. Load the model", "_, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn( b'The --signature_name flag", "or implied. # See the License for the specific language", "toy keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5')", "instance. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json", "# with uint16 quantization. weight_shard_size_bytes = int(total_weight_bytes * 0.3) #", "@classmethod def setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model')", "output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format',", "model_prime.predict([x1, x2]) self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x", "= weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias',", "self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there are two weight groups", "output is close to # before. new_model = keras.models.load_model(new_h5_path) new_y", "the model from saved artifacts. model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json'))", "'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4,", "process = subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ =", "# 6. Load the keras model and check the predict()", "the predict() output is close to # before. new_model =", "]) process.communicate() self.assertEqual(0, process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session(): # 6. Load", "to the default # non-split_weights_by_layer behavior. The model is a", "# limitations under the License. # ============================================================================== \"\"\"Test the Python", "# Briefly check the model topology. with open(os.path.join(self._tmp_dir, 'model.json'), 'rt')", "}, assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel", "graph_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the model.json", "a TensorFlow Hub module for testing. Args: save_path: The directory", "tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for", "testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x1 = np.random.randn(4, 8) x2 =", "directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8,", "model.get_weights() total_weight_bytes = sum(np.size(w) for w in weights) * 4", "with uint16 quantization. weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due", "file. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr))", "self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there are two", "to another tfjs_layers_model, # with sharded weights. weight_shard_size_bytes = int(total_weight_bytes", "subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0,", "are two weight groups due to the optional flag #", "'module/Variable', 'dtype': 'float32' }] }] # Load the saved weights", "for testing. Args: save_path: The directory path in which to", "= tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def", "module for testing. Args: save_path: The directory path in which", "weight_file_size = os.path.getsize(weight_files[0]) # The size of the weight file", "process.returncode) # 4. Check the quantized weight file and its", "weight_file_sizes = [os.path.getsize(f) for f in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0],", "shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Reshape([2, 3],", "Load the tensorflowjs artifacts as a keras.Model instance. with tf.Graph().as_default(),", "The size of the weight file should reflect the uint16", "the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create", "' 'This file is intended to be run on pip", "the model back and assert on the equality of the", "tfjs_layers_model to another tfjs_layers_model, # with uint16 quantization. weight_shard_size_bytes =", "cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def", "new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10)", "tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]]) w = tf.compat.v1.get_variable('w', shape=[2, 2]) y", "JSON string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights)", "self._createNestedSequentialModel() y = model.predict(x) weights = model.get_weights() total_weight_bytes = sum(np.size(w)", "to another tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph') process = subprocess.Popen([", "tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.ops import", "])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'],", "= sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) if __name__ == '__main__':", "self.assertEqual(0, process.returncode) # 3. Convert the tfjs_layers_model to another tfjs_graph_model.", "use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor) output = keras.layers.Dense( 2,", "_createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer', h5_path,", "layer names. This helps avoid clashes in layer names between", "= variables.Variable(3.) root.v2 = variables.Variable(2.) root.f = def_function.function(lambda x: root.v1", "Optional string path for a HDF5 (.h5) file to save", "flag is applicable only to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir =", "between different test methods. save_path: The directory path in which", "one weight file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with", "sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\": x}, outputs={\"output\": output}) },", "= output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths'])", "'--input_format', 'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate() self.assertEqual(0, process.returncode)", "'model.json')) as f: json_content = json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'],", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0,", "# Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*')))", "--output_format value: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format',", "model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path = os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path)", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0,", "API of the pip package.\"\"\" @classmethod def setUpClass(cls): cls.class_tmp_dir =", "= constant_op.constant(1., shape=[1]) root = tracking.AutoTrackable() root.v1 = variables.Variable(3.) root.v2", "Hub module for testing. Args: save_path: The directory path in", "to save the model. \"\"\" input_data = constant_op.constant(1., shape=[1]) root", "under. This helps avoid op and variable name clashes between", "0.3) # Due to the shard size, there ought to", "h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the", "'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2])", "root = tracking.AutoTrackable() root.v1 = variables.Variable(3.) root.v2 = variables.Variable(2.) root.f", "cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a',", "testKerasH5ConversionWithSignatureNameErrors(self): process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', '--signature_name', 'bar',", "model.save(h5_path) return model def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel", "initializer on `w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def(", "[4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify", "super(APIAndShellTest, self).setUp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def", "* 0.3) # Due to the shard size, there ought", "the shard size, there ought to be 4 shards after", "def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create a toy keras model and", "'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', model_json_path,", "name collision. with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy", "tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import", "'--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path ]) process.communicate() self.assertEqual(0, process.returncode) with", "weight_dtypes = dict() for manifest_item in weights_manifest: for weight in", "First create a toy keras model. model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1,", "process.communicate() self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3.", "= self._createNestedSequentialModel() y = model.predict(x) weights = model.get_weights() total_weight_bytes =", "weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due to the shard", "def testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create a toy keras model and", "y = keras.layers.Concatenate()([input1, input2]) y = keras.layers.Dense(4, activation='softmax')(y) model =", "process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) class", "hub.add_signature(inputs=x, outputs=x*w) graph = tf.Graph() with graph.as_default(): spec = hub.create_module_spec(double_module_fn)", "model_2.to_json() self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create a toy", "as tf from tensorflow import keras from tensorflow.python.eager import def_function", "Google LLC # # Licensed under the Apache License, Version", "h5_path: model.save(h5_path) return model def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a TensorFlow", "json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) # Briefly check the weights manifest. weight_shapes", "model to tfjs_layers_model format. layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit", "output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process", "in writing, software # distributed under the License is distributed", "'--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3.", "of the weight file should reflect the uint16 quantization. self.assertEqual(weight_file_size,", "to keras h5 format. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process =", "self.tf_hub_module_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths':", "model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) # Check the content of the output", "model back and assert on the equality of the predict", "h5_path) model_json = model.to_json() # 2. Convert the HDF5 file", "def testMissingInputPathRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "model to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use", "process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def", "w = tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph", "'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "the tensorflowjs artifacts as a keras.Model instance. with tf.Graph().as_default(), tf.compat.v1.Session():", "Load the model from saved artifacts. model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir,", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir, 'model.json')", "License, Version 2.0 (the \"License\"); # you may not use", "= model_2.to_json() self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create a", "that doubles its input. def double_module_fn(): w = tf.Variable([2.0, 4.0])", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "model.json and weight file and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files", "def _createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8]) input2 = keras.Input(shape=[10]) y =", "a Keras model for testing. Args: layer_name_prefix: A prefix string", "init_op = w.initializer # Create a builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path)", "])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'],", "self.assertEqual(len(weight_files), 1) weight_file_size = os.path.getsize(weight_files[0]) # The size of the", "np import tensorflow as tf from tensorflow import keras from", "'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # Briefly check", "group due to the default # non-split_weights_by_layer behavior. The model", "saved the model # as a SavedModel. model = self._createFunctionalModelWithWeights()", "the License for the specific language governing permissions and #", "# 3. Load the tensorflowjs artifacts as a keras.Model instance.", "'--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights =", "super(APIAndShellTest, self).tearDown() def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self): with self.test_session():", "'-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0, process.returncode) self.assertIn(", "testing. Args: name_scope: Name scope to create the model under.", "os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not run this test from the Python", "# with sharded weights. weight_shard_size_bytes = int(total_weight_bytes * 0.3) #", "'tensorflowjs_converter', '--input_format', 'keras', h5_path, layers_model_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "stdout, _ = process.communicate() self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' %", "predict # results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1, x2])", "of the tensorflowjs pip package.\"\"\" from __future__ import absolute_import from", "self._tmp_dir = tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown()", "value of --output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras',", "os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert the tfjs model to", "to create the model under. This helps avoid op and", "as f: json_content = json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict)", "model. \"\"\" input_data = constant_op.constant(1., shape=[1]) root = tracking.AutoTrackable() root.v1", "with graph.as_default(): with tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]])", "_create_hub_module(save_path): \"\"\"Create a TensorFlow Hub module for testing. Args: save_path:", "Convert the tfjs_layers_model to another tfjs_layers_model, # with uint16 quantization.", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "tf.compat.as_bytes(stdout)) process = subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _", "'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ]) process.communicate() self.assertEqual(0,", "Create a builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as sess:", "weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel'", "json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if", "tracking from tensorflow.python.saved_model.save import save import tensorflow_hub as hub import", "to the optional flag # --split_weights_by_layer behavior. The model is", "the keras saved model to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir,", "model.save(h5_path) # 2. Convert the keras saved model to tfjs_layers_model", "its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files = sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files),", "weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5. Convert the sharded tfjs_layers_model back", "cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir", "keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1, x2]) self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with", "package.\"\"\" from __future__ import absolute_import from __future__ import division from", "zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) # Check the content of", "save it as an HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path =", "content of the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self): process", "= w.initializer # Create a builder. builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with", "self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8,", "# distributed under the License is distributed on an \"AS", "self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest,", "sys import tempfile import unittest import numpy as np import", "# Unless required by applicable law or agreed to in", "process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load the model back", "format. layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit value of --output_format:", "tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self): # Make sure this file is", "'shape': [2, 2]}]}] # Load the saved weights as a", "in weights) * 4 keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the", "# 5. Convert the sharded tfjs_layers_model back into a keras", "tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) # Compare the loaded model with the", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "import unittest import numpy as np import tensorflow as tf", "'tfjs') # Use explicit --output_format value: tfjs_layers_model process = subprocess.Popen([", "for w in weights) * 4 keras.experimental.export_saved_model(model, self._tmp_dir) # 2.", "APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the Python API of the pip package.\"\"\"", "hub.create_module_spec(double_module_fn) m = hub.Module(spec) # Export the module. with tf.compat.v1.Session(graph=graph)", "directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter',", "save the model. \"\"\" # Module function that doubles its", "'--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0,", "from the source directory, to # avoid picking up source", "have weight sizes exceeding the 4-MB shard size # limit.", "'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir,", "from __future__ import division from __future__ import print_function import glob", "the Apache License, Version 2.0 (the \"License\"); # you may", "a TensorFlow SavedModel for testing. Args: name_scope: Name scope to", "os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI', h5_path)", "= np.random.randn(4, 8) x2 = np.random.randn(4, 10) # 1. Run", "= json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest =", "to tensorflowjs format. process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path,", "uint16 quantization. weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due to", "'rt')) self.assertEqual(output_json['weightsManifest'], weights) # Check the content of the output", "function that doubles its input. def double_module_fn(): w = tf.Variable([2.0,", "\"\"\"Tests for the Python API of the pip package.\"\"\" @classmethod", "self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check the", "# results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict(x) self.assertAllClose(y, new_y)", "[3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'],", "input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model def _createNestedSequentialModel(self): model =", "the License. # ============================================================================== \"\"\"Test the Python API and shell", "tf.compat.v1.Session() as sess: # Run the initializer on `w`. sess.run(init_op)", "tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use incorrect --input_format value: keras", "self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5. Convert the sharded tfjs_layers_model back into", "file, ' b'but it points to a directory', tf.compat.as_bytes(stderr)) def", "a SavedModel. model = self._createFunctionalModelWithWeights() y = model.predict([x1, x2]) keras.experimental.export_saved_model(model,", "process.communicate() self.assertEqual(0, process.returncode) # 4. Load the model back from", "on `w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\": tf.compat.v1.saved_model.signature_def_utils.predict_signature_def( inputs={\"x\":", "with self.test_session(): # First create a toy keras model. model", "testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1.", "hub.Module(spec) # Export the module. with tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer())", "weight file should reflect the uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes //", "h5 format. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter',", "# limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process =", "= json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights))", "quantization. self.assertEqual(weight_file_size, total_weight_bytes // 2) def testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8,", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr))", "Load the keras model and check the predict() output is", "self.assertEqual(0, process.returncode) # 4. Check the quantized weight file and", "'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{", "with tf.Graph().as_default(), tf.compat.v1.Session(): x1 = np.random.randn(4, 8) x2 = np.random.randn(4,", "tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use explicit --output_format value: tfjs_layers_model", "shutil import subprocess import sys import tempfile import unittest import", "the tfjs model to keras h5 format. new_h5_path = os.path.join(self._tmp_dir,", "'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4,", "= keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix + '2')(dense1) model =", "self._createNestedSequentialModel() y = model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the", "run from the source directory, to # avoid picking up", "exceeding the 4-MB shard size # limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir,", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', model_json_path, new_h5_path]) process.communicate()", "the sharded weight files and their sizes. weight_files = sorted(", "# ============================================================================== \"\"\"Test the Python API and shell binary of", "small one, which # does not exceed the 4-MB shard", "'--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ])", "'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path ]) process.communicate() self.assertEqual(0, process.returncode)", "under the License is distributed on an \"AS IS\" BASIS,", "y = keras.layers.Dense(4, activation='softmax')(y) model = keras.Model([input1, input2], y) return", "process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'dtype': 'float32',", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path ])", "to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use incorrect", "new_y = model_prime.predict(x) self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "groups due to the optional flag # --split_weights_by_layer behavior. The", "model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved", "outputs={\"output\": output}) }, assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a", "= keras.models.load_model(new_h5_path) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): #", "self.assertGreater(process.returncode, 0) self.assertIn( b'The --signature_name flag is applicable only to',", "weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) # Briefly check the weights", "process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir, tfjs_output_dir ],", "3. Load the tensorflowjs artifacts as a keras.Model instance. with", "'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create a toy keras model and save", "activation='sigmoid')) h5_path = os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) # 2. Convert the", "SavedModel. model = self._createNestedSequentialModel() y = model.predict(x) weights = model.get_weights()", "for manifest_item in weights_manifest: for weight in manifest_item['weights']: weight_name =", "store the result. Then saved the model # as a", "model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10)", "self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self): # Use separate tf.Graph and tf.compat.v1.Session", "x: root.v1 * root.v2 * x) to_save = root.f.get_concrete_function(input_data) save(root,", "from __future__ import absolute_import from __future__ import division from __future__", "2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self): #", "[2], 'name': 'module/Variable', 'dtype': 'float32' }] }] # Load the", "output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self): process = subprocess.Popen( [", "process.returncode) # 3. Convert the tensorflowjs artifacts back to HDF5.", "self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32',", "result. Then saved the model # as a SavedModel. model", "of keras.Model. \"\"\" input_tensor = keras.layers.Input((3, )) dense1 = keras.layers.Dense(", "\"\"\"Create a Keras model for testing. Args: layer_name_prefix: A prefix", "a small one, which # does not exceed the 4-MB", "Load the model back and assert on the equality of", "model def _createNestedSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel())", "with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json =", "input1 = keras.Input(shape=[8]) input2 = keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1, input2])", "Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def", "equality of the predict # results. model_prime = keras.models.load_model(new_h5_path) new_y", "keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix + '2')(dense1) model = keras.models.Model(inputs=[input_tensor],", "path in which to save the model. \"\"\" input_data =", "model to tfjs_layers_model format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit", "pip install.') self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def tearDown(self): if", "self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self): with self.test_session(): # First create a", "sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the Python API of the", "which # does not exceed the 4-MB shard size limit.", "[ 'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _,", "'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir)", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate()", "= os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) # 2. Convert the keras saved", "tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json = model_2.to_json()", "the 4-MB shard size limit. Therefore, there should # be", "3], input_shape=[6])) model.add(keras.layers.LSTM(10)) model.add(keras.layers.Dense(1, activation='sigmoid')) return model def _createNestedSequentialModel(self): model", "doubles its input. def double_module_fn(): w = tf.Variable([2.0, 4.0]) x", "to tfjs_layers_model format. layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit value", "model in. Returns: An instance of keras.Model. \"\"\" input_tensor =", "glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes = [os.path.getsize(f) for f in", "subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir,", "ANY KIND, either express or implied. # See the License", "the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self): process = subprocess.Popen(", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer', h5_path, self._tmp_dir ])", "'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there is", "super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir = tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir)", "the License. # You may obtain a copy of the", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate()", "'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size = os.path.getsize(weight_files[0]) # The size of", "compare with the # original model. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2", "permissions and # limitations under the License. # ============================================================================== \"\"\"Test", "= os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format',", "# See the License for the specific language governing permissions", "= [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'dtype': 'float32', 'shape': [],", "HDF5 (.h5) file to save the model in. Returns: An", "for testing. Args: name_scope: Name scope to create the model", "= tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph =", "os.path.join(self._tmp_dir, 'model.json')) # Compare the loaded model with the original", "model and save it as an HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5'))", "model.add(self._createSimpleSequentialModel()) return model def _createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8]) input2 =", "constant_op.constant(1., shape=[1]) root = tracking.AutoTrackable() root.v1 = variables.Variable(3.) root.v2 =", "process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32', 'name':", "check the predict() output is close to # before. new_model", "another tfjs_layers_model, # with sharded weights. weight_shard_size_bytes = int(total_weight_bytes *", "os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr =", "HDF5. new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "_createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for testing. Args: name_scope:", "new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x1 = np.random.randn(4, 8)", "'--input_format', 'keras', self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr =", "self._tmp_dir) # Briefly check the model topology. with open(os.path.join(self._tmp_dir, 'model.json'))", "as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the", "'StatefulPartitionedCall/mul' }] }] # Load the saved weights as a", "and # limitations under the License. # ============================================================================== \"\"\"Test the", "[], 'name': 'StatefulPartitionedCall/mul' }] }] # Load the saved weights", "due to the optional flag # --split_weights_by_layer behavior. The model", "the keras model and check the predict() output is close", "= variables.Variable(2.) root.f = def_function.function(lambda x: root.v1 * root.v2 *", "# Implicit value of --output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter',", "model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create", "1. Create a toy keras model and save it as", "kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor) output = keras.layers.Dense( 2, use_bias=False,", "of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir =", "['group1-shard1of1.bin'], 'weights': [{ 'shape': [2], 'name': 'module/Variable', 'dtype': 'float32' }]", "tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1. Run the", "sharded weights. weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due to", "weight_name = weight['name'] weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual(", "# 3. Convert the tfjs_layers_model to another tfjs_graph_model. graph_model_dir =", "import tensorflow_hub as hub import tensorflowjs as tfjs def _createKerasModel(layer_name_prefix,", "hub import tensorflowjs as tfjs def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "def testConvertTfjsLayersModelToTfjsGraphModel(self): x = np.random.randn(8, 10) # 1. Create a", "np.random.randn(4, 10) # 1. Run the model.predict(), store the result.", "# Make sure this file is not being run from", "# original model. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path) model_2_json", "writing, software # distributed under the License is distributed on", "tfjs_layers_model, # with sharded weights. weight_shard_size_bytes = int(total_weight_bytes * 0.3)", "two weight groups due to the optional flag # --split_weights_by_layer", "JSON string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest =", "process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session(): # 6. Load the keras model", "output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights) # Check", "model. model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly check the", "weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'dtype': 'float32', 'shape':", "tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir =", "= os.path.join(self._tmp_dir, 'tfjs') # Implicit value of --output_format: tfjs_layers_model process", "= sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size = os.path.getsize(weight_files[0]) #", "_createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for testing. Args: name_scope:", "# First create a toy keras model. model1 = _createKerasModel('MergedDense')", "y = model.predict(x) weights = model.get_weights() total_weight_bytes = sum(np.size(w) for", "shape=[1]) root = tracking.AutoTrackable() root.v1 = variables.Variable(3.) root.v2 = variables.Variable(2.)", "'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI', h5_path) model_json =", "glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size = os.path.getsize(weight_files[0]) # The size", "to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([", "the model.predict(), store the result. Then saved the model #", "(.h5) file to save the model in. Returns: An instance", "None of # the layers should have weight sizes exceeding", "'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir)", "tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tfjs_layers_model", "keras.models.load_model(new_h5_path) new_y = new_model.predict(x) self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(),", "The directory path in which to save the model. \"\"\"", "self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the", "= keras.Input(shape=[8]) input2 = keras.Input(shape=[10]) y = keras.layers.Concatenate()([input1, input2]) y", "sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the quantized", "# Due to the shard size, there ought to be", "tf from tensorflow import keras from tensorflow.python.eager import def_function from", "sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size = os.path.getsize(weight_files[0]) # The", "root.v2 * x) to_save = root.f.get_concrete_function(input_data) save(root, save_path, to_save) def", "'shape': [], 'name': 'StatefulPartitionedCall/mul' }] }] # Load the saved", "quantization. weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due to the", "< 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'],", "os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process", "the tfjs_layers_model to another tfjs_layers_model, # with sharded weights. weight_shard_size_bytes", "constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_spec from", "process.communicate() self.assertEqual(0, process.returncode) # 3. Convert the tfjs_layers_model to another", "back to HDF5. new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5') process = subprocess.Popen([", "weight in manifest_item['weights']: weight_name = weight['name'] weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name]", "tensorflow.python.training.tracking import tracking from tensorflow.python.saved_model.save import save import tensorflow_hub as", "under the License. # ============================================================================== \"\"\"Test the Python API and", "def double_module_fn(): w = tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x,", "root.v1 * root.v2 * x) to_save = root.f.get_concrete_function(input_data) save(root, save_path,", "model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create a toy keras model", "json_content = json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict)", "= model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session(): # Load the model from", "the 4-MB shard size # limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*'))))", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', '--split_weights_by_layer', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0,", "stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process", "keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path: model.save(h5_path) return model def _createTensorFlowSavedModelV1(name_scope, save_path):", "keras h5 file. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([", "= process.communicate() self.assertIn( b'Expected path to point to an HDF5", "as a JSON string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt'))", "content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir", "inputs={\"x\": x}, outputs={\"output\": output}) }, assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope, save_path):", "if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def", "save the model in. Returns: An instance of keras.Model. \"\"\"", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir", "to save the model. \"\"\" graph = tf.Graph() with graph.as_default():", "save_path, to_save) def _create_hub_module(save_path): \"\"\"Create a TensorFlow Hub module for", "self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create", "Use explicit --output_format value: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "input. def double_module_fn(): w = tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32)", "and save it as an HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path", "os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session():", "'paths': ['group1-shard1of1.bin'], 'weights': [{ 'dtype': 'float32', 'shape': [], 'name': 'StatefulPartitionedCall/mul'", "sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the Python API", "4. Load the model back and assert on the equality", "self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value, model2_weight_value in zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value,", "= model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value, model2_weight_value in zip( model1_weight_values,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First", "keras.models.load_model(new_h5_path) new_y = model_prime.predict(x) self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(),", "names between different test methods. h5_path: Optional string path for", "%s' % tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp()", "model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest", "[3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'],", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(save_path) with tf.compat.v1.Session() as sess: # Run the", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path])", "len(weights)) if sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else:", "json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest = json_content['weightsManifest']", "with graph.as_default(): spec = hub.create_module_spec(double_module_fn) m = hub.Module(spec) # Export", "tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json)", "'tfjs') # Use incorrect --input_format value: keras process = subprocess.Popen(", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "process.communicate() self.assertIn( b'Expected path to point to an HDF5 file,", "x2]) self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x =", "different test methods. h5_path: Optional string path for a HDF5", "dense1 = keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor)", "value of --output_format: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model',", "separate tf.Graph and tf.compat.v1.Session contexts to prevent name collision. with", "size, there ought to be 4 shards after conversion. sharded_model_dir", "another tfjs_layers_model, # with uint16 quantization. weight_shard_size_bytes = int(total_weight_bytes *", "def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a Keras model for testing. Args:", "def setUp(self): # Make sure this file is not being", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "3. Convert the tfjs_layers_model to another tfjs_layers_model, # with sharded", "content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir", "process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load the model back and assert", "os.path.join(self._tmp_dir, 'tfjs_graph') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model',", "'keras', '--split_weights_by_layer', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # Briefly", "explicit --output_format value: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model',", "'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr", "testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1.", "import keras from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op", "tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a", "specific language governing permissions and # limitations under the License.", "the result. Then saved the model # as a SavedModel.", "= tf.compat.v1.matmul(x, w) output = tf.compat.v1.nn.softmax(y) init_op = w.initializer #", "process.returncode) # 4. Check the sharded weight files and their", "weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5. Convert the sharded", "artifacts back to HDF5. new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5') process =", "output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process", "string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest = output_json['weightsManifest']", "a JSON string. output_json = json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'],", "= os.path.join(self._tmp_dir, 'model_2.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format',", "a keras h5 file. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process =", "tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, layers_model_output_dir ])", "sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'],", "total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5. Convert", "behavior. The model is a small one, which # does", "saved model to tfjs_layers_model format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') #", "tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI', h5_path) model_json = model.to_json() # 2.", "tf.compat.v1.Session(): # First create a toy keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5'))", "# you may not use this file except in compliance", "h5_path=None): \"\"\"Create a Keras model for testing. Args: layer_name_prefix: A", "with tf.compat.v1.Session() as sess: # Run the initializer on `w`.", "m = hub.Module(spec) # Export the module. with tf.compat.v1.Session(graph=graph) as", "x1 = np.random.randn(4, 8) x2 = np.random.randn(4, 10) # 1.", "tfjs_layers_model to another tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph') process =", "self.assertEqual(len(weight_files), 4) weight_file_sizes = [os.path.getsize(f) for f in weight_files] self.assertEqual(sum(weight_file_sizes),", "graph = tf.Graph() with graph.as_default(): with tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0,", "'w', 'shape': [2, 2]}]}] # Load the saved weights as", "binary of the tensorflowjs pip package.\"\"\" from __future__ import absolute_import", "'--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "not being run from the source directory, to # avoid", "'model.json')) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testVersion(self): process =", "there are two weight groups due to the optional flag", "import print_function import glob import json import os import shutil", "* x) to_save = root.f.get_concrete_function(input_data) save(root, save_path, to_save) def _create_hub_module(save_path):", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "the module. with tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class", "sure this file is not being run from the source", "sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the sharded", "4. Check the sharded weight files and their sizes. weight_files", "# Module function that doubles its input. def double_module_fn(): w", "sum(np.size(w) for w in weights) * 4 keras.experimental.export_saved_model(model, self._tmp_dir) #", "= tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir,", "process.returncode) # 4. Load the model back from the new", "self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8,", "self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Load the tensorflowjs", "# 2. Convert the HDF5 file to tensorflowjs format. process", "Module function that doubles its input. def double_module_fn(): w =", "in which to save the model. \"\"\" # Module function", "# non-split_weights_by_layer behavior. The model is a small one, which", "under the Apache License, Version 2.0 (the \"License\"); # you", "tfjs.__version__), tf.compat.as_bytes(stdout)) process = subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout,", "= tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]]) w = tf.compat.v1.get_variable('w', shape=[2, 2])", "tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w) graph = tf.Graph() with graph.as_default(): spec =", "'paths': ['group1-shard1of1.bin'], 'weights': [{ 'shape': [2], 'name': 'module/Variable', 'dtype': 'float32'", "an HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5')", "contexts to prevent name collision. with tf.Graph().as_default(), tf.compat.v1.Session(): # First", "ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir = tempfile.mkdtemp() def tearDown(self):", "helps avoid clashes in layer names between different test methods.", "op and variable name clashes between different test methods. save_path:", "to be 4 shards after conversion. sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded')", "is a small one, which # does not exceed the", "in manifest_item['weights']: weight_name = weight['name'] weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] =", "# Verify that there is only one weight group due", "testMissingInputPathRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _,", "'dtype': 'float32' }] }] # Load the saved weights as", "glob import json import os import shutil import subprocess import", "tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1')", "is applicable only to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir)", "on pip install.') self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def tearDown(self):", "process.returncode) # 3. Convert the tfjs_layers_model to another tfjs_layers_model, #", "['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32', 'name': 'w', 'shape': [2, 2]}]}] #", "= os.path.join(self._tmp_dir, 'tfjs_sharded') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format',", "new_y = new_model.predict(x) self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "the Python source directory. ' 'This file is intended to", "the layers should have weight sizes exceeding the 4-MB shard", "activation='sigmoid')) return model def _createNestedSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10],", "self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) #", "# does not exceed the 4-MB shard size limit. Therefore,", "]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the sharded weight", "the model under. This helps avoid op and variable name", "Convert the tfjs_layers_model to another tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph')", "sizes exceeding the 4-MB shard size # limit. self.assertEqual( 2,", "model. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path) model_2_json = model_2.to_json()", "* 4 keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved", "= keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return model def _createFunctionalModelWithWeights(self):", "'--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _,", "the predict # results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1,", "# Load the saved weights as a JSON string. output_json", "testVersion(self): process = subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _", "'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "[4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32')", "toy keras model and save it as an HDF5 file.", "run on pip install.') self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest, self).setUp() def", "sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the Python", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "model with the original one. model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values))", "= weight['name'] weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())),", "First create a toy keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path =", "' b'but it points to a directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self):", "# 4. Check the model.json and weight file and its", "os.path.join(sharded_model_dir, 'model.json'), new_h5_path ]) process.communicate() self.assertEqual(0, process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session():", "keras model and save it as an HDF5 file. os.makedirs(os.path.join(self._tmp_dir,", "variables.Variable(3.) root.v2 = variables.Variable(2.) root.f = def_function.function(lambda x: root.v1 *", "# 1. Create a model for testing. model = keras.Sequential()", "= sum(np.size(w) for w in weights) * 4 keras.experimental.export_saved_model(model, self._tmp_dir)", "keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras saved model to", "test from the Python source directory. ' 'This file is", "dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list) # Briefly", "+ '2')(dense1) model = keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path: model.save(h5_path) return", "testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy keras", "if sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'],", "model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path = os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) # 2. Convert", "Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def", "def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self): # Make sure this file", "instance of keras.Model. \"\"\" input_tensor = keras.layers.Input((3, )) dense1 =", "4. Load the model back from the new HDF5 file", "# 3. Convert the tfjs_layers_model to another tfjs_layers_model, # with", "keras.layers.Concatenate()([input1, input2]) y = keras.layers.Dense(4, activation='softmax')(y) model = keras.Model([input1, input2],", "= os.path.join(self._tmp_dir, 'tfjs_graph') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format',", "open(os.path.join(self._tmp_dir, 'model.json')) as f: json_content = json.load(f) model_json = json_content['modelTopology']", "os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self): #", "model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path)", "the model topology. with open(os.path.join(self._tmp_dir, 'model.json')) as f: json_content =", "self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): #", "with tf.compat.v1.name_scope(name_scope): x = tf.compat.v1.constant([[37.0, -23.0], [1.0, 4.0]]) w =", "'keras', self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate()", "output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0] < 3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'],", "model topology. with open(os.path.join(self._tmp_dir, 'model.json')) as f: json_content = json.load(f)", "manifest. weight_shapes = dict() weight_dtypes = dict() for manifest_item in", "should # be only one weight file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir,", "tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir = tempfile.mkdtemp()", "tfjs_layers_model to another tfjs_layers_model, # with sharded weights. weight_shard_size_bytes =", "is intended to be run on pip install.') self._tmp_dir =", "[{'dtype': 'float32', 'name': 'w', 'shape': [2, 2]}]}] # Load the", "the model topology. with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f: json_content", "Export the module. with tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess)", "model_json = model.to_json() # 2. Convert the HDF5 file to", "model def _createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8]) input2 = keras.Input(shape=[10]) y", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub',", "layers should have weight sizes exceeding the 4-MB shard size", "'name': 'StatefulPartitionedCall/mul' }] }] # Load the saved weights as", "value: keras process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir,", "self.assertEqual(output_json['weightsManifest'], weights) # Check the content of the output directory.", "sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4])", "self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32')", "y) return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x =", "testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1.", "0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First", "does not exceed the 4-MB shard size limit. Therefore, there", "['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0, process.returncode)", "Apache License, Version 2.0 (the \"License\"); # you may not", "tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter',", "either express or implied. # See the License for the", "testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1.", "save the model. \"\"\" input_data = constant_op.constant(1., shape=[1]) root =", "h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir ])", "tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertIn( b'Expected", "Args: save_path: The directory path in which to save the", "be run on pip install.') self._tmp_dir = tempfile.mkdtemp() super(APIAndShellTest, self).setUp()", "[2, 2]}]}] # Load the saved weights as a JSON", "if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not run this test from", "the content of the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir, 'group*-*'))) def testInvalidInputFormatRaisesError(self):", "'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "w = tf.compat.v1.get_variable('w', shape=[2, 2]) y = tf.compat.v1.matmul(x, w) output", "], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(", "self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self): # Use separate tf.Graph", "'float32') def testLoadKerasModel(self): # Use separate tf.Graph and tf.compat.v1.Session contexts", "np.random.randn(4, 8) x2 = np.random.randn(4, 10) # 1. Run the", "'model.h5') model.save(h5_path) # 2. Convert the keras saved model to", "'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) #", "model = keras.Model([input1, input2], y) return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with", "dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.ops import variables from", "= _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly check the model topology.", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir ]) process.communicate()", "limit. Therefore, there should # be only one weight file.", "= model.predict(x) weights = model.get_weights() total_weight_bytes = sum(np.size(w) for w", "the model. \"\"\" graph = tf.Graph() with graph.as_default(): with tf.compat.v1.name_scope(name_scope):", "= json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers',", "the tfjs_layers_model to another tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph') process", "'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0,", "as hub import tensorflowjs as tfjs def _createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json)", "weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{'dtype': 'float32', 'name': 'w',", ")) dense1 = keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix +", "= os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter',", "self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2]) self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'],", "'--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "self).setUp() def tearDown(self): if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def testVersionString(self):", "directory path in which to save the model. \"\"\" graph", "weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3,", "process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir ],", "in. Returns: An instance of keras.Model. \"\"\" input_tensor = keras.layers.Input((3,", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ])", "'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights", "_createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls):", "toy keras model. model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly", "output}) }, assets_collection=None) builder.save() def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a TensorFlow", "'model.json')) # Compare the loaded model with the original one.", "model = self._createFunctionalModelWithWeights() y = model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir) #", "else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights']) # Check the content of", "string path for a HDF5 (.h5) file to save the", "= keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1, x2]) self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self):", "check the model topology. with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f:", "h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Load the", "process.returncode) # 3. Load the tensorflowjs artifacts as a keras.Model", "os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(APIAndShellTest, self).tearDown() def testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self):", "model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict(x) self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self):", "new_y = model_prime.predict([x1, x2]) self.assertAllClose(y, new_y) def testUsingIncorrectKerasSavedModelRaisesError(self): with tf.Graph().as_default(),", "weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes = [os.path.getsize(f)", "Then saved the model # as a SavedModel. model =", "subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "from the Python source directory. ' 'This file is intended", "this test from the Python source directory. ' 'This file", "saved weights as a JSON string. output_json = json.load( open(os.path.join(output_dir,", "'tfjs_layers_model', '--output_format', 'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) #", "]) process.communicate() self.assertEqual(0, process.returncode) # Briefly check the model topology.", "flag # --split_weights_by_layer behavior. The model is a small one.", "if os.path.isdir(self._tmp_dir): shutil.rmtree(self._tmp_dir) super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self): model = keras.Sequential()", "This helps avoid clashes in layer names between different test", "the weights manifest. weight_shapes = dict() weight_dtypes = dict() for", "_createKerasModel('MergedDenseForCLI', h5_path) model_json = model.to_json() # 2. Convert the HDF5", "3. Convert the tfjs_layers_model to another tfjs_layers_model, # with uint16", "variable name clashes between different test methods. save_path: The directory", "'2')(dense1) model = keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path: model.save(h5_path) return model", "output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir,", "'--output_format', 'tfjs_layers_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path =", "tensorflowjs format. process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir", "'tfjs_graph') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir,", "= keras.layers.Dense(4, activation='softmax')(y) model = keras.Model([input1, input2], y) return model", "import tensor_spec from tensorflow.python.ops import variables from tensorflow.python.training.tracking import tracking", "save_path: The directory path in which to save the model.", "to prevent name collision. with tf.Graph().as_default(), tf.compat.v1.Session(): # First create", "original one. model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value, model2_weight_value", "'keras', os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) # 4. Load", "process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) process = subprocess.Popen(", "process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'shape': [2],", "model_2.to_json() self.assertEqual(model_json, model_2_json) def testVersion(self): process = subprocess.Popen( ['tensorflowjs_converter', '--version'],", "= os.path.join(self._tmp_dir, 'tfjs') # Use incorrect --input_format value: keras process", "stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def", "use this file except in compliance with the License. #", "weights manifest. weight_shapes = dict() weight_dtypes = dict() for manifest_item", "%s' % tfjs.__version__), tf.compat.as_bytes(stdout)) process = subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE,", "artifacts as a keras.Model instance. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 =", "tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit value of --output_format: tfjs_layers_model", "= weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'],", "stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertIn( b'Expected path to point", "# 2. Convert the keras saved model to tfjs_layers_model format.", "self.assertEqual(model_json, model_2_json) def testVersion(self): process = subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE,", "numpy as np import tensorflow as tf from tensorflow import", "original model. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path) model_2_json =", "collision. with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy keras", "HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with", "to HDF5. new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5') process = subprocess.Popen([ 'tensorflowjs_converter',", "tensorflow.python.ops import variables from tensorflow.python.training.tracking import tracking from tensorflow.python.saved_model.save import", "back and assert on the equality of the predict #", "new_model = keras.models.load_model(new_h5_path) new_y = new_model.predict(x) self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self):", "self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self):", "to save the model. \"\"\" # Module function that doubles", "picking up source files. if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not", "'2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4.", "to an HDF5 file, ' b'but it points to a", "__future__ import print_function import glob import json import os import", "path for a HDF5 (.h5) file to save the model", "4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor) output = keras.layers.Dense(", "input_data = constant_op.constant(1., shape=[1]) root = tracking.AutoTrackable() root.v1 = variables.Variable(3.)", "os.path.join(self._tmp_dir, 'tfjs') # Use explicit --output_format value: tfjs_layers_model process =", "model = keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path: model.save(h5_path) return model def", "outputs=[output]) if h5_path: model.save(h5_path) return model def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create", "in compliance with the License. # You may obtain a", "shutil.rmtree(cls.class_tmp_dir) def setUp(self): # Make sure this file is not", "software # distributed under the License is distributed on an", "size # limit. self.assertEqual( 2, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionWithSignatureNameErrors(self): process", "Run the model.predict(), store the result. Then saved the model", "a directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x =", "optional flag # --split_weights_by_layer behavior. The model is a small", "Briefly check the model topology. with open(os.path.join(self._tmp_dir, 'model.json')) as f:", "points to a directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "'model.json'), new_h5_path ]) process.communicate() self.assertEqual(0, process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session(): #", "model.add(keras.layers.Dense(6, input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return model def _createFunctionalModelWithWeights(self): input1 =", "weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel',", "4) weight_file_sizes = [os.path.getsize(f) for f in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes)", "weights_manifest: for weight in manifest_item['weights']: weight_name = weight['name'] weight_shapes[weight_name] =", "weight groups due to the optional flag # --split_weights_by_layer behavior.", "import dtypes from tensorflow.python.framework import tensor_spec from tensorflow.python.ops import variables", "self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there", "subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "which to save the model. \"\"\" input_data = constant_op.constant(1., shape=[1])", "= weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias',", "4. Check the model.json and weight file and its size.", "self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4])", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'),", "1. Run the model.predict(), store the result. Then saved the", "package.\"\"\" @classmethod def setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir,", "['group1-shard1of1.bin'], 'weights': [{ 'dtype': 'float32', 'shape': [], 'name': 'StatefulPartitionedCall/mul' }]", "# Compare the loaded model with the original one. model2_weight_values", "predict # results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict(x) self.assertAllClose(y,", "a toy keras model. model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) #", "assert on the equality of the predict # results. model_prime", "module. with tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase):", "file and its size. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files),", "weights[0]['weights']) # Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir,", "model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict([x1, x2]) self.assertAllClose(y, new_y) def", "h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with tf.Graph().as_default(), tf.compat.v1.Session(): model =", "10) # 1. Run the model.predict(), store the result. Then", "name clashes between different test methods. save_path: The directory path", "setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir = tempfile.mkdtemp() def tearDown(self): if os.path.isdir(self._tmp_dir):", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'),", "2. Convert the HDF5 file to tensorflowjs format. process =", "in weights_manifest: for weight in manifest_item['weights']: weight_name = weight['name'] weight_shapes[weight_name]", "cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir = os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join(", "one weight group due to the default # non-split_weights_by_layer behavior.", "self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self): # 1. Create a toy keras", "= model_prime.predict(x) self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x1", "keras.Model instance. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json'))", "with the License. # You may obtain a copy of", "a small one. None of # the layers should have", "json.load( open(os.path.join(output_dir, 'model.json'), 'rt')) self.assertEqual(output_json['weightsManifest'], weights) # Check the content", "self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x1 = np.random.randn(4,", "LLC # # Licensed under the Apache License, Version 2.0", "# Use separate tf.Graph and tf.compat.v1.Session contexts to prevent name", "An instance of keras.Model. \"\"\" input_tensor = keras.layers.Input((3, )) dense1", "4. Check the quantized weight file and its size. weight_files", "'--input_format', 'keras', '--signature_name', 'bar', os.path.join(self._tmp_dir, 'foo.h5'), os.path.join(self._tmp_dir, 'output') ], stdout=subprocess.PIPE,", "with the # original model. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 =", "self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase):", "'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter',", "model is a small one, which # does not exceed", "another tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph') process = subprocess.Popen([ 'tensorflowjs_converter',", "4.0]]) w = tf.compat.v1.get_variable('w', shape=[2, 2]) y = tf.compat.v1.matmul(x, w)", "tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit value of", "a SavedModel. model = self._createNestedSequentialModel() y = model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir)", "'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes = [os.path.getsize(f) for f in weight_files]", "self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode,", "model and check the predict() output is close to #", "# 4. Load the model back and assert on the", "weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3,", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "create the model under. This helps avoid op and variable", "new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load the model", "'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir,", "'name': 'module/Variable', 'dtype': 'float32' }] }] # Load the saved", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert the tfjs model to keras h5", "Python source directory. ' 'This file is intended to be", "testing. model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path", "return model def _createNestedSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Dense(6, input_shape=[10], activation='relu'))", "CONDITIONS OF ANY KIND, either express or implied. # See", "Convert the tfjs model to keras h5 format. new_h5_path =", "layer_name_prefix: A prefix string for layer names. This helps avoid", "weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([ 'MergedDense1/kernel', 'MergedDense1/bias', 'MergedDense2/kernel' ]))", "as a keras.Model instance. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2 = tfjs.converters.load_keras_model(", "def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x1 = np.random.randn(4, 8) x2", "testing. Args: save_path: The directory path in which to save", "tf.Graph().as_default(), tf.compat.v1.Session(): # First create a toy keras model. os.makedirs(os.path.join(self._tmp_dir,", "model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session(): # Load the model from saved", "the saved weights as a JSON string. output_json = json.load(", "output = keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix + '2')(dense1) model", "'--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights =", "keras.Model([input1, input2], y) return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session():", "m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests for the Python API of", "+ '1')(input_tensor) output = keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones', name=layer_name_prefix +", "self._tmp_dir) model1_weight_values = model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session(): # Load the", "= tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) # Compare the loaded model with", "methods. h5_path: Optional string path for a HDF5 (.h5) file", "weights) * 4 keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras", "1) weight_file_size = os.path.getsize(weight_files[0]) # The size of the weight", "self._tmp_dir) # 2. Convert the keras saved model to tfjs", "tempfile import unittest import numpy as np import tensorflow as", "super(ConvertTfKerasSavedModelTest, self).tearDown() def _createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6]))", "= process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process =", "model_2 = keras.models.load_model(new_h5_path) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def testLoadTensorflowjsArtifactsAsKerasModel(self):", "default # non-split_weights_by_layer behavior. The model is a small one,", "self.assertIn( b'Expected path to point to an HDF5 file, '", "# Use incorrect --input_format value: keras process = subprocess.Popen( [", "Use separate tf.Graph and tf.compat.v1.Session contexts to prevent name collision.", "= keras.layers.Input((3, )) dense1 = keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros',", "2. Convert the keras saved model to tfjs_layers_model format. tfjs_output_dir", "'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras',", "SavedModel. model = self._createFunctionalModelWithWeights() y = model.predict([x1, x2]) keras.experimental.export_saved_model(model, self._tmp_dir)", "'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--weight_shard_size_bytes', str(weight_shard_size_bytes), os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir", "manifest_item in weights_manifest: for weight in manifest_item['weights']: weight_name = weight['name']", "process.communicate() self.assertEqual(0, process.returncode) # Briefly check the model topology. with", "self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) # 3. Convert", "'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process =", "'tensorflowjs')): self.fail('Do not run this test from the Python source", "input2], y) return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x", "output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths': ['group1-shard1of1.bin'],", "= _createKerasModel('MergedDenseForCLI', h5_path) model_json = model.to_json() # 2. Convert the", "applicable only to', tf.compat.as_bytes(stderr)) def testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process", "os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'),", "f in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3],", "model1 = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model1, self._tmp_dir) model1_weight_values = model1.get_weights() with tf.Graph().as_default(),", "root.f.get_concrete_function(input_data) save(root, save_path, to_save) def _create_hub_module(save_path): \"\"\"Create a TensorFlow Hub", "[{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'dtype': 'float32', 'shape': [], 'name':", "file should reflect the uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes // 2)", "self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): # 1. Create a toy keras", "the content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self):", "model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) # Check the content of the", "stderr = process.communicate() self.assertIn( b'Expected path to point to an", "tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path))", "3: self.assertItemsEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertItemsEqual(weights_manifest[0]['weights'], weights[0]['weights']) else: self.assertCountEqual(weights_manifest[0]['paths'], weights[0]['paths']) self.assertCountEqual(weights_manifest[0]['weights'], weights[0]['weights'])", "'tensorflowjs_converter', '--input_format', 'keras_saved_model', self._tmp_dir, tfjs_output_dir ]) process.communicate() self.assertEqual(0, process.returncode) model_json_path", "with open(os.path.join(self._tmp_dir, 'model.json'), 'rt') as f: json_content = json.load(f) model_json", "len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create", "should reflect the uint16 quantization. self.assertEqual(weight_file_size, total_weight_bytes // 2) def", "= keras.models.load_model(new_h5_path) new_y = new_model.predict(x) self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self): with", "weight['name'] weight_shapes[weight_name] = weight['shape'] weight_dtypes[weight_name] = weight['dtype'] self.assertEqual( sorted(list(weight_shapes.keys())), sorted([", "First create a toy keras model. model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model,", "to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Implicit value", "root.f = def_function.function(lambda x: root.v1 * root.v2 * x) to_save", "in zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) # Check the content", "'tf_hub', self.tf_hub_module_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{", "tracking.AutoTrackable() root.v1 = variables.Variable(3.) root.v2 = variables.Variable(2.) root.f = def_function.function(lambda", "model from saved artifacts. model2 = tfjs.converters.load_keras_model( os.path.join(self._tmp_dir, 'model.json')) #", "stderr = process.communicate() self.assertGreater(process.returncode, 0) self.assertIn(b'input_path', tf.compat.as_bytes(stderr)) def testKerasH5ConversionWorksFromCLI(self): with", "list) # Briefly check the weights manifest. weight_shapes = dict()", "non-split_weights_by_layer behavior. The model is a small one, which #", "'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a", "back from the new HDF5 file and compare with the", "'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', os.path.join(sharded_model_dir, 'model.json'), new_h5_path", "# 4. Check the quantized weight file and its size.", "new_model.predict(x) self.assertAllClose(new_y, y) def testConvertTfjsLayersModelWithQuantization(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x =", "dict) self.assertIsInstance(model_json['model_config']['config'], dict) self.assertIn('layers', model_json['model_config']['config']) weights_manifest = json_content['weightsManifest'] self.assertIsInstance(weights_manifest, list)", "the tfjs_layers_model to another tfjs_layers_model, # with uint16 quantization. weight_shard_size_bytes", "The model is a small one, which # does not", "self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFSavedModelWithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([", "self.assertEqual(0, process.returncode) self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) process =", "self.assertEqual(weight_file_sizes[0], weight_file_sizes[2]) self.assertLess(weight_file_sizes[3], weight_file_sizes[0]) # 5. Convert the sharded tfjs_layers_model", "process.communicate() self.assertEqual(0, process.returncode) # 4. Check the sharded weight files", "= def_function.function(lambda x: root.v1 * root.v2 * x) to_save =", "]) process.communicate() self.assertEqual(0, process.returncode) model_json_path = os.path.join(tfjs_output_dir, 'model.json') self.assertTrue(os.path.isfile(model_json_path)) #", "input_tensor = keras.layers.Input((3, )) dense1 = keras.layers.Dense( 4, use_bias=True, kernel_initializer='ones',", "API and shell binary of the tensorflowjs pip package.\"\"\" from", "2]}]}] # Load the saved weights as a JSON string.", "HDF5 file, ' b'but it points to a directory', tf.compat.as_bytes(stderr))", "'weights': [{'dtype': 'float32', 'name': 'w', 'shape': [2, 2]}]}] # Load", "predict() output is close to # before. new_model = keras.models.load_model(new_h5_path)", "Create a model for testing. model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu',", "and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files = sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin')))", "'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir", "Convert the tensorflowjs artifacts back to HDF5. new_h5_path = os.path.join(self._tmp_dir,", "input_shape=[10], activation='relu')) model.add(self._createSimpleSequentialModel()) return model def _createFunctionalModelWithWeights(self): input1 = keras.Input(shape=[8])", "Create a toy keras model and save it as an", "# as a SavedModel. model = self._createFunctionalModelWithWeights() y = model.predict([x1,", "weights = [{ 'paths': ['group1-shard1of1.bin'], 'weights': [{ 'shape': [2], 'name':", "y = model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) # 2. Convert the keras", "from tensorflow.python.ops import variables from tensorflow.python.training.tracking import tracking from tensorflow.python.saved_model.save", "Python API and shell binary of the tensorflowjs pip package.\"\"\"", "b'but it points to a directory', tf.compat.as_bytes(stderr)) def testConvertTfjsLayersModelIntoShardedWeights(self): with", "tf.Graph().as_default(), tf.compat.v1.Session(): x1 = np.random.randn(4, 8) x2 = np.random.randn(4, 10)", "which to save the model. \"\"\" graph = tf.Graph() with", "weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1) weight_file_size = os.path.getsize(weight_files[0])", "Returns: An instance of keras.Model. \"\"\" input_tensor = keras.layers.Input((3, ))", "tensorflow_hub as hub import tensorflowjs as tfjs def _createKerasModel(layer_name_prefix, h5_path=None):", "Copyright 2018 Google LLC # # Licensed under the Apache", "save(root, save_path, to_save) def _create_hub_module(save_path): \"\"\"Create a TensorFlow Hub module", "path in which to save the model. \"\"\" # Module", "'--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate() self.assertEqual(0, process.returncode) self.assertIn(", "is a small one. None of # the layers should", "'model.json'), 'rt')) weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0] <", "directory path in which to save the model. \"\"\" input_data", "and check the predict() output is close to # before.", "import sys import tempfile import unittest import numpy as np", "self.assertIn( b'The --signature_name flag is applicable only to', tf.compat.as_bytes(stderr)) def", "graph.as_default(): spec = hub.create_module_spec(double_module_fn) m = hub.Module(spec) # Export the", "self.assertEqual(0, process.returncode) # Briefly check the model topology. with open(os.path.join(self._tmp_dir,", "'--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, layers_model_output_dir ]) process.communicate() self.assertEqual(0,", "tensorflow.python.framework import tensor_spec from tensorflow.python.ops import variables from tensorflow.python.training.tracking import", "# First create a toy keras model. model = _createKerasModel('MergedDense')", "to the shard size, there ought to be 4 shards", "tf.compat.v1.Session(): model_2 = keras.models.load_model(new_h5_path) model_2_json = model_2.to_json() self.assertEqual(model_json, model_2_json) def", "size of the weight file should reflect the uint16 quantization.", "shards after conversion. sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded') process = subprocess.Popen([", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "the Python API of the pip package.\"\"\" @classmethod def setUpClass(cls):", "os.path.getsize(weight_files[0]) # The size of the weight file should reflect", "behavior. The model is a small one. None of #", "from the new HDF5 file and compare with the #", "model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values), len(model2_weight_values)) for model1_weight_value, model2_weight_value in zip(", "self.assertIn( tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) process = subprocess.Popen( ['tensorflowjs_converter',", "'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights", "= subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'keras', self._tmp_dir, tfjs_output_dir ], stdout=subprocess.PIPE,", "[{ 'dtype': 'float32', 'shape': [], 'name': 'StatefulPartitionedCall/mul' }] }] #", "input2]) y = keras.layers.Dense(4, activation='softmax')(y) model = keras.Model([input1, input2], y)", "that there are two weight groups due to the optional", "pip package.\"\"\" @classmethod def setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir =", "tensorflow.python.saved_model.save import save import tensorflow_hub as hub import tensorflowjs as", "def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for testing. Args:", "f: json_content = json.load(f) model_json = json_content['modelTopology'] self.assertIsInstance(model_json['model_config'], dict) self.assertIsInstance(model_json['model_config']['config'],", "double_module_fn(): w = tf.Variable([2.0, 4.0]) x = tf.compat.v1.placeholder(dtype=tf.float32) hub.add_signature(inputs=x, outputs=x*w)", "the HDF5 file to tensorflowjs format. process = subprocess.Popen([ 'tensorflowjs_converter',", "int(total_weight_bytes * 0.3) # Due to the shard size, there", "SavedModel. model = self._createNestedSequentialModel() y = model.predict(x) keras.experimental.export_saved_model(model, self._tmp_dir) #", "the model. \"\"\" input_data = constant_op.constant(1., shape=[1]) root = tracking.AutoTrackable()", "their sizes. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 4) weight_file_sizes", "of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTFHubModuleWithCommandLineWorks(self): output_dir =", "the model. \"\"\" # Module function that doubles its input.", "# as a SavedModel. model = self._createNestedSequentialModel() y = model.predict(x)", "graph = tf.Graph() with graph.as_default(): spec = hub.create_module_spec(double_module_fn) m =", "file and compare with the # original model. with tf.Graph().as_default(),", "Use incorrect --input_format value: keras process = subprocess.Popen( [ 'tensorflowjs_converter',", "Version 2.0 (the \"License\"); # you may not use this", "# 1. Create a toy keras model and save it", "keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path = os.path.join(self._tmp_dir, 'model.h5')", "that there is only one weight group due to the", "\"\"\" input_tensor = keras.layers.Input((3, )) dense1 = keras.layers.Dense( 4, use_bias=True,", "format. process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras', h5_path, self._tmp_dir ])", "Verify that there is only one weight group due to", "from tensorflow import keras from tensorflow.python.eager import def_function from tensorflow.python.framework", "2]) self.assertEqual(weight_dtypes['MergedDenseForCLI1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that", "a toy keras model. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5',", "new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model',", "# Briefly check the model topology. with open(os.path.join(self._tmp_dir, 'model.json')) as", "'float32') # Verify that there is only one weight group", "__future__ import absolute_import from __future__ import division from __future__ import", "def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) #", "model # as a SavedModel. model = self._createFunctionalModelWithWeights() y =", "format. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "division from __future__ import print_function import glob import json import", "weight file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def testKerasH5ConversionSplitWeightsByLayerWorksFromCLI(self): with tf.Graph().as_default(),", "os.path.join(self._tmp_dir, 'model.json'), new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) # 4. Load the", "self._tmp_dir) # 2. Convert the keras saved model to tfjs_layers_model", "return model def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for", "model1_weight_value, model2_weight_value in zip( model1_weight_values, model2_weight_values): self.assertAllClose(model1_weight_value, model2_weight_value) # Check", "to # before. new_model = keras.models.load_model(new_h5_path) new_y = new_model.predict(x) self.assertAllClose(new_y,", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_hub', self.tf_hub_module_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode)", "by applicable law or agreed to in writing, software #", "model.add(keras.layers.Dense(1, activation='sigmoid')) return model def _createNestedSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Dense(6,", "format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use incorrect --input_format value:", "testSaveKerasModel(self): with self.test_session(): # First create a toy keras model.", "= subprocess.Popen( ['tensorflowjs_converter', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ = process.communicate()", "the model.json and weight file and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json')))", "back into a keras h5 file. new_h5_path = os.path.join(self._tmp_dir, 'new_h5.h5')", "the pip package.\"\"\" @classmethod def setUpClass(cls): cls.class_tmp_dir = tempfile.mkdtemp() cls.tf_saved_model_dir", "process = subprocess.Popen( [ 'tensorflowjs_converter' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr", "model2_weight_value) # Check the content of the output directory. self.assertTrue(glob.glob(os.path.join(self._tmp_dir,", "tf.Graph().as_default(), tf.compat.v1.Session(): # 6. Load the keras model and check", "'model.json'), graph_model_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 4. Check the", "Convert the keras saved model to tfjs_layers_model format. tfjs_output_dir =", "builder.save() def _createTensorFlowSavedModel(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for testing.", "tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model', self._tmp_dir,", "testing. Args: layer_name_prefix: A prefix string for layer names. This", "tensorflowjs pip package.\"\"\" from __future__ import absolute_import from __future__ import", "file and its size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files = sorted( glob.glob(os.path.join(graph_model_dir,", "0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process = subprocess.Popen( [ 'tensorflowjs_converter'", "process = subprocess.Popen( ['tensorflowjs_converter', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, _ =", "test methods. h5_path: Optional string path for a HDF5 (.h5)", "open(os.path.join(output_dir, 'model.json'), 'rt')) weights_manifest = output_json['weightsManifest'] self.assertEqual(len(weights_manifest), len(weights)) if sys.version_info[0]", "h5_path = os.path.join(self._tmp_dir, 'model.h5') model.save(h5_path) # 2. Convert the keras", "pip package.\"\"\" from __future__ import absolute_import from __future__ import division", "= os.path.join(self._tmp_dir, 'tfjs') # Use explicit --output_format value: tfjs_layers_model process", "os import shutil import subprocess import sys import tempfile import", "save_path): \"\"\"Create a TensorFlow SavedModel for testing. Args: name_scope: Name", "= tf.compat.v1.get_variable('w', shape=[2, 2]) y = tf.compat.v1.matmul(x, w) output =", "value: tfjs_layers_model process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'keras_saved_model', '--output_format', 'tfjs_layers_model',", "_createKerasModel(layer_name_prefix, h5_path=None): \"\"\"Create a Keras model for testing. Args: layer_name_prefix:", "'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'], [4]) self.assertEqual(weight_shapes['MergedDenseForCLI2/kernel'],", "os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir,", "self.assertEqual(0, process.returncode) # 4. Check the sharded weight files and", "up source files. if os.path.isdir( os.path.join(os.path.dirname(__file__), 'tensorflowjs')): self.fail('Do not run", "self._tmp_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = process.communicate() self.assertGreater(process.returncode, 0)", "os.path.join(self._tmp_dir, 'new_h5.h5') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras',", "'MergedDense2/kernel' ])) self.assertEqual(weight_shapes['MergedDense1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDense1/bias'], [4]) self.assertEqual(weight_shapes['MergedDense2/kernel'], [4, 2])", "applicable law or agreed to in writing, software # distributed", "helps avoid op and variable name clashes between different test", "dict() for manifest_item in weights_manifest: for weight in manifest_item['weights']: weight_name", "process.communicate() self.assertEqual(0, process.returncode) # 4. Check the model.json and weight", "self).tearDown() def _createSimpleSequentialModel(self): model = keras.Sequential() model.add(keras.layers.Reshape([2, 3], input_shape=[6])) model.add(keras.layers.LSTM(10))", "it as an HDF5 file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir,", "the tensorflowjs artifacts back to HDF5. new_h5_path = os.path.join(self._tmp_dir, 'model_2.h5')", "testVersionString(self): self.assertEqual(2, tfjs.__version__.count('.')) def testSaveKerasModel(self): with self.test_session(): # First create", "saved the model # as a SavedModel. model = self._createNestedSequentialModel()", "for the Python API of the pip package.\"\"\" @classmethod def", "weight group due to the default # non-split_weights_by_layer behavior. The", "there ought to be 4 shards after conversion. sharded_model_dir =", "'--output_format', 'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir, 'model.json'), sharded_model_dir ]) process.communicate() self.assertEqual(0,", "'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_graph_model', os.path.join(layers_model_output_dir, 'model.json'), graph_model_dir ]) process.communicate()", "self.assertGreater(process.returncode, 0) self.assertIn(b'--input_format', tf.compat.as_bytes(stderr)) def testMissingInputPathRaisesError(self): process = subprocess.Popen( [", "model back from the new HDF5 file and compare with", "= keras.Model([input1, input2], y) return model def testConvertTfKerasNestedSequentialSavedModelIntoTfjsFormat(self): with tf.Graph().as_default(),", "a toy keras model and save it as an HDF5", "saved model to tfjs_layers_model format. layers_model_output_dir = os.path.join(self._tmp_dir, 'tfjs_layers') #", "os.path.join(self._tmp_dir, 'tfjs_layers') # Implicit value of --output_format: tfjs_layers_model process =", "[os.path.getsize(f) for f in weight_files] self.assertEqual(sum(weight_file_sizes), total_weight_bytes) self.assertEqual(weight_file_sizes[0], weight_file_sizes[1]) self.assertEqual(weight_file_sizes[0],", "self.assertIsInstance(weights_manifest, list) # Briefly check the weights manifest. weight_shapes =", "Briefly check the weights manifest. weight_shapes = dict() weight_dtypes =", "3. Convert the tfjs model to keras h5 format. new_h5_path", "2. Convert the keras saved model to tfjs format. tfjs_output_dir", "os.path.join(cls.class_tmp_dir, 'tf_saved_model') cls.tf_saved_model_v1_dir = os.path.join( cls.class_tmp_dir, 'tf_saved_model_v1') _createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b',", "process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'keras', model_json_path, new_h5_path])", "import tensorflow as tf from tensorflow import keras from tensorflow.python.eager", "# You may obtain a copy of the License at", "1. Create a model for testing. model = keras.Sequential() model.add(keras.layers.Dense(10,", "os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "size. self.assertTrue(os.path.isfile(os.path.join(graph_model_dir, 'model.json'))) weight_files = sorted( glob.glob(os.path.join(graph_model_dir, 'group*.bin'))) self.assertEqual(len(weight_files), 1)", "with tf.Graph().as_default(), tf.compat.v1.Session(): model = _createKerasModel('MergedDenseForCLI', h5_path) model_json = model.to_json()", "% tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest, self).setUp() self._tmp_dir", "subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_v1_dir, output_dir ]) process.communicate()", "# Briefly check the weights manifest. weight_shapes = dict() weight_dtypes", "be only one weight file. self.assertEqual( 1, len(glob.glob(os.path.join(self._tmp_dir, 'group*')))) def", "4 shards after conversion. sharded_model_dir = os.path.join(self._tmp_dir, 'tfjs_sharded') process =", "self.assertEqual(weight_dtypes['MergedDense1/kernel'], 'float32') self.assertEqual(weight_dtypes['MergedDense1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDense2/kernel'], 'float32') def testLoadKerasModel(self): # Use", "point to an HDF5 file, ' b'but it points to", "new_h5_path]) process.communicate() self.assertEqual(0, process.returncode) # 4. Load the model back", "only one weight group due to the default # non-split_weights_by_layer", "with sharded weights. weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due", "the Python API and shell binary of the tensorflowjs pip", "2. Convert the keras saved model to tfjs_layers_model format. layers_model_output_dir", "= keras.models.load_model(new_h5_path) new_y = model_prime.predict(x) self.assertAllClose(y, new_y) def testConvertTfKerasFunctionalSavedModelIntoTfjsFormat(self): with", "with tf.compat.v1.Session(graph=graph) as sess: sess.run(tf.compat.v1.global_variables_initializer()) m.export(save_path, sess) class APIAndShellTest(tf.test.TestCase): \"\"\"Tests", "content of the output directory. self.assertTrue(glob.glob(os.path.join(output_dir, 'group*-*'))) def testConvertTensorflowjsArtifactsToKerasH5(self): #", "incorrect --input_format value: keras process = subprocess.Popen( [ 'tensorflowjs_converter', '--input_format',", "\"\"\"Test the Python API and shell binary of the tensorflowjs", "'shape': [2], 'name': 'module/Variable', 'dtype': 'float32' }] }] # Load", "not run this test from the Python source directory. '", "'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod def tearDownClass(cls): shutil.rmtree(cls.class_tmp_dir) def setUp(self): # Make", "create a toy keras model. model = _createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir)", "keras model and check the predict() output is close to", "model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=[4])) model.add(keras.layers.Dense(1, activation='sigmoid')) h5_path =", "\"\"\"Create a TensorFlow SavedModel for testing. Args: name_scope: Name scope", "file. os.makedirs(os.path.join(self._tmp_dir, 'keras_h5')) h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') with tf.Graph().as_default(),", "def _createTensorFlowSavedModelV1(name_scope, save_path): \"\"\"Create a TensorFlow SavedModel for testing. Args:", "testConvertTFSavedModelV1WithCommandLineWorks(self): output_dir = os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model',", "4-MB shard size limit. Therefore, there should # be only", "the predict # results. model_prime = keras.models.load_model(new_h5_path) new_y = model_prime.predict(x)", "_createTensorFlowSavedModel('a', cls.tf_saved_model_dir) _createTensorFlowSavedModelV1('b', cls.tf_saved_model_v1_dir) cls.tf_hub_module_dir = os.path.join(cls.class_tmp_dir, 'tf_hub_module') _create_hub_module(cls.tf_hub_module_dir) @classmethod", "_createKerasModel('MergedDense') tfjs.converters.save_keras_model(model, self._tmp_dir) # Briefly check the model topology. with", "to tfjs format. tfjs_output_dir = os.path.join(self._tmp_dir, 'tfjs') # Use explicit", "with tf.Graph().as_default(), tf.compat.v1.Session(): x = np.random.randn(8, 10) # 1. Run", "HDF5 file to tensorflowjs format. process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "weights. weight_shard_size_bytes = int(total_weight_bytes * 0.3) # Due to the", "= subprocess.Popen( [ 'tensorflowjs_converter', '--input_format', 'nonsensical_format', self._tmp_dir, self._tmp_dir ], stdout=subprocess.PIPE,", "self.assertEqual(weight_dtypes['MergedDenseForCLI1/bias'], 'float32') self.assertEqual(weight_dtypes['MergedDenseForCLI2/kernel'], 'float32') # Verify that there is only", "tf.compat.as_bytes('tensorflowjs %s' % tfjs.__version__), tf.compat.as_bytes(stdout)) class ConvertTfKerasSavedModelTest(tf.test.TestCase): def setUp(self): super(ConvertTfKerasSavedModelTest,", "prefix string for layer names. This helps avoid clashes in", "Load the saved weights as a JSON string. output_json =", "model.predict(), store the result. Then saved the model # as", "bias_initializer='zeros', name=layer_name_prefix + '1')(input_tensor) output = keras.layers.Dense( 2, use_bias=False, kernel_initializer='ones',", "spec = hub.create_module_spec(double_module_fn) m = hub.Module(spec) # Export the module.", "different test methods. save_path: The directory path in which to", "weight file and its size. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir, 'group*.bin')))", "new_h5_path ]) process.communicate() self.assertEqual(0, process.returncode) with tf.Graph().as_default(), tf.compat.v1.Session(): # 6.", "import os import shutil import subprocess import sys import tempfile", "\"License\"); # you may not use this file except in", "def_function.function(lambda x: root.v1 * root.v2 * x) to_save = root.f.get_concrete_function(input_data)", "os.path.join(self._tmp_dir) process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tf_saved_model', '--output_format', 'tfjs_graph_model', self.tf_saved_model_dir,", "sorted(list(weight_shapes.keys())), sorted([ 'MergedDenseForCLI1/kernel', 'MergedDenseForCLI1/bias', 'MergedDenseForCLI2/kernel' ])) self.assertEqual(weight_shapes['MergedDenseForCLI1/kernel'], [3, 4]) self.assertEqual(weight_shapes['MergedDenseForCLI1/bias'],", "= root.f.get_concrete_function(input_data) save(root, save_path, to_save) def _create_hub_module(save_path): \"\"\"Create a TensorFlow", "= subprocess.Popen([ 'tensorflowjs_converter', '--input_format', 'tfjs_layers_model', '--output_format', 'tfjs_layers_model', '--quantization_bytes', '2', os.path.join(tfjs_output_dir,", "quantized weight file and its size. weight_files = sorted( glob.glob(os.path.join(sharded_model_dir,", "'keras', h5_path, self._tmp_dir ]) process.communicate() self.assertEqual(0, process.returncode) # 3. Load", "tensorflowjs artifacts as a keras.Model instance. with tf.Graph().as_default(), tf.compat.v1.Session(): model_2", "model1_weight_values = model1.get_weights() with tf.Graph().as_default(), tf.compat.v1.Session(): # Load the model", "loaded model with the original one. model2_weight_values = model2.get_weights() self.assertEqual(len(model1_weight_values),", "self.tf_saved_model_dir, output_dir ]) process.communicate() self.assertEqual(0, process.returncode) weights = [{ 'paths':", "tfjs_graph_model. graph_model_dir = os.path.join(self._tmp_dir, 'tfjs_graph') process = subprocess.Popen([ 'tensorflowjs_converter', '--input_format',", "prevent name collision. with tf.Graph().as_default(), tf.compat.v1.Session(): # First create a", "the equality of the predict # results. model_prime = keras.models.load_model(new_h5_path)", "the initializer on `w`. sess.run(init_op) builder.add_meta_graph_and_variables( sess, [tf.compat.v1.saved_model.tag_constants.SERVING], signature_def_map={ \"serving_default\":", "is not being run from the source directory, to #", "self.assertTrue(os.path.isfile(new_h5_path)) # 4. Load the model back and assert on", "8) x2 = np.random.randn(4, 10) # 1. Run the model.predict(),", "h5_path = os.path.join(self._tmp_dir, 'keras_h5', 'model.h5') _createKerasModel('MergedDenseForCLI', h5_path) process = subprocess.Popen([", "kernel_initializer='ones', name=layer_name_prefix + '2')(dense1) model = keras.models.Model(inputs=[input_tensor], outputs=[output]) if h5_path:", "shell binary of the tensorflowjs pip package.\"\"\" from __future__ import" ]
[ "re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" % (folder, str(match[0]))) if", "new = old setNew(new, value) def lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds',", "COLOR1, SKIN[5:].title()), \"Would you like to view a list of", "gui file: %s\" % gui) guif = open(gui, 'r+') msg", "gui settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" % str(match)) if", "from resources.lib.modules import control try: import json as simplejson except:", "re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" % str(match)) if len(match) > 0: skinid", "import control try: import json as simplejson except: import simplejson", "def checkSkin(): control.loga(\"Invalid Skin Check Start\") DEFAULTSKIN = setting('defaultskin') DEFAULTNAME", "current = getOld(old) new = old setNew(new, value) def lookandFeelData(do='save'):", "'save': for item in scan: query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}'", "control.log(\"[Default Skin Check]\") tempgui = os.path.join(USERDATAPATH, 'guitemp.xml') gui = tempgui", "match2[0] else: skinname = 'no match' else: skinname = 'no", "skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID not found for %s\" % folder)", "= DEFAULTNAME else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin", "> 0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID not found for %s\"", "(item, value)) def defaultSkin(): control.log(\"[Default Skin Check]\") tempgui = os.path.join(USERDATAPATH,", "gui = tempgui if os.path.exists(tempgui) else GUISETTINGS if not os.path.exists(gui):", "switch to!\", skinname) if choice == -1: control.loga(\"Skin was not", "else GUISETTINGS if not os.path.exists(gui): return False control.log(\"Reading gui file:", "'': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems that", "folder if os.path.exists(xml): f = open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close();", "(item) response = control.jsonrpc(query) if not 'error' in response: match", "skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui): control.log(\"Deleting", "you like to view a list of avaliable skins?[/COLOR]\"): choice", "%s]It seems that the skin has been set back to", "= skin current = getOld(old) new = old setNew(new, value)", "json as simplejson except: import simplejson ADDONS = os.path.join(control.HOMEPATH, 'addons')", "% (old) response = control.jsonrpc(query) response = simplejson.loads(response) if response.has_key('result'):", "match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" % (folder, str(match[0]))) if len(match)", "skinlist = [] for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml =", "0: skinname = match2[0] else: skinname = 'no match' else:", "not reset\"); control.setSetting('defaultskinignore', 'true') else: control.loga(\"No skins found in addons", "= open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2", "(COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to set the skin", "os.path.exists(addonxml): addf = open(addonxml, 'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2", "= skinlist[choice] gotoname = skinname[choice] else: control.loga(\"Skin was not reset\");", "if response.has_key('result'): if response['result'].has_key('value'): return response ['result']['value'] except: pass return", "re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s saved to %s\" % (item,", "control.loga(\"ID not found for %s\" % folder) else: control.loga(\"ID not", "control.loga(\"ID not found for %s\" % folder) if len(skinlist) >", "match' else: skinname = 'no file' control.log(\"[Default Skin Check] Skin", "DEFAULTSKIN == '': skinname = [] skinlist = [] for", "scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow',", "while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x < 150: x += 1", "\"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item) response = control.jsonrpc(query) if not 'error'", "not found for %s\" % folder) else: control.loga(\"ID not found", "gotoname = DEFAULTNAME else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true');", "if not DEFAULTSKIN == '': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle,", "def getOld(old): try: old = '\"%s\"' % old query =", "'{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old) response = control.jsonrpc(query) response =", "if do == 'save': for item in scan: query =", "\"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old) response = control.jsonrpc(query) response = simplejson.loads(response)", "for item in scan: value = setting(item.replace('lookandfeel', 'default')) query =", "Check Start\") DEFAULTSKIN = setting('defaultskin') DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE =", "= '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item) response = control.jsonrpc(query) if", "gotoskin = False if not DEFAULTSKIN == '': if os.path.exists(os.path.join(ADDONS,", "> 1: if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems that the skin", "% folder if os.path.exists(xml): f = open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t','');", "%s\" % gui) guif = open(gui, 'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace('", "to switch to!\", skinname) if choice == -1: control.loga(\"Skin was", "swapSkins(gotoskin) x = 0 control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x", "DIALOG.yesno(control.AddonTitle, \"It seems that the skin has been set back", "[] skinlist = [] for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml", "control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap Timed Out!') control.loga(\"Invalid Skin Check", "= ''; DEFAULTNAME = '' if DEFAULTSKIN == '': skinname", "old = '\"%s\"' % old query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}'", "pass return None def swapSkins(skin): old = 'lookandfeel.skin' value =", "control.log(\"%s saved to %s\" % (item, match[0])) else: for item", "\"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item, value) response = control.jsonrpc(query) control.log(\"%s restored", "folder) else: control.loga(\"ID not found for %s\" % folder) if", "gotoskin: swapSkins(gotoskin) x = 0 control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and", "# -*- coding: UTF-8 -*- import os, re, shutil, time,", "xbmc from resources.lib.modules import control try: import json as simplejson", "= setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore') gotoskin = False if not", "DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems that the skin has", "0: skinid = match[0] addonxml = os.path.join(ADDONS, match[0], 'addon.xml') if", "addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) > 0: skinname =", "\"It seems that the skin has been set back to", "the skin back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)): gotoskin", "the skin has been set back to [B]%s[/B]\" % (SKIN[5:].title()),", "folder in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml = \"%s/addon.xml\" % folder if", "value): try: new = '\"%s\"' % new value = '\"%s\"'", "= os.path.join(control.HOMEPATH, 'addons') def currSkin(): return control.skin def getOld(old): try:", "SKIN[5:].title()), \"Would you like to view a list of avaliable", "control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap Timed Out!')", "= match2[0] else: skinname = 'no match' else: skinname =", "you like to set the skin back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]'", "0 control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x < 150: x", "control.log(\"Reading gui file: %s\" % gui) guif = open(gui, 'r+')", "os, re, shutil, time, xbmc from resources.lib.modules import control try:", "= False if gotoskin: swapSkins(gotoskin) x = 0 control.sleep(1000) while", "Check] Skin name: %s\" % skinname) control.log(\"[Default Skin Check] Skin", "skinname = [] skinlist = [] for folder in glob.glob(os.path.join(ADDONS,", "not found for %s\" % folder) if len(skinlist) > 0:", "'': skinname = [] skinlist = [] for folder in", "(SKIN[5:].title()), \"Would you like to set the skin back to:", "%s\" % str(match)) if len(match) > 0: skinid = match[0]", "response = control.jsonrpc(query) if not 'error' in response: match =", "response = control.jsonrpc(query) except: pass return None def swapSkins(skin): old", "restored to %s\" % (item, value)) def defaultSkin(): control.log(\"[Default Skin", "= addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) > 0:", "control.setSetting('defaultskinname', ''); DEFAULTSKIN = ''; DEFAULTNAME = '' if DEFAULTSKIN", "'' if DEFAULTSKIN == '': skinname = [] skinlist =", "DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore') gotoskin = False if", "old = 'lookandfeel.skin' value = skin current = getOld(old) new", "re, shutil, time, xbmc from resources.lib.modules import control try: import", "not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x < 150: x += 1 control.sleep(200)", "control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN = ''; DEFAULTNAME = ''", "0: if len(skinlist) > 1: if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems", "'\"%s\"' % old query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old)", "Skin Check]\") tempgui = os.path.join(USERDATAPATH, 'guitemp.xml') gui = tempgui if", "'[B] %s [/B]' % (skinname[0])): gotoskin = skinlist[0] gotoname =", "swapSkins(skin): old = 'lookandfeel.skin' value = skin current = getOld(old)", "set back to [COLOR %s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()), \"Would", "response['result'].has_key('value'): return response ['result']['value'] except: pass return None def setNew(new,", "len(match2) > 0: skinname = match2[0] else: skinname = 'no", "% (SKIN[5:].title()), \"Would you like to set the skin back", "found in addons folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False if", "(old) response = control.jsonrpc(query) response = simplejson.loads(response) if response.has_key('result'): if", "Gui File.\") os.remove(tempgui) control.log(\"[Default Skin Check] End\") def checkSkin(): control.loga(\"Invalid", "= '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item, value) response = control.jsonrpc(query)", "gotoskin = False if gotoskin: swapSkins(gotoskin) x = 0 control.sleep(1000)", "(COLOR1, DEFAULTNAME)): gotoskin = DEFAULTSKIN gotoname = DEFAULTNAME else: control.loga(\"Skin", "= control.jsonrpc(query) control.log(\"%s restored to %s\" % (item, value)) def", "Skin name: %s\" % skinname) control.log(\"[Default Skin Check] Skin id:", "os.path.exists(gui): return False control.log(\"Reading gui file: %s\" % gui) guif", "= 'lookandfeel.skin' value = skin current = getOld(old) new =", "def currSkin(): return control.skin def getOld(old): try: old = '\"%s\"'", "except: pass return None def swapSkins(skin): old = 'lookandfeel.skin' value", "not reset\"); control.setSetting('defaultskinignore', 'true') else: gotoskin = skinlist[choice] gotoname =", "simplejson ADDONS = os.path.join(control.HOMEPATH, 'addons') def currSkin(): return control.skin def", "> 0: skinid = match[0] addonxml = os.path.join(ADDONS, match[0], 'addon.xml')", "'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do == 'save':", "g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g)", "for %s\" % folder) if len(skinlist) > 0: if len(skinlist)", "== -1: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: gotoskin", "response: match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s saved to", "pass return None def setNew(new, value): try: new = '\"%s\"'", "view a list of avaliable skins?[/COLOR]\"): choice = DIALOG.select(\"Select skin", "item in scan: query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item)", "%s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to set", "control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: gotoskin = skinlist[choice]", "'\"%s\"' % new value = '\"%s\"' % value query =", "import simplejson ADDONS = os.path.join(control.HOMEPATH, 'addons') def currSkin(): return control.skin", "'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do == 'save': for item in", "skinname) if choice == -1: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore',", "DEFAULTNAME else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin =", "in addons folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False if gotoskin:", "item in scan: value = setting(item.replace('lookandfeel', 'default')) query = '{\"jsonrpc\":\"2.0\",", "= 'no file' control.log(\"[Default Skin Check] Skin name: %s\" %", "Skin Check] Skin name: %s\" % skinname) control.log(\"[Default Skin Check]", "= tempgui if os.path.exists(tempgui) else GUISETTINGS if not os.path.exists(gui): return", "open(gui, 'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening gui settings\")", "reset\"); control.setSetting('defaultskinignore', 'true') else: if DIALOG.yesno(control.AddonTitle, \"It seems that the", "in scan: value = setting(item.replace('lookandfeel', 'default')) query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s},", "False control.log(\"Reading gui file: %s\" % gui) guif = open(gui,", "match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" % (folder,", "% (skinname[0])): gotoskin = skinlist[0] gotoname = skinname[0] else: control.loga(\"Skin", "has been set back to [B]%s[/B]\" % (SKIN[5:].title()), \"Would you", "= os.path.join(USERDATAPATH, 'guitemp.xml') gui = tempgui if os.path.exists(tempgui) else GUISETTINGS", "reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname',", "== '': skinname = [] skinlist = [] for folder", "control.log(\"[Default Skin Check] Skin id: %s\" % skinid) control.setSetting('defaultskin', skinid)", "xml = \"%s/addon.xml\" % folder if os.path.exists(xml): f = open(xml,mode='r');", "in scan: query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item) response", "'\"%s\"' % value query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new,", "%s\" % skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false') if", "= False if not DEFAULTSKIN == '': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)):", "new value = '\"%s\"' % value query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s},", "open(addonxml, 'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if", "\", '[B] %s [/B]' % (skinname[0])): gotoskin = skinlist[0] gotoname", "match[0], 'addon.xml') if os.path.exists(addonxml): addf = open(addonxml, 'r+') msg2 =", "shutil, time, xbmc from resources.lib.modules import control try: import json", "control.jsonrpc(query) control.log(\"%s restored to %s\" % (item, value)) def defaultSkin():", "response = control.jsonrpc(query) control.log(\"%s restored to %s\" % (item, value))", "control.setSetting('defaultskinignore', 'true'); gotoskin = False else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', '');", "gotoskin = skinlist[0] gotoname = skinname[0] else: control.loga(\"Skin was not", "(item, match[0])) else: for item in scan: value = setting(item.replace('lookandfeel',", "getOld(old): try: old = '\"%s\"' % old query = '{\"jsonrpc\":\"2.0\",", "(item, value) response = control.jsonrpc(query) control.log(\"%s restored to %s\" %", "value) response = control.jsonrpc(query) except: pass return None def swapSkins(skin):", "\"Would you like to view a list of avaliable skins?[/COLOR]\"):", "control.log(\"%s restored to %s\" % (item, value)) def defaultSkin(): control.log(\"[Default", "-*- import os, re, shutil, time, xbmc from resources.lib.modules import", "skin has been set back to [B]%s[/B]\" % (SKIN[5:].title()), \"Would", "if choice == -1: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true')", "os.path.exists(xml): f = open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match =", "and x < 150: x += 1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"):", "= \"%s/addon.xml\" % folder if os.path.exists(xml): f = open(xml,mode='r'); g", "%s\" % folder) if len(skinlist) > 0: if len(skinlist) >", "'no match' else: skinname = 'no file' control.log(\"[Default Skin Check]", "list of avaliable skins?[/COLOR]\"): choice = DIALOG.select(\"Select skin to switch", "value = skin current = getOld(old) new = old setNew(new,", "% (item) response = control.jsonrpc(query) if not 'error' in response:", "= '\"%s\"' % new value = '\"%s\"' % value query", "'true') else: if DIALOG.yesno(control.AddonTitle, \"It seems that the skin has", "if len(match2) > 0: skinname = match2[0] else: skinname =", "% skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui):", "match[0]) control.log(\"%s saved to %s\" % (item, match[0])) else: for", "len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID not found for", "'{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item) response = control.jsonrpc(query) if not", "[/B]' % (skinname[0])): gotoskin = skinlist[0] gotoname = skinname[0] else:", "% (COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to view a", "%s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)): gotoskin = DEFAULTSKIN gotoname = DEFAULTNAME", "% (new, value) response = control.jsonrpc(query) except: pass return None", "lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin',", "= control.jsonrpc(query) if not 'error' in response: match = re.compile('{\"value\":(.+?)}').findall(str(response))", "= match[0] addonxml = os.path.join(ADDONS, match[0], 'addon.xml') if os.path.exists(addonxml): addf", "back to: \", '[B] %s [/B]' % (skinname[0])): gotoskin =", "% skinname) control.log(\"[Default Skin Check] Skin id: %s\" % skinid)", "control.setSetting('defaultskinignore', 'true'); gotoskin = False if gotoskin: swapSkins(gotoskin) x =", "Skin Check] End\") def checkSkin(): control.loga(\"Invalid Skin Check Start\") DEFAULTSKIN", "value = setting(item.replace('lookandfeel', 'default')) query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' %", "['result']['value'] except: pass return None def setNew(new, value): try: new", "to set the skin back to: \", '[B] %s [/B]'", "of avaliable skins?[/COLOR]\"): choice = DIALOG.select(\"Select skin to switch to!\",", "0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID not found for %s\" %", "return control.skin def getOld(old): try: old = '\"%s\"' % old", "% old query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old) response", "\"Would you like to set the skin back to:[/COLOR]\", '[COLOR", "skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui): control.log(\"Deleting Temp Gui", "[] for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml = \"%s/addon.xml\" %", "id: %s\" % skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false')", "set the skin back to: \", '[B] %s [/B]' %", "to %s\" % (item, value)) def defaultSkin(): control.log(\"[Default Skin Check]\")", "= [] for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml = \"%s/addon.xml\"", "folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False if gotoskin: swapSkins(gotoskin) x", "= simplejson.loads(response) if response.has_key('result'): if response['result'].has_key('value'): return response ['result']['value'] except:", "return None def setNew(new, value): try: new = '\"%s\"' %", "= re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" % (folder, str(match[0])))", "control.setSetting('defaultskinignore', 'true') else: control.loga(\"No skins found in addons folder.\"); control.setSetting('defaultskinignore',", "value) def lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme',", "not DEFAULTSKIN == '': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR", "else: for item in scan: value = setting(item.replace('lookandfeel', 'default')) query", "to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)): gotoskin = DEFAULTSKIN gotoname", "%s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to view", "was not reset\"); control.setSetting('defaultskinignore', 'true') else: gotoskin = skinlist[choice] gotoname", "'true'); gotoskin = False if gotoskin: swapSkins(gotoskin) x = 0", "\"id\":1}' % (item, value) response = control.jsonrpc(query) control.log(\"%s restored to", "checkSkin(): control.loga(\"Invalid Skin Check Start\") DEFAULTSKIN = setting('defaultskin') DEFAULTNAME =", "SKIN[5:].title()), \"Would you like to set the skin back to:[/COLOR]\",", "to set the skin back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' % (COLOR1,", "File.\") os.remove(tempgui) control.log(\"[Default Skin Check] End\") def checkSkin(): control.loga(\"Invalid Skin", "+= 1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap", "except: import simplejson ADDONS = os.path.join(control.HOMEPATH, 'addons') def currSkin(): return", "to view a list of avaliable skins?[/COLOR]\"): choice = DIALOG.select(\"Select", "= DIALOG.select(\"Select skin to switch to!\", skinname) if choice ==", "[B]%s[/B]\" % (SKIN[5:].title()), \"Would you like to set the skin", "return None def swapSkins(skin): old = 'lookandfeel.skin' value = skin", "settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" % str(match)) if len(match)", "skinname) control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui): control.log(\"Deleting Temp Gui File.\") os.remove(tempgui)", "'[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)): gotoskin = DEFAULTSKIN gotoname =", "(skinname[0])): gotoskin = skinlist[0] gotoname = skinname[0] else: control.loga(\"Skin was", "lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap Timed Out!') control.loga(\"Invalid Skin Check End\")", "if os.path.exists(tempgui): control.log(\"Deleting Temp Gui File.\") os.remove(tempgui) control.log(\"[Default Skin Check]", "def setNew(new, value): try: new = '\"%s\"' % new value", "new = '\"%s\"' % new value = '\"%s\"' % value", "%s\" % (folder, str(match[0]))) if len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0]))", "set back to [B]%s[/B]\" % (SKIN[5:].title()), \"Would you like to", "x += 1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin", "addf = open(addonxml, 'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 =", "if len(skinlist) > 1: if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems that", "match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s saved to %s\"", "\"id\":1}' % (item) response = control.jsonrpc(query) if not 'error' in", "% str(match)) if len(match) > 0: skinid = match[0] addonxml", "= setting('defaultskinignore') gotoskin = False if not DEFAULTSKIN == '':", "if DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems that the skin has been", "has been set back to [COLOR %s]%s[/COLOR]\" % (COLOR2, COLOR1,", "setNew(new, value) def lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors',", "COLOR1, SKIN[5:].title()), \"Would you like to set the skin back", "control.jsonrpc(query) response = simplejson.loads(response) if response.has_key('result'): if response['result'].has_key('value'): return response", "in response: match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s saved", "file' control.log(\"[Default Skin Check] Skin name: %s\" % skinname) control.log(\"[Default", "control.log(\"Matches: %s\" % str(match)) if len(match) > 0: skinid =", "os.path.join(control.HOMEPATH, 'addons') def currSkin(): return control.skin def getOld(old): try: old", "control.jsonrpc(query) if not 'error' in response: match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel',", "\"id\":1}' % (new, value) response = control.jsonrpc(query) except: pass return", "to [COLOR %s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()), \"Would you like", "-*- coding: UTF-8 -*- import os, re, shutil, time, xbmc", "False if not DEFAULTSKIN == '': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if", "os.remove(tempgui) control.log(\"[Default Skin Check] End\") def checkSkin(): control.loga(\"Invalid Skin Check", "query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new, value) response =", "control.log(\"[Default Skin Check] Skin name: %s\" % skinname) control.log(\"[Default Skin", "setting('defaultskinignore') gotoskin = False if not DEFAULTSKIN == '': if", "\"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new, value) response = control.jsonrpc(query) except: pass", "= '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new, value) response = control.jsonrpc(query)", "simplejson.loads(response) if response.has_key('result'): if response['result'].has_key('value'): return response ['result']['value'] except: pass", "'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do ==", "str(match)) if len(match) > 0: skinid = match[0] addonxml =", "def defaultSkin(): control.log(\"[Default Skin Check]\") tempgui = os.path.join(USERDATAPATH, 'guitemp.xml') gui", "= False else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN = '';", "control.log(\"[Default Skin Check] End\") def checkSkin(): control.loga(\"Invalid Skin Check Start\")", "response ['result']['value'] except: pass return None def setNew(new, value): try:", "except: pass return None def setNew(new, value): try: new =", "if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap Timed Out!') control.loga(\"Invalid", "'no file' control.log(\"[Default Skin Check] Skin name: %s\" % skinname)", "= guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening gui settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg)", "'true') else: control.loga(\"No skins found in addons folder.\"); control.setSetting('defaultskinignore', 'true');", "like to set the skin back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' %", "try: old = '\"%s\"' % old query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s},", "msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) >", "'default'), match[0]) control.log(\"%s saved to %s\" % (item, match[0])) else:", "False else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN = ''; DEFAULTNAME", "\"%s/addon.xml\" % folder if os.path.exists(xml): f = open(xml,mode='r'); g =", "control.log(\"Opening gui settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" % str(match))", "currSkin(): return control.skin def getOld(old): try: old = '\"%s\"' %", "% gui) guif = open(gui, 'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ','');", "'addons') def currSkin(): return control.skin def getOld(old): try: old =", "% value query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new, value)", "back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)): gotoskin = DEFAULTSKIN", "DEFAULTNAME)): gotoskin = DEFAULTSKIN gotoname = DEFAULTNAME else: control.loga(\"Skin was", "been set back to [B]%s[/B]\" % (SKIN[5:].title()), \"Would you like", "'{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new, value) response = control.jsonrpc(query) except:", "= old setNew(new, value) def lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font',", "'error' in response: match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s", "control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s saved to %s\" % (item, match[0]))", "GUISETTINGS if not os.path.exists(gui): return False control.log(\"Reading gui file: %s\"", "as simplejson except: import simplejson ADDONS = os.path.join(control.HOMEPATH, 'addons') def", "%s\" % (item, value)) def defaultSkin(): control.log(\"[Default Skin Check]\") tempgui", "getOld(old) new = old setNew(new, value) def lookandFeelData(do='save'): scan =", "else: skinname = 'no match' else: skinname = 'no file'", "= f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s:", "to!\", skinname) if choice == -1: control.loga(\"Skin was not reset\");", "DEFAULTNAME = '' if DEFAULTSKIN == '': skinname = []", "def swapSkins(skin): old = 'lookandfeel.skin' value = skin current =", "skinname.append(str(match2[0])) else: control.loga(\"ID not found for %s\" % folder) else:", "else: control.loga(\"ID not found for %s\" % folder) if len(skinlist)", "if gotoskin: swapSkins(gotoskin) x = 0 control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\")", "skinlist[choice] gotoname = skinname[choice] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore',", "\"Would you like to set the skin back to: \",", "control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui): control.log(\"Deleting Temp Gui File.\") os.remove(tempgui) control.log(\"[Default", "skinname = 'no file' control.log(\"[Default Skin Check] Skin name: %s\"", "%s [/B]' % (skinname[0])): gotoskin = skinlist[0] gotoname = skinname[0]", "'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do == 'save': for item", "\"[COLOR %s]It seems that the skin has been set back", "'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do == 'save': for item in scan:", "re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" % (folder, str(match[0]))) if len(match) > 0:", "glob.glob(os.path.join(ADDONS, 'skin.*/')): xml = \"%s/addon.xml\" % folder if os.path.exists(xml): f", "gotoskin = skinlist[choice] gotoname = skinname[choice] else: control.loga(\"Skin was not", "reset\"); control.setSetting('defaultskinignore', 'true') else: gotoskin = skinlist[choice] gotoname = skinname[choice]", "that the skin has been set back to [COLOR %s]%s[/COLOR]\"", "to [B]%s[/B]\" % (SKIN[5:].title()), \"Would you like to set the", "len(skinlist) > 1: if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems that the", "'true'); gotoskin = False else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN", "None def swapSkins(skin): old = 'lookandfeel.skin' value = skin current", "control.condVisibility(\"Window.isVisible(yesnodialog)\") and x < 150: x += 1 control.sleep(200) if", "'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2)", "(new, value) response = control.jsonrpc(query) except: pass return None def", "control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap Timed Out!') control.loga(\"Invalid Skin", "',''); guif.close() control.log(\"Opening gui settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\"", "old setNew(new, value) def lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit',", "re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) > 0: skinname = match2[0] else: skinname", "control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui): control.log(\"Deleting Temp", "Check]\") tempgui = os.path.join(USERDATAPATH, 'guitemp.xml') gui = tempgui if os.path.exists(tempgui)", "setting('defaultskin') DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore') gotoskin = False", "query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item) response = control.jsonrpc(query)", "% (item, value) response = control.jsonrpc(query) control.log(\"%s restored to %s\"", "len(match) > 0: skinid = match[0] addonxml = os.path.join(ADDONS, match[0],", "None def setNew(new, value): try: new = '\"%s\"' % new", "Check] Skin id: %s\" % skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname)", "'lookandfeel.skin' value = skin current = getOld(old) new = old", "the skin back to: \", '[B] %s [/B]' % (skinname[0])):", "if len(match) > 0: skinid = match[0] addonxml = os.path.join(ADDONS,", "def lookandFeelData(do='save'): scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom',", "simplejson except: import simplejson ADDONS = os.path.join(control.HOMEPATH, 'addons') def currSkin():", "try: new = '\"%s\"' % new value = '\"%s\"' %", "if len(skinlist) > 0: if len(skinlist) > 1: if DIALOG.yesno(control.AddonTitle,", "x = 0 control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x <", "os.path.exists(tempgui): control.log(\"Deleting Temp Gui File.\") os.remove(tempgui) control.log(\"[Default Skin Check] End\")", "= control.jsonrpc(query) except: pass return None def swapSkins(skin): old =", "the skin has been set back to [COLOR %s]%s[/COLOR]\" %", "tempgui = os.path.join(USERDATAPATH, 'guitemp.xml') gui = tempgui if os.path.exists(tempgui) else", "if DEFAULTSKIN == '': skinname = [] skinlist = []", "control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x < 150: x +=", "else: if DIALOG.yesno(control.AddonTitle, \"It seems that the skin has been", "skin to switch to!\", skinname) if choice == -1: control.loga(\"Skin", "folder) if len(skinlist) > 0: if len(skinlist) > 1: if", "choice == -1: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else:", "setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore') gotoskin = False if not DEFAULTSKIN", "been set back to [COLOR %s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()),", "'guitemp.xml') gui = tempgui if os.path.exists(tempgui) else GUISETTINGS if not", "response = simplejson.loads(response) if response.has_key('result'): if response['result'].has_key('value'): return response ['result']['value']", "resources.lib.modules import control try: import json as simplejson except: import", "Check] End\") def checkSkin(): control.loga(\"Invalid Skin Check Start\") DEFAULTSKIN =", "'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do", "= 0 control.sleep(1000) while not control.condVisibility(\"Window.isVisible(yesnodialog)\") and x < 150:", "was not reset\"); control.setSetting('defaultskinignore', 'true') else: control.loga(\"No skins found in", "'true') else: gotoskin = skinlist[choice] gotoname = skinname[choice] else: control.loga(\"Skin", "control try: import json as simplejson except: import simplejson ADDONS", "f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\"", "os.path.join(ADDONS, match[0], 'addon.xml') if os.path.exists(addonxml): addf = open(addonxml, 'r+') msg2", "= getOld(old) new = old setNew(new, value) def lookandFeelData(do='save'): scan", "(COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to view a list", "= re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" % (folder, str(match[0]))) if len(match) >", "< 150: x += 1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore')", "% new value = '\"%s\"' % value query = '{\"jsonrpc\":\"2.0\",", "not 'error' in response: match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0])", "1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else: control.Notify(control.AddonTitle,'Skin Swap Timed", "skins?[/COLOR]\"): choice = DIALOG.select(\"Select skin to switch to!\", skinname) if", "''; DEFAULTNAME = '' if DEFAULTSKIN == '': skinname =", "time, xbmc from resources.lib.modules import control try: import json as", "match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) > 0: skinname = match2[0]", "1: if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems that the skin has", "that the skin has been set back to [B]%s[/B]\" %", "ADDONS = os.path.join(control.HOMEPATH, 'addons') def currSkin(): return control.skin def getOld(old):", "Start\") DEFAULTSKIN = setting('defaultskin') DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore')", "import os, re, shutil, time, xbmc from resources.lib.modules import control", "= '\"%s\"' % old query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' %", "Skin id: %s\" % skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore',", "for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml = \"%s/addon.xml\" % folder", "UTF-8 -*- import os, re, shutil, time, xbmc from resources.lib.modules", "control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: if DIALOG.yesno(control.AddonTitle, \"It", "skin back to: \", '[B] %s [/B]' % (skinname[0])): gotoskin", "%s\" % skinname) control.log(\"[Default Skin Check] Skin id: %s\" %", "Skin Check Start\") DEFAULTSKIN = setting('defaultskin') DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE", "else: control.loga(\"No skins found in addons folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin", "was not reset\"); control.setSetting('defaultskinignore', 'true') else: if DIALOG.yesno(control.AddonTitle, \"It seems", "= open(addonxml, 'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2)", "= open(gui, 'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening gui", "'false') if os.path.exists(tempgui): control.log(\"Deleting Temp Gui File.\") os.remove(tempgui) control.log(\"[Default Skin", "len(skinlist) > 0: if len(skinlist) > 1: if DIALOG.yesno(control.AddonTitle, \"[COLOR", "return False control.log(\"Reading gui file: %s\" % gui) guif =", "control.setSetting('defaultskinignore', 'true') else: if DIALOG.yesno(control.AddonTitle, \"It seems that the skin", "\"id\":1}' % (old) response = control.jsonrpc(query) response = simplejson.loads(response) if", "skinname) control.log(\"[Default Skin Check] Skin id: %s\" % skinid) control.setSetting('defaultskin',", "not os.path.exists(gui): return False control.log(\"Reading gui file: %s\" % gui)", "'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening gui settings\") match", "addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close() match2 = re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) > 0: skinname", "skin current = getOld(old) new = old setNew(new, value) def", "= 'no match' else: skinname = 'no file' control.log(\"[Default Skin", "name: %s\" % skinname) control.log(\"[Default Skin Check] Skin id: %s\"", "you like to set the skin back to: \", '[B]", "'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if do == 'save': for", "defaultSkin(): control.log(\"[Default Skin Check]\") tempgui = os.path.join(USERDATAPATH, 'guitemp.xml') gui =", "skinname = 'no match' else: skinname = 'no file' control.log(\"[Default", "coding: UTF-8 -*- import os, re, shutil, time, xbmc from", "DIALOG.select(\"Select skin to switch to!\", skinname) if choice == -1:", "value) response = control.jsonrpc(query) control.log(\"%s restored to %s\" % (item,", "DEFAULTSKIN gotoname = DEFAULTNAME else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore',", "control.jsonrpc(query) except: pass return None def swapSkins(skin): old = 'lookandfeel.skin'", "in glob.glob(os.path.join(ADDONS, 'skin.*/')): xml = \"%s/addon.xml\" % folder if os.path.exists(xml):", "seems that the skin has been set back to [B]%s[/B]\"", "response.has_key('result'): if response['result'].has_key('value'): return response ['result']['value'] except: pass return None", "if os.path.exists(tempgui) else GUISETTINGS if not os.path.exists(gui): return False control.log(\"Reading", "choice = DIALOG.select(\"Select skin to switch to!\", skinname) if choice", "else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: if DIALOG.yesno(control.AddonTitle,", "msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening gui settings\") match =", "% folder) else: control.loga(\"ID not found for %s\" % folder)", "150: x += 1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)') lookandFeelData('restore') else:", "guif.close() control.log(\"Opening gui settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" %", "'addon.xml') if os.path.exists(addonxml): addf = open(addonxml, 'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t','');", "%s\" % folder) else: control.loga(\"ID not found for %s\" %", "% folder) if len(skinlist) > 0: if len(skinlist) > 1:", "not reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False else: control.setSetting('defaultskin', '');", "return response ['result']['value'] except: pass return None def setNew(new, value):", "DEFAULTIGNORE = setting('defaultskinignore') gotoskin = False if not DEFAULTSKIN ==", "control.skin def getOld(old): try: old = '\"%s\"' % old query", "= control.jsonrpc(query) response = simplejson.loads(response) if response.has_key('result'): if response['result'].has_key('value'): return", "for item in scan: query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' %", "a list of avaliable skins?[/COLOR]\"): choice = DIALOG.select(\"Select skin to", "guif = open(gui, 'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening", "['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength'] if", "query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item, value) response =", "back to [COLOR %s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()), \"Would you", "skinname[0] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: control.loga(\"No", "f = open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g)", "% (folder, str(match[0]))) if len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else:", "skinname = match2[0] else: skinname = 'no match' else: skinname", "import json as simplejson except: import simplejson ADDONS = os.path.join(control.HOMEPATH,", "End\") def checkSkin(): control.loga(\"Invalid Skin Check Start\") DEFAULTSKIN = setting('defaultskin')", "-1: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: gotoskin =", "gotoname = skinname[0] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true')", "= DEFAULTSKIN gotoname = DEFAULTNAME else: control.loga(\"Skin was not reset\");", "= '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old) response = control.jsonrpc(query) response", "value)) def defaultSkin(): control.log(\"[Default Skin Check]\") tempgui = os.path.join(USERDATAPATH, 'guitemp.xml')", "skins found in addons folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False", "query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old) response = control.jsonrpc(query)", "seems that the skin has been set back to [COLOR", "False if gotoskin: swapSkins(gotoskin) x = 0 control.sleep(1000) while not", "tempgui if os.path.exists(tempgui) else GUISETTINGS if not os.path.exists(gui): return False", "saved to %s\" % (item, match[0])) else: for item in", "control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: control.loga(\"No skins found", "% (COLOR1, DEFAULTNAME)): gotoskin = DEFAULTSKIN gotoname = DEFAULTNAME else:", "''); control.setSetting('defaultskinname', ''); DEFAULTSKIN = ''; DEFAULTNAME = '' if", "addonxml = os.path.join(ADDONS, match[0], 'addon.xml') if os.path.exists(addonxml): addf = open(addonxml,", "control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False else:", "addons folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False if gotoskin: swapSkins(gotoskin)", "else: gotoskin = skinlist[choice] gotoname = skinname[choice] else: control.loga(\"Skin was", "setNew(new, value): try: new = '\"%s\"' % new value =", "skin back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)): gotoskin =", "str(match[0]))) if len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID not", "scan: query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"}, \"id\":1}' % (item) response =", "= setting(item.replace('lookandfeel', 'default')) query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item,", "% (item, match[0])) else: for item in scan: value =", "skin has been set back to [COLOR %s]%s[/COLOR]\" % (COLOR2,", "value = '\"%s\"' % value query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}'", "DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems that the skin has been set", "do == 'save': for item in scan: query = '{\"jsonrpc\":\"2.0\",", "Skin Check] Skin id: %s\" % skinid) control.setSetting('defaultskin', skinid) control.setSetting('defaultskinname',", "control.loga(\"%s: %s\" % (folder, str(match[0]))) if len(match) > 0: skinlist.append(str(match[0]));", "(folder, str(match[0]))) if len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID", "value query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' % (new, value) response", "== '': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems", "== 'save': for item in scan: query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":\"%s\"},", "% (item, value)) def defaultSkin(): control.log(\"[Default Skin Check]\") tempgui =", "''); DEFAULTSKIN = ''; DEFAULTNAME = '' if DEFAULTSKIN ==", "back to [B]%s[/B]\" % (SKIN[5:].title()), \"Would you like to set", "gotoskin = DEFAULTSKIN gotoname = DEFAULTNAME else: control.loga(\"Skin was not", "try: import json as simplejson except: import simplejson ADDONS =", "if not 'error' in response: match = re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'),", "like to view a list of avaliable skins?[/COLOR]\"): choice =", "control.setSetting('defaultskinignore', 'true') else: gotoskin = skinlist[choice] gotoname = skinname[choice] else:", "found for %s\" % folder) else: control.loga(\"ID not found for", "os.path.exists(tempgui) else GUISETTINGS if not os.path.exists(gui): return False control.log(\"Reading gui", "os.path.join(USERDATAPATH, 'guitemp.xml') gui = tempgui if os.path.exists(tempgui) else GUISETTINGS if", "match[0])) else: for item in scan: value = setting(item.replace('lookandfeel', 'default'))", "'skin.*/')): xml = \"%s/addon.xml\" % folder if os.path.exists(xml): f =", "= setting('defaultskin') DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore') gotoskin =", "'{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item, value) response = control.jsonrpc(query) control.log(\"%s", "= '' if DEFAULTSKIN == '': skinname = [] skinlist", "= re.compile('{\"value\":(.+?)}').findall(str(response)) control.setSetting(item.replace('lookandfeel', 'default'), match[0]) control.log(\"%s saved to %s\" %", "found for %s\" % folder) if len(skinlist) > 0: if", "skinid = match[0] addonxml = os.path.join(ADDONS, match[0], 'addon.xml') if os.path.exists(addonxml):", "if len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0])) else: control.loga(\"ID not found", "= re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" % str(match)) if len(match) > 0:", "was not reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False else: control.setSetting('defaultskin',", "control.loga(\"No skins found in addons folder.\"); control.setSetting('defaultskinignore', 'true'); gotoskin =", "else: control.loga(\"ID not found for %s\" % folder) else: control.loga(\"ID", "'default')) query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item, value) response", "= '\"%s\"' % value query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":%s,\"value\":%s}, \"id\":1}' %", "DEFAULTSKIN == '': if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR %s]It", "<reponame>rrosajp/script.ezclean<gh_stars>1-10 # -*- coding: UTF-8 -*- import os, re, shutil,", "match[0] addonxml = os.path.join(ADDONS, match[0], 'addon.xml') if os.path.exists(addonxml): addf =", "f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 = re.compile('<addon.+?name=\"(.+?)\".+?>').findall(g) control.loga(\"%s: %s\" %", "= skinname[0] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else:", "else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true'); gotoskin = False", "gui) guif = open(gui, 'r+') msg = guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close()", "= os.path.join(ADDONS, match[0], 'addon.xml') if os.path.exists(addonxml): addf = open(addonxml, 'r+')", "else: skinname = 'no file' control.log(\"[Default Skin Check] Skin name:", "setting(item.replace('lookandfeel', 'default')) query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}' % (item, value)", "= skinname[choice] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else:", "to: \", '[B] %s [/B]' % (skinname[0])): gotoskin = skinlist[0]", "os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems that the skin", "% (COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to set the", "[COLOR %s]%s[/COLOR]\" % (COLOR2, COLOR1, SKIN[5:].title()), \"Would you like to", "DEFAULTSKIN = ''; DEFAULTNAME = '' if DEFAULTSKIN == '':", "match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches: %s\" % str(match)) if len(match) >", "file: %s\" % gui) guif = open(gui, 'r+') msg =", "if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)): if DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems that the", "to %s\" % (item, match[0])) else: for item in scan:", "= [] skinlist = [] for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')):", "control.setSetting('defaultskinname', skinname) control.setSetting('defaultskinignore', 'false') if os.path.exists(tempgui): control.log(\"Deleting Temp Gui File.\")", "if not os.path.exists(gui): return False control.log(\"Reading gui file: %s\" %", "like to set the skin back to: \", '[B] %s", "skinname[choice] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: if", "avaliable skins?[/COLOR]\"): choice = DIALOG.select(\"Select skin to switch to!\", skinname)", "scan: value = setting(item.replace('lookandfeel', 'default')) query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.SetSettingValue\",\"params\":{\"setting\":\"%s\",\"value\":%s}, \"id\":1}'", "DEFAULTSKIN = setting('defaultskin') DEFAULTNAME = setting('defaultskinname') DEFAULTIGNORE = setting('defaultskinignore') gotoskin", "control.loga(\"Invalid Skin Check Start\") DEFAULTSKIN = setting('defaultskin') DEFAULTNAME = setting('defaultskinname')", "> 0: if len(skinlist) > 1: if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It", "Temp Gui File.\") os.remove(tempgui) control.log(\"[Default Skin Check] End\") def checkSkin():", "for %s\" % folder) else: control.loga(\"ID not found for %s\"", "= skinlist[0] gotoname = skinname[0] else: control.loga(\"Skin was not reset\");", "else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true') else: control.loga(\"No skins", "if DIALOG.yesno(control.AddonTitle, \"It seems that the skin has been set", "= re.compile('<addon.+?ame=\"(.+?)\".+?>').findall(msg2) if len(match2) > 0: skinname = match2[0] else:", "x < 150: x += 1 control.sleep(200) if control.condVisibility(\"Window.isVisible(yesnodialog)\"): control.execute('SendClick(11)')", "gotoskin = False else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN =", "old query = '{\"jsonrpc\":\"2.0\", \"method\":\"Settings.GetSettingValue\",\"params\":{\"setting\":%s}, \"id\":1}' % (old) response =", "control.log(\"Deleting Temp Gui File.\") os.remove(tempgui) control.log(\"[Default Skin Check] End\") def", "DIALOG.yesno(AddonTitle, \"[COLOR %s]It seems that the skin has been set", "if DIALOG.yesno(control.AddonTitle, \"[COLOR %s]It seems that the skin has been", "if response['result'].has_key('value'): return response ['result']['value'] except: pass return None def", "response = control.jsonrpc(query) response = simplejson.loads(response) if response.has_key('result'): if response['result'].has_key('value'):", "open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match = re.compile('<addon.+?id=\"(.+?)\".+?>').findall(g) match2 =", "gotoname = skinname[choice] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore', 'true')", "'lookandfeel.stereostrength'] if do == 'save': for item in scan: query", "if os.path.exists(xml): f = open(xml,mode='r'); g = f.read().replace('\\n','').replace('\\r','').replace('\\t',''); f.close(); match", "not reset\"); control.setSetting('defaultskinignore', 'true') else: if DIALOG.yesno(control.AddonTitle, \"It seems that", "else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN = ''; DEFAULTNAME =", "if os.path.exists(addonxml): addf = open(addonxml, 'r+') msg2 = addf.read().replace('\\n','').replace('\\r','').replace('\\t',''); addf.close()", "guif.read().replace('\\n','').replace('\\r','').replace('\\t','').replace(' ',''); guif.close() control.log(\"Opening gui settings\") match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg) control.log(\"Matches:", "set the skin back to:[/COLOR]\", '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)):", "%s\" % (item, match[0])) else: for item in scan: value", "= ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength']", "> 0: skinname = match2[0] else: skinname = 'no match'", "skinlist[0] gotoname = skinname[0] else: control.loga(\"Skin was not reset\"); control.setSetting('defaultskinignore',", "reset\"); control.setSetting('defaultskinignore', 'true') else: control.loga(\"No skins found in addons folder.\");" ]
[ "dict of properties, such as Format, ValidValues, etc. :type properties:", "len(value) > 64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256) if HAP_PERMISSION_READ in", "and a set of properties, like format, min and max", "\"\"\"Generic exception class for characteristic errors.\"\"\" class Characteristic: \"\"\"Represents a", "class for characteristic errors.\"\"\" class Characteristic: \"\"\"Represents a HAP characteristic,", "be displayed for this characteristic, i.e. the `description` in the", "this characteristic, i.e. the `description` in the HAP representation. :type", "raise ValueError(\"No properties or valid_values specified to override.\") if properties:", "to allow for calling `getter_callback` :return: Current Characteristic Value \"\"\"", "### HAP Format ### HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT = \"int\"", "\"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32:", "= logging.getLogger(__name__) # ### HAP Format ### HAP_FORMAT_BOOL = \"bool\"", "of characteristic. :type type_id: uuid.UUID :param properties: A dict of", "# pylint: disable=not-callable self.setter_callback(value) def notify(self, sender_client_addr=None): \"\"\"Notify clients about", ") elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if len(value) > 64: hap_rep[HAP_REPR_MAX_LEN]", "seealso:: Characteristic.value :param value: The value to assign as this", "the keys `Format`, `Permissions` and `UUID` :type json_dict: dict \"\"\"", "home, e.g. a temperature measuring or a device status. \"\"\"", "float)): error_msg = \"{}: value={} is not a numeric value.\".format(", "PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS = \"Permissions\" PROP_UNIT", "raise ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE, value), value) value = max(self.properties.get(PROP_MIN_VALUE,", "characteristic.\"\"\" return \"<characteristic display_name={} value={} properties={}>\".format( self.display_name, self.value, self.properties )", "\"int\" HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY = \"array\"", "clients about a value change. Sends the value. .. seealso::", "= \"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE =", "HAP representation of this Characteristic. Used for json serialization. :return:", "calling `getter_callback` :return: Current Characteristic Value \"\"\" if self.getter_callback: #", ":param json_dict: Dictionary containing at least the keys `Format`, `Permissions`", "value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if value not in self.properties[PROP_VALID_VALUES].values(): error_msg =", "callback. \"\"\" logger.debug( \"client_update_value: %s to %s from client: %s\",", "= valid_values try: self.value = self.to_valid_value(self.value) except ValueError: self.value =", "a bit of space in the payload. Only include it", "HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS = \"seconds\" # ### Properties ###", "or state, like battery status or the current temperature. Characteristics", "HAP representation. :type display_name: str :param type_id: UUID unique to", "valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if value not in self.properties[PROP_VALID_VALUES].values(): error_msg", "raw value. It is checked if it is a valid", "this Characteristic's value. :type value: Depends on properties[\"Format\"] :param should_notify:", "= ( \"broker\", \"display_name\", \"properties\", \"type_id\", \"value\", \"getter_callback\", \"setter_callback\", \"service\",", "value, should_notify=True): \"\"\"Set the given raw value. It is checked", "display_name: str :param type_id: UUID unique to this type of", "include it # if it has been changed from the", "HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32", "\"properties\", \"type_id\", \"value\", \"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\", ) def", "None def __repr__(self): \"\"\"Return the representation of the characteristic.\"\"\" return", "pylint: disable=not-callable self.setter_callback(value) def notify(self, sender_client_addr=None): \"\"\"Notify clients about a", "things for a HAP characteristic. A Characteristic is the smallest", "\"\"\"Return default value for format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value", "properties. :param display_name: Name that will be displayed for this", "a value change. Sends the value. .. seealso:: accessory.publish ..", "HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } #", "HAP_REPR_DESC (description) is optional and takes up # quite a", "for this characteristic, i.e. the `description` in the HAP representation.", "a characteristic object from a dict. :param json_dict: Dictionary containing", "= str(value)[:256] elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value = bool(value) elif", "= self.get_value() if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k] for", "self, sender_client_addr) # pylint: disable=invalid-name def to_HAP(self): \"\"\"Create a HAP", "def from_dict(cls, name, json_dict, from_loader=False): \"\"\"Initialize a characteristic object from", "HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS", "max(self.properties.get(PROP_MIN_VALUE, value), value) return value def override_properties(self, properties=None, valid_values=None): \"\"\"Override", "from the default loader version if ( not self._loader_display_name or", "bool \"\"\" logger.debug(\"set_value: %s to %s\", self.display_name, value) value =", "are contained in services. Each characteristic has a unique type", "value = max(self.properties.get(PROP_MIN_VALUE, value), value) return value def override_properties(self, properties=None,", "HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value return hap_rep @classmethod def", "\"broker\", \"display_name\", \"properties\", \"type_id\", \"value\", \"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\",", "Valid values will be set to new dictionary. :type valid_values:", "def _get_default_value(self): \"\"\"Return default value for format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return", "\"value\", \"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\", ) def __init__(self, display_name,", "values and valid values. :param properties: Dictionary with values to", "Name that will be displayed for this characteristic, i.e. the", ".. seealso:: accessory.publish .. seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value, self, sender_client_addr)", "self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING:", ":param should_notify: Whether a the change should be sent to", "`Characteristic.setter_callback` You may also define a `setter_callback` on the `Characteristic`.", "== HAP_FORMAT_BOOL: value = bool(value) elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if", "given raw value. It is checked if it is a", "values are required. :type properties: dict :param valid_values: Dictionary with", "def notify(self, sender_client_addr=None): \"\"\"Notify clients about a value change. Sends", "be aborted and an error message will be displayed. `Characteristic.setter_callback`", "\"{}: value={} is an invalid value.\".format( self.display_name, value ) logger.error(error_msg)", "`setter_callback` on the `Characteristic`. This will be called with the", ":return: A HAP representation. :rtype: dict \"\"\" hap_rep = {", "def set_value(self, value, should_notify=True): \"\"\"Set the given raw value. It", "dict \"\"\" hap_rep = { HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM:", "\"float\" HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY = \"dictionary\"", "Characteristics are contained in services. Each characteristic has a unique", "{k: self.properties[k] for k in self.properties.keys() & PROP_NUMERIC} ) if", "PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT]", "Home app. Change self.value to value and call callback. \"\"\"", "self.broker.publish(self.value, self, sender_client_addr) # pylint: disable=invalid-name def to_HAP(self): \"\"\"Create a", "assign as this Characteristic's value. :type value: Depends on properties[\"Format\"]", "in HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k] for k in self.properties.keys() &", "\"\"\"Set the given raw value. It is checked if it", "None self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name = None def __repr__(self): \"\"\"Return", "elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if len(value) > 64: hap_rep[HAP_REPR_MAX_LEN] =", "\"uint32\" HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8 = \"tlv8\"", "self.properties[k] for k in self.properties.keys() & PROP_NUMERIC} ) if PROP_VALID_VALUES", "self.broker = None self.display_name = display_name self.properties = properties self.type_id", "state, like battery status or the current temperature. Characteristics are", "properties[\"Format\"] :param should_notify: Whether a the change should be sent", "HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\",", "`getter_callback` :return: Current Characteristic Value \"\"\" if self.getter_callback: # pylint:", "\"_loader_display_name\", ) def __init__(self, display_name, type_id, properties): \"\"\"Initialise with the", "error message will be displayed. `Characteristic.setter_callback` You may also define", "and self.broker: self.notify() def client_update_value(self, value, sender_client_addr=None): \"\"\"Called from broker", "to this type of characteristic. :type type_id: uuid.UUID :param properties:", "HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS = \"seconds\" #", "if it is a valid value. If not set_value will", "the existing valid_values. Valid values will be set to new", "self.setter_callback: # pylint: disable=not-callable self.setter_callback(value) def notify(self, sender_client_addr=None): \"\"\"Notify clients", "a HAP characteristic. A Characteristic is the smallest unit of", ":type valid_values: dict \"\"\" if not properties and not valid_values:", "\"\"\"Create a HAP representation of this Characteristic. Used for json", "existing properties. Only changed values are required. :type properties: dict", "\"\"\"This is to allow for calling `getter_callback` :return: Current Characteristic", "exception class for characteristic errors.\"\"\" class Characteristic: \"\"\"Represents a HAP", "like battery status or the current temperature. Characteristics are contained", "return self.value def to_valid_value(self, value): \"\"\"Perform validation and conversion to", "smallest unit of the smart home, e.g. a temperature measuring", "\"\"\"Notify clients about a value change. Sends the value. ..", "\"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE = \"percentage\"", "= { HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT],", "will be displayed. `Characteristic.setter_callback` You may also define a `setter_callback`", "specified to override.\") if properties: self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES] =", "Characteristic: \"\"\"Represents a HAP characteristic, the smallest unit of the", "return value def override_properties(self, properties=None, valid_values=None): \"\"\"Override characteristic property values", "ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE, value), value) value = max(self.properties.get(PROP_MIN_VALUE, value),", "others. \"\"\" __slots__ = ( \"broker\", \"display_name\", \"properties\", \"type_id\", \"value\",", "properties and not valid_values: raise ValueError(\"No properties or valid_values specified", "} # HAP_REPR_DESC (description) is optional and takes up #", "HAP_FORMAT_STRING: if len(value) > 64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256) if", "\"seconds\" # ### Properties ### PROP_FORMAT = \"Format\" PROP_MAX_VALUE =", "displayed. `Characteristic.setter_callback` You may also define a `setter_callback` on the", "change should be sent to subscribed clients. Notify will be", "value to assign as this Characteristic's value. :type value: Depends", "self.value = self._get_default_value() def set_value(self, value, should_notify=True): \"\"\"Set the given", "dict :param valid_values: Dictionary with values to override the existing", "is an invalid value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg)", "default value for format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value =", "\"Permissions\" PROP_UNIT = \"unit\" PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE,", "a the change should be sent to subscribed clients. Notify", "### PROP_FORMAT = \"Format\" PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP = \"minStep\"", "{ HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], }", "= \"int\" HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY =", "# HAP_REPR_DESC (description) is optional and takes up # quite", "keys `Format`, `Permissions` and `UUID` :type json_dict: dict \"\"\" type_id", "hap_rep.update( {k: self.properties[k] for k in self.properties.keys() & PROP_NUMERIC} )", "= \"dictionary\" HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32 =", "HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\",", "value = self.get_value() if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k]", "of properties, like format, min and max values, valid values", "format, min and max values, valid values and others. \"\"\"", "should be sent to subscribed clients. Notify will be performed", "Dictionary with values to override the existing properties. Only changed", "valid_values: Dictionary with values to override the existing valid_values. Valid", "= None self.service = None self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name =", "HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } # HAP_REPR_DESC (description) is optional and takes", "the default loader version if ( not self._loader_display_name or self._loader_display_name", "containing at least the keys `Format`, `Permissions` and `UUID` :type", "conversion to valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if value not in", "= uuid_to_hap_type(type_id) self._loader_display_name = None def __repr__(self): \"\"\"Return the representation", "and `UUID` :type json_dict: dict \"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char", "self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE, value),", "unit of the smart home, e.g. a temperature measuring or", "it has been changed from the default loader version if", "will be set to new dictionary. :type valid_values: dict \"\"\"", "= \"Permissions\" PROP_UNIT = \"unit\" PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC =", "value not in self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}: value={} is an", ":param properties: Dictionary with values to override the existing properties.", "\"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\", ) def __init__(self, display_name, type_id,", "\"\"\"Initialize a characteristic object from a dict. :param json_dict: Dictionary", "an invalid value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) elif", "Format, ValidValues, etc. :type properties: dict \"\"\" self.broker = None", "\"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic", "= value self.notify(sender_client_addr) if self.setter_callback: # pylint: disable=not-callable self.setter_callback(value) def", "characteristic errors.\"\"\" class Characteristic: \"\"\"Represents a HAP characteristic, the smallest", ") self.value = value self.notify(sender_client_addr) if self.setter_callback: # pylint: disable=not-callable", "elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value = str(value)[:256] elif self.properties[PROP_FORMAT] ==", "__slots__ = ( \"broker\", \"display_name\", \"properties\", \"type_id\", \"value\", \"getter_callback\", \"setter_callback\",", "the `Characteristic`. This will be called with the value being", "\"client_update_value: %s to %s from client: %s\", self.display_name, value, sender_client_addr,", "self._loader_display_name or self._loader_display_name != self.display_name ): hap_rep[HAP_REPR_DESC] = self.display_name value", "self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING:", "broker for value change in Home app. Change self.value to", "i.e. the `description` in the HAP representation. :type display_name: str", "0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT,", "dict. :param json_dict: Dictionary containing at least the keys `Format`,", "logger.error(error_msg) raise ValueError(error_msg) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value = str(value)[:256]", "if self.properties.get(PROP_VALID_VALUES): if value not in self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}:", "return self.to_valid_value(value) def get_value(self): \"\"\"This is to allow for calling", "str :param type_id: UUID unique to this type of characteristic.", "if ( not self._loader_display_name or self._loader_display_name != self.display_name ): hap_rep[HAP_REPR_DESC]", "0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8:", "\"unit\" PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT)", "pylint: disable=not-callable self.value = self.to_valid_value(value=self.getter_callback()) return self.value def to_valid_value(self, value):", "with values to override the existing properties. Only changed values", "\"\"\" if not properties and not valid_values: raise ValueError(\"No properties", "dict \"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name, type_id, properties=json_dict)", "and max values, valid values and others. \"\"\" __slots__ =", "HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16", "\"service\", \"_uuid_str\", \"_loader_display_name\", ) def __init__(self, display_name, type_id, properties): \"\"\"Initialise", "it # if it has been changed from the default", "called with the value being set as the arg. ..", "%s to %s\", self.display_name, value) value = self.to_valid_value(value) self.value =", ":param display_name: Name that will be displayed for this characteristic,", "= self.to_valid_value(value) self.value = value if should_notify and self.broker: self.notify()", "set as the arg. .. seealso:: Characteristic.value :param value: The", "Only include it # if it has been changed from", "representation. :rtype: dict \"\"\" hap_rep = { HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE:", "a valid value. If not set_value will be aborted and", "notify(self, sender_client_addr=None): \"\"\"Notify clients about a value change. Sends the", "= \"uint8\" HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64 =", "self.value to value and call callback. \"\"\" logger.debug( \"client_update_value: %s", "in the payload. Only include it # if it has", "= sorted( self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if len(value)", "value) return value def override_properties(self, properties=None, valid_values=None): \"\"\"Override characteristic property", "256) if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value return hap_rep", "self.getter_callback: # pylint: disable=not-callable self.value = self.to_valid_value(value=self.getter_callback()) return self.value def", "a dict. :param json_dict: Dictionary containing at least the keys", "payload. Only include it # if it has been changed", "\"maxValue\" PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS = \"Permissions\"", "error_msg = \"{}: value={} is not a numeric value.\".format( self.display_name,", "value. If not set_value will be aborted and an error", "be sent to subscribed clients. Notify will be performed if", "valid_values: raise ValueError(\"No properties or valid_values specified to override.\") if", "logger = logging.getLogger(__name__) # ### HAP Format ### HAP_FORMAT_BOOL =", "characteristic has a unique type UUID and a set of", "self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES] = valid_values try: self.value = self.to_valid_value(self.value)", "= { HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\",", "= \"{}: value={} is not a numeric value.\".format( self.display_name, value", "\"\"\"Called from broker for value change in Home app. Change", "a HAP characteristic, the smallest unit of the smart home.", "\"dictionary\" HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32 = \"uint32\"", "should_notify: bool \"\"\" logger.debug(\"set_value: %s to %s\", self.display_name, value) value", "= \"uint32\" HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8 =", "logger.error(error_msg) raise ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE, value), value) value =", "\"lux\" HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS = \"seconds\" # ### Properties", "`description` in the HAP representation. :type display_name: str :param type_id:", ".util import hap_type_to_uuid, uuid_to_hap_type logger = logging.getLogger(__name__) # ### HAP", "with the given properties. :param display_name: Name that will be", "battery status or the current temperature. Characteristics are contained in", "# ### Properties ### PROP_FORMAT = \"Format\" PROP_MAX_VALUE = \"maxValue\"", ":param value: The value to assign as this Characteristic's value.", "in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value return hap_rep @classmethod def from_dict(cls,", "( \"broker\", \"display_name\", \"properties\", \"type_id\", \"value\", \"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\",", "properties: dict :param valid_values: Dictionary with values to override the", "set of properties, like format, min and max values, valid", "type_id: UUID unique to this type of characteristic. :type type_id:", "\"bool\" HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING = \"string\"", "# ### HAP Format ### HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT =", "contained in services. Each characteristic has a unique type UUID", "the smallest unit of the smart home, e.g. a temperature", "self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } # HAP_REPR_DESC", "\"\"\" import logging from pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT,", "seealso:: accessory.publish .. seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value, self, sender_client_addr) #", "value if should_notify and self.broker: self.notify() def client_update_value(self, value, sender_client_addr=None):", "self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value = str(value)[:256] elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL:", "self.properties ) def _get_default_value(self): \"\"\"Return default value for format.\"\"\" if", "in the HAP representation. :type display_name: str :param type_id: UUID", "to %s from client: %s\", self.display_name, value, sender_client_addr, ) self.value", "PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic exception", "and valid values. :param properties: Dictionary with values to override", "### HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT = \"float\"", "self.properties = properties self.type_id = type_id self.value = self._get_default_value() self.getter_callback", "value. :type value: Depends on properties[\"Format\"] :param should_notify: Whether a", "None self.setter_callback = None self.service = None self._uuid_str = uuid_to_hap_type(type_id)", "bit of space in the payload. Only include it #", "HAP_FORMAT_NUMERICS: if not isinstance(value, (int, float)): error_msg = \"{}: value={}", "import logging from pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID,", "def __init__(self, display_name, type_id, properties): \"\"\"Initialise with the given properties.", "return min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def get_value(self): \"\"\"This", "properties: A dict of properties, such as Format, ValidValues, etc.", "characteristic is some measurement or state, like battery status or", "`UUID` :type json_dict: dict \"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char =", "as this Characteristic's value. :type value: Depends on properties[\"Format\"] :param", "value ) logger.error(error_msg) raise ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE, value), value)", "type UUID and a set of properties, like format, min", "unique type UUID and a set of properties, like format,", "value for format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]]", "self.display_name = display_name self.properties = properties self.type_id = type_id self.value", "be called with the value being set as the arg.", "seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value, self, sender_client_addr) # pylint: disable=invalid-name def", "logger.debug( \"client_update_value: %s to %s from client: %s\", self.display_name, value,", "def __repr__(self): \"\"\"Return the representation of the characteristic.\"\"\" return \"<characteristic", "should_notify=True): \"\"\"Set the given raw value. It is checked if", "to subscribed clients. Notify will be performed if the broker", "\"\"\" self.broker = None self.display_name = display_name self.properties = properties", "hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if", "HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0,", "\"\"\" self.broker.publish(self.value, self, sender_client_addr) # pylint: disable=invalid-name def to_HAP(self): \"\"\"Create", "accessory.publish .. seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value, self, sender_client_addr) # pylint:", "PROP_UNIT = \"unit\" PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE,", "if not properties and not valid_values: raise ValueError(\"No properties or", "HAP Units ### HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX", "`Permissions` and `UUID` :type json_dict: dict \"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\"))", "values. :param properties: Dictionary with values to override the existing", "an error message will be displayed. `Characteristic.setter_callback` You may also", "change in Home app. Change self.value to value and call", "PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS = \"Permissions\" PROP_UNIT = \"unit\" PROP_VALID_VALUES", ") def __init__(self, display_name, type_id, properties): \"\"\"Initialise with the given", "It is checked if it is a valid value. If", "`Characteristic`. This will be called with the value being set", "self.to_valid_value(self.value) except ValueError: self.value = self._get_default_value() def set_value(self, value, should_notify=True):", "quite a bit of space in the payload. Only include", "self._loader_display_name = None def __repr__(self): \"\"\"Return the representation of the", "to new dictionary. :type valid_values: dict \"\"\" if not properties", "( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE,", "sender_client_addr, ) self.value = value self.notify(sender_client_addr) if self.setter_callback: # pylint:", "properties self.type_id = type_id self.value = self._get_default_value() self.getter_callback = None", "properties, such as Format, ValidValues, etc. :type properties: dict \"\"\"", "and conversion to valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if value not", "PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class", "HAP_FORMAT_UINT64, ) # ### HAP Units ### HAP_UNIT_ARC_DEGREE = \"arcdegrees\"", "on properties[\"Format\"] :param should_notify: Whether a the change should be", "this Characteristic. Used for json serialization. :return: A HAP representation.", "self.setter_callback(value) def notify(self, sender_client_addr=None): \"\"\"Notify clients about a value change.", "min(self.properties.get(PROP_MAX_VALUE, value), value) value = max(self.properties.get(PROP_MIN_VALUE, value), value) return value", "from_dict(cls, name, json_dict, from_loader=False): \"\"\"Initialize a characteristic object from a", "HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS", "not in self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}: value={} is an invalid", "is the smallest unit of the smart home, e.g. a", ") if PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values() )", "the current temperature. Characteristics are contained in services. Each characteristic", "= hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name, type_id, properties=json_dict) if from_loader: char._loader_display_name", "value. It is checked if it is a valid value.", "error_msg = \"{}: value={} is an invalid value.\".format( self.display_name, value", "self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value return hap_rep @classmethod def from_dict(cls, name,", "has been changed from the default loader version if (", "has a unique type UUID and a set of properties,", "\"\"\" logger.debug( \"client_update_value: %s to %s from client: %s\", self.display_name,", "properties={}>\".format( self.display_name, self.value, self.properties ) def _get_default_value(self): \"\"\"Return default value", "HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16,", "if self.getter_callback: # pylint: disable=not-callable self.value = self.to_valid_value(value=self.getter_callback()) return self.value", "for value change in Home app. Change self.value to value", "HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from .util import hap_type_to_uuid, uuid_to_hap_type logger", "HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE", "least the keys `Format`, `Permissions` and `UUID` :type json_dict: dict", "properties: Dictionary with values to override the existing properties. Only", "return \"<characteristic display_name={} value={} properties={}>\".format( self.display_name, self.value, self.properties ) def", "not properties and not valid_values: raise ValueError(\"No properties or valid_values", "for calling `getter_callback` :return: Current Characteristic Value \"\"\" if self.getter_callback:", "try: self.value = self.to_valid_value(self.value) except ValueError: self.value = self._get_default_value() def", "> 64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256) if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]:", "HAP_FORMAT_BOOL: value = bool(value) elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if not", "HAP characteristic, the smallest unit of the smart home. A", "will be performed if the broker is set. :type should_notify:", "64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256) if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE]", "if the broker is set. :type should_notify: bool \"\"\" logger.debug(\"set_value:", "valid_values. Valid values will be set to new dictionary. :type", "self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name = None def __repr__(self): \"\"\"Return the", "self.notify() def client_update_value(self, value, sender_client_addr=None): \"\"\"Called from broker for value", "\"string\" HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8 = \"uint8\"", "\"minStep\" PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS = \"Permissions\" PROP_UNIT = \"unit\"", "( not self._loader_display_name or self._loader_display_name != self.display_name ): hap_rep[HAP_REPR_DESC] =", "properties: self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES] = valid_values try: self.value =", "json_dict: dict \"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name, type_id,", "properties=json_dict) if from_loader: char._loader_display_name = ( # pylint: disable=protected-access char.display_name", "not a numeric value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg)", "value. .. seealso:: accessory.publish .. seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value, self,", "HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from .util", "class Characteristic: \"\"\"Represents a HAP characteristic, the smallest unit of", "0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8:", "self.properties.get(PROP_VALID_VALUES): if value not in self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}: value={}", "if value not in self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}: value={} is", "self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if not isinstance(value, (int, float)): error_msg =", "status. \"\"\" import logging from pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC,", "self.service = None self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name = None def", "HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\",", "properties=None, valid_values=None): \"\"\"Override characteristic property values and valid values. :param", "Whether a the change should be sent to subscribed clients.", "json_dict: Dictionary containing at least the keys `Format`, `Permissions` and", "def client_update_value(self, value, sender_client_addr=None): \"\"\"Called from broker for value change", "being set as the arg. .. seealso:: Characteristic.value :param value:", "max values, valid values and others. \"\"\" __slots__ = (", "= cls(name, type_id, properties=json_dict) if from_loader: char._loader_display_name = ( #", "min and max values, valid values and others. \"\"\" __slots__", "\"type_id\", \"value\", \"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\", ) def __init__(self,", "get_value(self): \"\"\"This is to allow for calling `getter_callback` :return: Current", "the smart home. A HAP characteristic is some measurement or", "Sends the value. .. seealso:: accessory.publish .. seealso:: accessory_driver.publish \"\"\"", "\"data\" HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL: False, HAP_FORMAT_INT:", "All things for a HAP characteristic. A Characteristic is the", "HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA", "%s\", self.display_name, value) value = self.to_valid_value(value) self.value = value if", "= \"tlv8\" HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT:", "value): \"\"\"Perform validation and conversion to valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES):", "serialization. :return: A HAP representation. :rtype: dict \"\"\" hap_rep =", "uuid.UUID :param properties: A dict of properties, such as Format,", "self.properties[PROP_FORMAT], } # HAP_REPR_DESC (description) is optional and takes up", "invalid value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) elif self.properties[PROP_FORMAT]", "smart home, e.g. a temperature measuring or a device status.", "dictionary. :type valid_values: dict \"\"\" if not properties and not", "= self._get_default_value() def set_value(self, value, should_notify=True): \"\"\"Set the given raw", "HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL:", "if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def", "Depends on properties[\"Format\"] :param should_notify: Whether a the change should", "Units ### HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX =", "if self.setter_callback: # pylint: disable=not-callable self.setter_callback(value) def notify(self, sender_client_addr=None): \"\"\"Notify", "at least the keys `Format`, `Permissions` and `UUID` :type json_dict:", "HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) # ### HAP Units ###", "representation. :type display_name: str :param type_id: UUID unique to this", "as Format, ValidValues, etc. :type properties: dict \"\"\" self.broker =", "not self._loader_display_name or self._loader_display_name != self.display_name ): hap_rep[HAP_REPR_DESC] = self.display_name", "= \"float\" HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY =", "self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value = bool(value) elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS:", "a unique type UUID and a set of properties, like", "with the value being set as the arg. .. seealso::", "Current Characteristic Value \"\"\" if self.getter_callback: # pylint: disable=not-callable self.value", "\"\"\" __slots__ = ( \"broker\", \"display_name\", \"properties\", \"type_id\", \"value\", \"getter_callback\",", "arg. .. seealso:: Characteristic.value :param value: The value to assign", "Change self.value to value and call callback. \"\"\" logger.debug( \"client_update_value:", "import ( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES,", "logger.debug(\"set_value: %s to %s\", self.display_name, value) value = self.to_valid_value(value) self.value", "### Properties ### PROP_FORMAT = \"Format\" PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP", "errors.\"\"\" class Characteristic: \"\"\"Represents a HAP characteristic, the smallest unit", "value: The value to assign as this Characteristic's value. :type", "display_name self.properties = properties self.type_id = type_id self.value = self._get_default_value()", "override the existing valid_values. Valid values will be set to", "characteristic property values and valid values. :param properties: Dictionary with", "HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from .util import hap_type_to_uuid, uuid_to_hap_type", "and others. \"\"\" __slots__ = ( \"broker\", \"display_name\", \"properties\", \"type_id\",", "hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name, type_id, properties=json_dict) if from_loader: char._loader_display_name =", "\"\", } HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32,", "HAP characteristic is some measurement or state, like battery status", "status or the current temperature. Characteristics are contained in services.", "from_loader: char._loader_display_name = ( # pylint: disable=protected-access char.display_name ) return", ":rtype: dict \"\"\" hap_rep = { HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str,", "None self.display_name = display_name self.properties = properties self.type_id = type_id", "the value. .. seealso:: accessory.publish .. seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value,", "is set. :type should_notify: bool \"\"\" logger.debug(\"set_value: %s to %s\",", "temperature measuring or a device status. \"\"\" import logging from", "name, json_dict, from_loader=False): \"\"\"Initialize a characteristic object from a dict.", "to override the existing valid_values. Valid values will be set", "A HAP characteristic is some measurement or state, like battery", "value={} is not a numeric value.\".format( self.display_name, value ) logger.error(error_msg)", "to value and call callback. \"\"\" logger.debug( \"client_update_value: %s to", "hap_rep @classmethod def from_dict(cls, name, json_dict, from_loader=False): \"\"\"Initialize a characteristic", "json_dict, from_loader=False): \"\"\"Initialize a characteristic object from a dict. :param", "if it has been changed from the default loader version", "= \"celsius\" HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS =", "== HAP_FORMAT_STRING: if len(value) > 64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256)", "values to override the existing properties. Only changed values are", "0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16:", "# pylint: disable=not-callable self.value = self.to_valid_value(value=self.getter_callback()) return self.value def to_valid_value(self,", "object from a dict. :param json_dict: Dictionary containing at least", "\"\"\"Initialise with the given properties. :param display_name: Name that will", "%s\", self.display_name, value, sender_client_addr, ) self.value = value self.notify(sender_client_addr) if", "from a dict. :param json_dict: Dictionary containing at least the", "is checked if it is a valid value. If not", "characteristic. :type type_id: uuid.UUID :param properties: A dict of properties,", "valid_values: self.properties[PROP_VALID_VALUES] = valid_values try: self.value = self.to_valid_value(self.value) except ValueError:", "= (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic exception class", "characteristic. A Characteristic is the smallest unit of the smart", "self.broker: self.notify() def client_update_value(self, value, sender_client_addr=None): \"\"\"Called from broker for", "of this Characteristic. Used for json serialization. :return: A HAP", "value), value) return value def override_properties(self, properties=None, valid_values=None): \"\"\"Override characteristic", "of the smart home, e.g. a temperature measuring or a", "the smart home, e.g. a temperature measuring or a device", "the HAP representation. :type display_name: str :param type_id: UUID unique", "Characteristic.value :param value: The value to assign as this Characteristic's", "values will be set to new dictionary. :type valid_values: dict", "disable=not-callable self.setter_callback(value) def notify(self, sender_client_addr=None): \"\"\"Notify clients about a value", "value={} properties={}>\".format( self.display_name, self.value, self.properties ) def _get_default_value(self): \"\"\"Return default", "HAP Format ### HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT", "HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT,", "self.value = self.to_valid_value(self.value) except ValueError: self.value = self._get_default_value() def set_value(self,", "the given raw value. It is checked if it is", "elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if not isinstance(value, (int, float)): error_msg", ":param properties: A dict of properties, such as Format, ValidValues,", "HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from .util import hap_type_to_uuid,", "HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING:", ") logger.error(error_msg) raise ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE, value), value) value", "Notify will be performed if the broker is set. :type", "allow for calling `getter_callback` :return: Current Characteristic Value \"\"\" if", "%s to %s from client: %s\", self.display_name, value, sender_client_addr, )", "\"\", HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8,", ":type should_notify: bool \"\"\" logger.debug(\"set_value: %s to %s\", self.display_name, value)", "displayed for this characteristic, i.e. the `description` in the HAP", "in Home app. Change self.value to value and call callback.", "= min(self.properties.get(PROP_MAX_VALUE, value), value) value = max(self.properties.get(PROP_MIN_VALUE, value), value) return", "given properties. :param display_name: Name that will be displayed for", "HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } # HAP_REPR_DESC (description) is optional", "the value being set as the arg. .. seealso:: Characteristic.value", "optional and takes up # quite a bit of space", "@classmethod def from_dict(cls, name, json_dict, from_loader=False): \"\"\"Initialize a characteristic object", "`Format`, `Permissions` and `UUID` :type json_dict: dict \"\"\" type_id =", "HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from .util import", "CharacteristicError(Exception): \"\"\"Generic exception class for characteristic errors.\"\"\" class Characteristic: \"\"\"Represents", "0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\", }", ".. seealso:: Characteristic.value :param value: The value to assign as", "HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS", "to %s\", self.display_name, value) value = self.to_valid_value(value) self.value = value", "sorted( self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if len(value) >", "cls(name, type_id, properties=json_dict) if from_loader: char._loader_display_name = ( # pylint:", "the given properties. :param display_name: Name that will be displayed", "self.getter_callback = None self.setter_callback = None self.service = None self._uuid_str", "broker is set. :type should_notify: bool \"\"\" logger.debug(\"set_value: %s to", ".. seealso:: accessory_driver.publish \"\"\" self.broker.publish(self.value, self, sender_client_addr) # pylint: disable=invalid-name", "HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from", "= \"uint16\" HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA =", "\"display_name\", \"properties\", \"type_id\", \"value\", \"getter_callback\", \"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\", )", "up # quite a bit of space in the payload.", "and takes up # quite a bit of space in", "HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) # ### HAP Units", "is not a numeric value.\".format( self.display_name, value ) logger.error(error_msg) raise", "a numeric value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) value", "display_name, type_id, properties): \"\"\"Initialise with the given properties. :param display_name:", "\"\"\"Return the representation of the characteristic.\"\"\" return \"<characteristic display_name={} value={}", "as the arg. .. seealso:: Characteristic.value :param value: The value", "performed if the broker is set. :type should_notify: bool \"\"\"", "self.properties.keys() & PROP_NUMERIC} ) if PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES] =", "to override the existing properties. Only changed values are required.", "PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS", "the broker is set. :type should_notify: bool \"\"\" logger.debug(\"set_value: %s", "not set_value will be aborted and an error message will", "values and others. \"\"\" __slots__ = ( \"broker\", \"display_name\", \"properties\",", "if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k] for k in", "value), value) value = max(self.properties.get(PROP_MIN_VALUE, value), value) return value def", "self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if len(value) > 64:", "= properties self.type_id = type_id self.value = self._get_default_value() self.getter_callback =", "\"minValue\" PROP_PERMISSIONS = \"Permissions\" PROP_UNIT = \"unit\" PROP_VALID_VALUES = \"ValidValues\"", "char._loader_display_name = ( # pylint: disable=protected-access char.display_name ) return char", "= \"maxValue\" PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS =", "Characteristic's value. :type value: Depends on properties[\"Format\"] :param should_notify: Whether", "self.setter_callback = None self.service = None self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name", "be set to new dictionary. :type valid_values: dict \"\"\" if", "accessory_driver.publish \"\"\" self.broker.publish(self.value, self, sender_client_addr) # pylint: disable=invalid-name def to_HAP(self):", "measurement or state, like battery status or the current temperature.", "of space in the payload. Only include it # if", "): hap_rep[HAP_REPR_DESC] = self.display_name value = self.get_value() if self.properties[PROP_FORMAT] in", "hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256) if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] =", "such as Format, ValidValues, etc. :type properties: dict \"\"\" self.broker", "display_name={} value={} properties={}>\".format( self.display_name, self.value, self.properties ) def _get_default_value(self): \"\"\"Return", "some measurement or state, like battery status or the current", "= None self.setter_callback = None self.service = None self._uuid_str =", "# if it has been changed from the default loader", "\"\"\"Represents a HAP characteristic, the smallest unit of the smart", "ValidValues, etc. :type properties: dict \"\"\" self.broker = None self.display_name", "for a HAP characteristic. A Characteristic is the smallest unit", "HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0,", "= \"unit\" PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP,", "value def override_properties(self, properties=None, valid_values=None): \"\"\"Override characteristic property values and", "app. Change self.value to value and call callback. \"\"\" logger.debug(", "device status. \"\"\" import logging from pyhap.const import ( HAP_PERMISSION_READ,", "self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } # HAP_REPR_DESC (description) is", "(description) is optional and takes up # quite a bit", "\"uint64\" HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS = {", ":type json_dict: dict \"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name,", "representation of the characteristic.\"\"\" return \"<characteristic display_name={} value={} properties={}>\".format( self.display_name,", "_get_default_value(self): \"\"\"Return default value for format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values())", "values to override the existing valid_values. Valid values will be", "unique to this type of characteristic. :type type_id: uuid.UUID :param", "that will be displayed for this characteristic, i.e. the `description`", ":return: Current Characteristic Value \"\"\" if self.getter_callback: # pylint: disable=not-callable", "value change. Sends the value. .. seealso:: accessory.publish .. seealso::", "HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0,", "value) value = max(self.properties.get(PROP_MIN_VALUE, value), value) return value def override_properties(self,", "= display_name self.properties = properties self.type_id = type_id self.value =", ") from .util import hap_type_to_uuid, uuid_to_hap_type logger = logging.getLogger(__name__) #", "uuid_to_hap_type logger = logging.getLogger(__name__) # ### HAP Format ### HAP_FORMAT_BOOL", "valid values and others. \"\"\" __slots__ = ( \"broker\", \"display_name\",", "be displayed. `Characteristic.setter_callback` You may also define a `setter_callback` on", "HAP_REPR_VALUE, ) from .util import hap_type_to_uuid, uuid_to_hap_type logger = logging.getLogger(__name__)", "define a `setter_callback` on the `Characteristic`. This will be called", "= ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) #", "the `description` in the HAP representation. :type display_name: str :param", "value and call callback. \"\"\" logger.debug( \"client_update_value: %s to %s", "aborted and an error message will be displayed. `Characteristic.setter_callback` You", "message will be displayed. `Characteristic.setter_callback` You may also define a", "hap_rep[HAP_REPR_VALUE] = value return hap_rep @classmethod def from_dict(cls, name, json_dict,", ":param valid_values: Dictionary with values to override the existing valid_values.", "= None def __repr__(self): \"\"\"Return the representation of the characteristic.\"\"\"", "\"\"\" if self.getter_callback: # pylint: disable=not-callable self.value = self.to_valid_value(value=self.getter_callback()) return", "unit of the smart home. A HAP characteristic is some", "You may also define a `setter_callback` on the `Characteristic`. This", "the arg. .. seealso:: Characteristic.value :param value: The value to", "A HAP representation. :rtype: dict \"\"\" hap_rep = { HAP_REPR_IID:", "== HAP_FORMAT_STRING: value = str(value)[:256] elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value", "in self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values() ) elif self.properties[PROP_FORMAT] ==", "Characteristic. Used for json serialization. :return: A HAP representation. :rtype:", "value, sender_client_addr, ) self.value = value self.notify(sender_client_addr) if self.setter_callback: #", ":param type_id: UUID unique to this type of characteristic. :type", "value being set as the arg. .. seealso:: Characteristic.value :param", "\"\"\" All things for a HAP characteristic. A Characteristic is", "value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) value = min(self.properties.get(PROP_MAX_VALUE,", "takes up # quite a bit of space in the", "properties or valid_values specified to override.\") if properties: self.properties.update(properties) if", "override_properties(self, properties=None, valid_values=None): \"\"\"Override characteristic property values and valid values.", "\"uint16\" HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA = \"data\"", "= \"lux\" HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS = \"seconds\" # ###", "a set of properties, like format, min and max values,", "value = bool(value) elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if not isinstance(value,", "self.to_valid_value(value) self.value = value if should_notify and self.broker: self.notify() def", "self.value = value if should_notify and self.broker: self.notify() def client_update_value(self,", "= \"array\" HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16 =", "The value to assign as this Characteristic's value. :type value:", "str(value)[:256] elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value = bool(value) elif self.properties[PROP_FORMAT]", "min(len(value), 256) if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value return", "display_name: Name that will be displayed for this characteristic, i.e.", "like format, min and max values, valid values and others.", "validation and conversion to valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if value", "\"\"\"Override characteristic property values and valid values. :param properties: Dictionary", "will be displayed for this characteristic, i.e. the `description` in", "a HAP representation of this Characteristic. Used for json serialization.", "logging.getLogger(__name__) # ### HAP Format ### HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT", "self.value = self._get_default_value() self.getter_callback = None self.setter_callback = None self.service", "type of characteristic. :type type_id: uuid.UUID :param properties: A dict", "type_id: uuid.UUID :param properties: A dict of properties, such as", "self._get_default_value() def set_value(self, value, should_notify=True): \"\"\"Set the given raw value.", "\"\"\" hap_rep = { HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS],", "### HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\" HAP_UNIT_LUX = \"lux\"", "valid_values: dict \"\"\" if not properties and not valid_values: raise", "valid values. :param properties: Dictionary with values to override the", "\"\"\"Perform validation and conversion to valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if", "HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0,", "clients. Notify will be performed if the broker is set.", "current temperature. Characteristics are contained in services. Each characteristic has", "= max(self.properties.get(PROP_MIN_VALUE, value), value) return value def override_properties(self, properties=None, valid_values=None):", "it is a valid value. If not set_value will be", "char = cls(name, type_id, properties=json_dict) if from_loader: char._loader_display_name = (", "the characteristic.\"\"\" return \"<characteristic display_name={} value={} properties={}>\".format( self.display_name, self.value, self.properties", "default loader version if ( not self._loader_display_name or self._loader_display_name !=", "set_value(self, value, should_notify=True): \"\"\"Set the given raw value. It is", "HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) # ### HAP", "not valid_values: raise ValueError(\"No properties or valid_values specified to override.\")", "self.properties[PROP_VALID_VALUES] = valid_values try: self.value = self.to_valid_value(self.value) except ValueError: self.value", "def to_HAP(self): \"\"\"Create a HAP representation of this Characteristic. Used", "been changed from the default loader version if ( not", "self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k] for k in self.properties.keys()", "self._loader_display_name != self.display_name ): hap_rep[HAP_REPR_DESC] = self.display_name value = self.get_value()", "measuring or a device status. \"\"\" import logging from pyhap.const", "= min(len(value), 256) if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value", "a temperature measuring or a device status. \"\"\" import logging", "self.display_name, self.value, self.properties ) def _get_default_value(self): \"\"\"Return default value for", "ValueError(\"No properties or valid_values specified to override.\") if properties: self.properties.update(properties)", "to_HAP(self): \"\"\"Create a HAP representation of this Characteristic. Used for", "value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) elif self.properties[PROP_FORMAT] ==", "type_id, properties=json_dict) if from_loader: char._loader_display_name = ( # pylint: disable=protected-access", ":type properties: dict \"\"\" self.broker = None self.display_name = display_name", "\"array\" HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16 = \"uint16\"", "value ) logger.error(error_msg) raise ValueError(error_msg) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value", "home. A HAP characteristic is some measurement or state, like", "self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } # HAP_REPR_DESC (description) is optional and", ") # ### HAP Units ### HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS", "is a valid value. If not set_value will be aborted", "k in self.properties.keys() & PROP_NUMERIC} ) if PROP_VALID_VALUES in self.properties:", "new dictionary. :type valid_values: dict \"\"\" if not properties and", "if properties: self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES] = valid_values try: self.value", "\"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA:", "or valid_values specified to override.\") if properties: self.properties.update(properties) if valid_values:", "= \"string\" HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8 =", "HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) # ### HAP Units ### HAP_UNIT_ARC_DEGREE =", "= \"bool\" HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING =", "self.value = self.to_valid_value(value=self.getter_callback()) return self.value def to_valid_value(self, value): \"\"\"Perform validation", "except ValueError: self.value = self._get_default_value() def set_value(self, value, should_notify=True): \"\"\"Set", "0, HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS =", "HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) from .util import hap_type_to_uuid, uuid_to_hap_type logger =", "= \"minValue\" PROP_PERMISSIONS = \"Permissions\" PROP_UNIT = \"unit\" PROP_VALID_VALUES =", "of properties, such as Format, ValidValues, etc. :type properties: dict", "representation of this Characteristic. Used for json serialization. :return: A", "HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64 = \"uint64\" HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8", "a device status. \"\"\" import logging from pyhap.const import (", "\"\"\" logger.debug(\"set_value: %s to %s\", self.display_name, value) value = self.to_valid_value(value)", "value) value = self.to_valid_value(value) self.value = value if should_notify and", "Used for json serialization. :return: A HAP representation. :rtype: dict", "sender_client_addr=None): \"\"\"Called from broker for value change in Home app.", "\"<characteristic display_name={} value={} properties={}>\".format( self.display_name, self.value, self.properties ) def _get_default_value(self):", "HAP characteristic. A Characteristic is the smallest unit of the", "is optional and takes up # quite a bit of", "in self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}: value={} is an invalid value.\".format(", "changed values are required. :type properties: dict :param valid_values: Dictionary", "HAP representation. :rtype: dict \"\"\" hap_rep = { HAP_REPR_IID: self.broker.iid_manager.get_iid(self),", "disable=not-callable self.value = self.to_valid_value(value=self.getter_callback()) return self.value def to_valid_value(self, value): \"\"\"Perform", "\"celsius\" HAP_UNIT_LUX = \"lux\" HAP_UNIT_PERCENTAGE = \"percentage\" HAP_UNIT_SECONDS = \"seconds\"", "in services. Each characteristic has a unique type UUID and", "sent to subscribed clients. Notify will be performed if the", "from client: %s\", self.display_name, value, sender_client_addr, ) self.value = value", "def get_value(self): \"\"\"This is to allow for calling `getter_callback` :return:", "value, sender_client_addr=None): \"\"\"Called from broker for value change in Home", "value = str(value)[:256] elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value = bool(value)", "PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic exception class for characteristic", "self.display_name, value, sender_client_addr, ) self.value = value self.notify(sender_client_addr) if self.setter_callback:", "valid_values=None): \"\"\"Override characteristic property values and valid values. :param properties:", "ValueError(error_msg) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value = str(value)[:256] elif self.properties[PROP_FORMAT]", "\"{}: value={} is not a numeric value.\".format( self.display_name, value )", "property values and valid values. :param properties: Dictionary with values", "Characteristic is the smallest unit of the smart home, e.g.", "from pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM,", "the change should be sent to subscribed clients. Notify will", "space in the payload. Only include it # if it", "with values to override the existing valid_values. Valid values will", "or self._loader_display_name != self.display_name ): hap_rep[HAP_REPR_DESC] = self.display_name value =", "characteristic, i.e. the `description` in the HAP representation. :type display_name:", "logging from pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN,", "= None self.display_name = display_name self.properties = properties self.type_id =", "not isinstance(value, (int, float)): error_msg = \"{}: value={} is not", "self.display_name value = self.get_value() if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update( {k:", "also define a `setter_callback` on the `Characteristic`. This will be", "and an error message will be displayed. `Characteristic.setter_callback` You may", "& PROP_NUMERIC} ) if PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted(", "client: %s\", self.display_name, value, sender_client_addr, ) self.value = value self.notify(sender_client_addr)", "self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def get_value(self):", "of the characteristic.\"\"\" return \"<characteristic display_name={} value={} properties={}>\".format( self.display_name, self.value,", "( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) # ###", "HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k] for k in self.properties.keys() & PROP_NUMERIC}", "False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY:", "= self.to_valid_value(self.value) except ValueError: self.value = self._get_default_value() def set_value(self, value,", "if should_notify and self.broker: self.notify() def client_update_value(self, value, sender_client_addr=None): \"\"\"Called", "to override.\") if properties: self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES] = valid_values", "from .util import hap_type_to_uuid, uuid_to_hap_type logger = logging.getLogger(__name__) # ###", "for k in self.properties.keys() & PROP_NUMERIC} ) if PROP_VALID_VALUES in", "json serialization. :return: A HAP representation. :rtype: dict \"\"\" hap_rep", "= \"uint64\" HAP_FORMAT_DATA = \"data\" HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS =", "Format ### HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT =", "value: Depends on properties[\"Format\"] :param should_notify: Whether a the change", "self.notify(sender_client_addr) if self.setter_callback: # pylint: disable=not-callable self.setter_callback(value) def notify(self, sender_client_addr=None):", "\"setter_callback\", \"service\", \"_uuid_str\", \"_loader_display_name\", ) def __init__(self, display_name, type_id, properties):", "override the existing properties. Only changed values are required. :type", "PROP_FORMAT = \"Format\" PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE", "= value return hap_rep @classmethod def from_dict(cls, name, json_dict, from_loader=False):", "# ### HAP Units ### HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS =", "type_id, properties): \"\"\"Initialise with the given properties. :param display_name: Name", "valid_values specified to override.\") if properties: self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES]", "properties. Only changed values are required. :type properties: dict :param", "value={} is an invalid value.\".format( self.display_name, value ) logger.error(error_msg) raise", "= HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def get_value(self): \"\"\"This is to allow", "HAP_FORMAT_UINT64: 0, HAP_FORMAT_DATA: \"\", HAP_FORMAT_TLV8: \"\", } HAP_FORMAT_NUMERICS = (", "disable=invalid-name def to_HAP(self): \"\"\"Create a HAP representation of this Characteristic.", "\"tlv8\" HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0,", "If not set_value will be aborted and an error message", "= value if should_notify and self.broker: self.notify() def client_update_value(self, value,", "Dictionary with values to override the existing valid_values. Valid values", "set to new dictionary. :type valid_values: dict \"\"\" if not", "about a value change. Sends the value. .. seealso:: accessory.publish", "values, valid values and others. \"\"\" __slots__ = ( \"broker\",", "sender_client_addr) # pylint: disable=invalid-name def to_HAP(self): \"\"\"Create a HAP representation", "hap_rep = { HAP_REPR_IID: self.broker.iid_manager.get_iid(self), HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT:", "or the current temperature. Characteristics are contained in services. Each", "\"percentage\" HAP_UNIT_SECONDS = \"seconds\" # ### Properties ### PROP_FORMAT =", "Only changed values are required. :type properties: dict :param valid_values:", "HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY", "and not valid_values: raise ValueError(\"No properties or valid_values specified to", "# pylint: disable=invalid-name def to_HAP(self): \"\"\"Create a HAP representation of", "elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value = bool(value) elif self.properties[PROP_FORMAT] in", "checked if it is a valid value. If not set_value", "HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE, HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, )", "\"uint8\" HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64 = \"uint64\"", "the existing properties. Only changed values are required. :type properties:", "or a device status. \"\"\" import logging from pyhap.const import", "__repr__(self): \"\"\"Return the representation of the characteristic.\"\"\" return \"<characteristic display_name={}", "change. Sends the value. .. seealso:: accessory.publish .. seealso:: accessory_driver.publish", "= None self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name = None def __repr__(self):", "if len(value) > 64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value), 256) if HAP_PERMISSION_READ", "!= self.display_name ): hap_rep[HAP_REPR_DESC] = self.display_name value = self.get_value() if", "\"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0, HAP_FORMAT_UINT32: 0, HAP_FORMAT_UINT64:", "type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name, type_id, properties=json_dict) if from_loader:", "etc. :type properties: dict \"\"\" self.broker = None self.display_name =", "PROP_NUMERIC} ) if PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values()", "= \"minStep\" PROP_MIN_VALUE = \"minValue\" PROP_PERMISSIONS = \"Permissions\" PROP_UNIT =", "the representation of the characteristic.\"\"\" return \"<characteristic display_name={} value={} properties={}>\".format(", "client_update_value(self, value, sender_client_addr=None): \"\"\"Called from broker for value change in", "required. :type properties: dict :param valid_values: Dictionary with values to", "self.value, self.properties ) def _get_default_value(self): \"\"\"Return default value for format.\"\"\"", "will be called with the value being set as the", "### HAP Units ### HAP_UNIT_ARC_DEGREE = \"arcdegrees\" HAP_UNIT_CELSIUS = \"celsius\"", "properties): \"\"\"Initialise with the given properties. :param display_name: Name that", "to_valid_value(self, value): \"\"\"Perform validation and conversion to valid value.\"\"\" if", "type_id self.value = self._get_default_value() self.getter_callback = None self.setter_callback = None", "should_notify: Whether a the change should be sent to subscribed", "if from_loader: char._loader_display_name = ( # pylint: disable=protected-access char.display_name )", "self.to_valid_value(value) def get_value(self): \"\"\"This is to allow for calling `getter_callback`", "uuid_to_hap_type(type_id) self._loader_display_name = None def __repr__(self): \"\"\"Return the representation of", "HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, )", "in HAP_FORMAT_NUMERICS: if not isinstance(value, (int, float)): error_msg = \"{}:", "HAP_FORMAT_UINT8 = \"uint8\" HAP_FORMAT_UINT16 = \"uint16\" HAP_FORMAT_UINT32 = \"uint32\" HAP_FORMAT_UINT64", "value change in Home app. Change self.value to value and", "properties: dict \"\"\" self.broker = None self.display_name = display_name self.properties", "PROP_PERMISSIONS = \"Permissions\" PROP_UNIT = \"unit\" PROP_VALID_VALUES = \"ValidValues\" PROP_NUMERIC", "= \"Format\" PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE =", "value = self.to_valid_value(value) self.value = value if should_notify and self.broker:", "set_value will be aborted and an error message will be", ":type display_name: str :param type_id: UUID unique to this type", "HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64, ) # ### HAP Units ### HAP_UNIT_ARC_DEGREE", "is some measurement or state, like battery status or the", "the smallest unit of the smart home. A HAP characteristic", "Value \"\"\" if self.getter_callback: # pylint: disable=not-callable self.value = self.to_valid_value(value=self.getter_callback())", ") def _get_default_value(self): \"\"\"Return default value for format.\"\"\" if self.properties.get(PROP_VALID_VALUES):", "from broker for value change in Home app. Change self.value", "%s from client: %s\", self.display_name, value, sender_client_addr, ) self.value =", "min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def get_value(self): \"\"\"This is", "import hap_type_to_uuid, uuid_to_hap_type logger = logging.getLogger(__name__) # ### HAP Format", "HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY = \"dictionary\" HAP_FORMAT_UINT8", "self.get_value() if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update( {k: self.properties[k] for k", "None self.service = None self._uuid_str = uuid_to_hap_type(type_id) self._loader_display_name = None", "HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING = \"string\" HAP_FORMAT_ARRAY = \"array\" HAP_FORMAT_DICTIONARY", "# quite a bit of space in the payload. Only", "self.properties[PROP_VALID_VALUES].values(): error_msg = \"{}: value={} is an invalid value.\".format( self.display_name,", "hap_type_to_uuid, uuid_to_hap_type logger = logging.getLogger(__name__) # ### HAP Format ###", "\"\"\" type_id = hap_type_to_uuid(json_dict.pop(\"UUID\")) char = cls(name, type_id, properties=json_dict) if", "self.value def to_valid_value(self, value): \"\"\"Perform validation and conversion to valid", "HAP_UNIT_SECONDS = \"seconds\" # ### Properties ### PROP_FORMAT = \"Format\"", "def to_valid_value(self, value): \"\"\"Perform validation and conversion to valid value.\"\"\"", "= \"seconds\" # ### Properties ### PROP_FORMAT = \"Format\" PROP_MAX_VALUE", "isinstance(value, (int, float)): error_msg = \"{}: value={} is not a", "characteristic object from a dict. :param json_dict: Dictionary containing at", "format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value)", "HAP_REPR_TYPE: self._uuid_str, HAP_REPR_PERM: self.properties[PROP_PERMISSIONS], HAP_REPR_FORMAT: self.properties[PROP_FORMAT], } # HAP_REPR_DESC (description)", "override.\") if properties: self.properties.update(properties) if valid_values: self.properties[PROP_VALID_VALUES] = valid_values try:", "should_notify and self.broker: self.notify() def client_update_value(self, value, sender_client_addr=None): \"\"\"Called from", "for format.\"\"\" if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return", "UUID unique to this type of characteristic. :type type_id: uuid.UUID", "pylint: disable=invalid-name def to_HAP(self): \"\"\"Create a HAP representation of this", "bool(value) elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if not isinstance(value, (int, float)):", "Properties ### PROP_FORMAT = \"Format\" PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP =", "A dict of properties, such as Format, ValidValues, etc. :type", "a `setter_callback` on the `Characteristic`. This will be called with", "= \"{}: value={} is an invalid value.\".format( self.display_name, value )", "{ HAP_FORMAT_BOOL: False, HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY:", "HAP_FORMAT_INT: 0, HAP_FORMAT_FLOAT: 0.0, HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\",", "= self.display_name value = self.get_value() if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: hap_rep.update(", "in self.properties.keys() & PROP_NUMERIC} ) if PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES]", "A Characteristic is the smallest unit of the smart home,", "Each characteristic has a unique type UUID and a set", "PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic exception class for characteristic errors.\"\"\" class", "= self.to_valid_value(value=self.getter_callback()) return self.value def to_valid_value(self, value): \"\"\"Perform validation and", "= \"data\" HAP_FORMAT_TLV8 = \"tlv8\" HAP_FORMAT_DEFAULTS = { HAP_FORMAT_BOOL: False,", "smart home. A HAP characteristic is some measurement or state,", "def override_properties(self, properties=None, valid_values=None): \"\"\"Override characteristic property values and valid", "= bool(value) elif self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS: if not isinstance(value, (int,", "HAP_FORMAT_STRING: \"\", HAP_FORMAT_ARRAY: \"\", HAP_FORMAT_DICTIONARY: \"\", HAP_FORMAT_UINT8: 0, HAP_FORMAT_UINT16: 0,", "set. :type should_notify: bool \"\"\" logger.debug(\"set_value: %s to %s\", self.display_name,", "pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, HAP_REPR_FORMAT, HAP_REPR_IID, HAP_REPR_MAX_LEN, HAP_REPR_PERM, HAP_REPR_TYPE,", "self.display_name, value) value = self.to_valid_value(value) self.value = value if should_notify", "class CharacteristicError(Exception): \"\"\"Generic exception class for characteristic errors.\"\"\" class Characteristic:", "if not isinstance(value, (int, float)): error_msg = \"{}: value={} is", "HAP_FORMAT_STRING: value = str(value)[:256] elif self.properties[PROP_FORMAT] == HAP_FORMAT_BOOL: value =", "to assign as this Characteristic's value. :type value: Depends on", "self._get_default_value() self.getter_callback = None self.setter_callback = None self.service = None", "self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: if len(value) > 64: hap_rep[HAP_REPR_MAX_LEN] = min(len(value),", "<filename>pyhap/characteristic.py \"\"\" All things for a HAP characteristic. A Characteristic", "= type_id self.value = self._get_default_value() self.getter_callback = None self.setter_callback =", "valid value. If not set_value will be aborted and an", "characteristic, the smallest unit of the smart home. A HAP", "the payload. Only include it # if it has been", "value = min(self.properties.get(PROP_MAX_VALUE, value), value) value = max(self.properties.get(PROP_MIN_VALUE, value), value)", "This will be called with the value being set as", "of the smart home. A HAP characteristic is some measurement", "call callback. \"\"\" logger.debug( \"client_update_value: %s to %s from client:", "value return hap_rep @classmethod def from_dict(cls, name, json_dict, from_loader=False): \"\"\"Initialize", ":type value: Depends on properties[\"Format\"] :param should_notify: Whether a the", "subscribed clients. Notify will be performed if the broker is", "Dictionary containing at least the keys `Format`, `Permissions` and `UUID`", "return hap_rep @classmethod def from_dict(cls, name, json_dict, from_loader=False): \"\"\"Initialize a", "dict \"\"\" if not properties and not valid_values: raise ValueError(\"No", "numeric value.\".format( self.display_name, value ) logger.error(error_msg) raise ValueError(error_msg) value =", "valid_values try: self.value = self.to_valid_value(self.value) except ValueError: self.value = self._get_default_value()", "if HAP_PERMISSION_READ in self.properties[PROP_PERMISSIONS]: hap_rep[HAP_REPR_VALUE] = value return hap_rep @classmethod", "if valid_values: self.properties[PROP_VALID_VALUES] = valid_values try: self.value = self.to_valid_value(self.value) except", "on the `Characteristic`. This will be called with the value", "} HAP_FORMAT_NUMERICS = ( HAP_FORMAT_INT, HAP_FORMAT_FLOAT, HAP_FORMAT_UINT8, HAP_FORMAT_UINT16, HAP_FORMAT_UINT32, HAP_FORMAT_UINT64,", "properties, like format, min and max values, valid values and", ":type properties: dict :param valid_values: Dictionary with values to override", "(PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic exception class for", "PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception): \"\"\"Generic exception class for characteristic errors.\"\"\"", "__init__(self, display_name, type_id, properties): \"\"\"Initialise with the given properties. :param", "be performed if the broker is set. :type should_notify: bool", "changed from the default loader version if ( not self._loader_display_name", "will be aborted and an error message will be displayed.", "\"Format\" PROP_MAX_VALUE = \"maxValue\" PROP_MIN_STEP = \"minStep\" PROP_MIN_VALUE = \"minValue\"", "\"_uuid_str\", \"_loader_display_name\", ) def __init__(self, display_name, type_id, properties): \"\"\"Initialise with", "sender_client_addr=None): \"\"\"Notify clients about a value change. Sends the value.", "= \"percentage\" HAP_UNIT_SECONDS = \"seconds\" # ### Properties ### PROP_FORMAT", "is to allow for calling `getter_callback` :return: Current Characteristic Value", "value = HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def get_value(self): \"\"\"This is to", "= \"ValidValues\" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) class CharacteristicError(Exception):", "(int, float)): error_msg = \"{}: value={} is not a numeric", "version if ( not self._loader_display_name or self._loader_display_name != self.display_name ):", "smallest unit of the smart home. A HAP characteristic is", "dict \"\"\" self.broker = None self.display_name = display_name self.properties =", "are required. :type properties: dict :param valid_values: Dictionary with values", "HAP_FORMAT_BOOL = \"bool\" HAP_FORMAT_INT = \"int\" HAP_FORMAT_FLOAT = \"float\" HAP_FORMAT_STRING", "services. Each characteristic has a unique type UUID and a", "= self._get_default_value() self.getter_callback = None self.setter_callback = None self.service =", "Characteristic Value \"\"\" if self.getter_callback: # pylint: disable=not-callable self.value =", ":type type_id: uuid.UUID :param properties: A dict of properties, such", "hap_rep[HAP_REPR_DESC] = self.display_name value = self.get_value() if self.properties[PROP_FORMAT] in HAP_FORMAT_NUMERICS:", "self.to_valid_value(value=self.getter_callback()) return self.value def to_valid_value(self, value): \"\"\"Perform validation and conversion", "existing valid_values. Valid values will be set to new dictionary.", "for json serialization. :return: A HAP representation. :rtype: dict \"\"\"", "self.display_name ): hap_rep[HAP_REPR_DESC] = self.display_name value = self.get_value() if self.properties[PROP_FORMAT]", "and call callback. \"\"\" logger.debug( \"client_update_value: %s to %s from", "e.g. a temperature measuring or a device status. \"\"\" import", "to valid value.\"\"\" if self.properties.get(PROP_VALID_VALUES): if value not in self.properties[PROP_VALID_VALUES].values():", "self.type_id = type_id self.value = self._get_default_value() self.getter_callback = None self.setter_callback", "may also define a `setter_callback` on the `Characteristic`. This will", "loader version if ( not self._loader_display_name or self._loader_display_name != self.display_name", "value self.notify(sender_client_addr) if self.setter_callback: # pylint: disable=not-callable self.setter_callback(value) def notify(self,", "UUID and a set of properties, like format, min and", "ValueError: self.value = self._get_default_value() def set_value(self, value, should_notify=True): \"\"\"Set the", "HAP_FORMAT_DEFAULTS[self.properties[PROP_FORMAT]] return self.to_valid_value(value) def get_value(self): \"\"\"This is to allow for", "self.value = value self.notify(sender_client_addr) if self.setter_callback: # pylint: disable=not-callable self.setter_callback(value)", "from_loader=False): \"\"\"Initialize a characteristic object from a dict. :param json_dict:", "for characteristic errors.\"\"\" class Characteristic: \"\"\"Represents a HAP characteristic, the", "temperature. Characteristics are contained in services. Each characteristic has a", "this type of characteristic. :type type_id: uuid.UUID :param properties: A", "raise ValueError(error_msg) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value = str(value)[:256] elif", ") logger.error(error_msg) raise ValueError(error_msg) elif self.properties[PROP_FORMAT] == HAP_FORMAT_STRING: value =", "if PROP_VALID_VALUES in self.properties: hap_rep[HAP_REPR_VALID_VALUES] = sorted( self.properties[PROP_VALID_VALUES].values() ) elif" ]
[ "pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ), data=dict( type=dataset_type,", "name not in use, but have defined one to run", "# name not in use, but have defined one to", "vqa_cfg = dict( train_txt_dbs=[ data_root + 'vqa_train.db', data_root + 'vqa_trainval.db',", "+ 'coco_val2014/', ans2label_file=data_root + 'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10, num_bb=36,", "val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root + 'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10,", "test_datasets = ['minival'] # name not in use, but have", "drop_last=True, size_multiple=8, ), data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ), ) test_data", "to run vqa_cfg = dict( train_txt_dbs=[ data_root + 'vqa_train.db', data_root", "), ) test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE,", "size_multiple=8, ), pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ), ) post_processor", "pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ), ) post_processor = dict(", "max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480, # 5120, val_batch_size=40960, # 10240, )", "num_bb=36, train_batch_size=20480, # 5120, val_batch_size=40960, # 10240, ) BUCKET_SIZE =", "10240, ) BUCKET_SIZE = 8192 train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4,", "dataset_type = 'UNITER_VqaDataset' data_root = '/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train'] test_datasets", "but have defined one to run vqa_cfg = dict( train_txt_dbs=[", "'coco_val2014', data_root + 'vg/', ], val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root +", "= 8192 train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler',", "workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ), pin_memory=True, data=dict(", "+ 'vqa_vg.db', ], train_img_dbs=[ data_root + 'coco_train2014/', data_root + 'coco_val2014',", "not in use, but have defined one to run vqa_cfg", "run vqa_cfg = dict( train_txt_dbs=[ data_root + 'vqa_train.db', data_root +", "<filename>configs/_base_/datasets/uniter/vqa_dataset_uniter.py<gh_stars>10-100 dataset_type = 'UNITER_VqaDataset' data_root = '/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train']", "type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ), ) test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4,", "+ 'vg/', ], val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root", "['train'] test_datasets = ['minival'] # name not in use, but", "+ 'vqa_trainval.db', data_root + 'vqa_vg.db', ], train_img_dbs=[ data_root + 'coco_train2014/',", "dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ),", "samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ),", "= '/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train'] test_datasets = ['minival'] # name", "batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ), data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ), )", "drop_last=False, size_multiple=8, ), pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ), )", "val_batch_size=40960, # 10240, ) BUCKET_SIZE = 8192 train_data = dict(", "data_root + 'coco_train2014/', data_root + 'coco_val2014', data_root + 'vg/', ],", "+ 'vqa_devval.db', val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root + 'ans2label.json', max_txt_len=60, conf_th=0.2,", "ans2label_file=data_root + 'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480, #", "data_root + 'vqa_trainval.db', data_root + 'vqa_vg.db', ], train_img_dbs=[ data_root +", "batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ), data=dict( type=dataset_type, datacfg=vqa_cfg,", "= 'UNITER_VqaDataset' data_root = '/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train'] test_datasets =", "= dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8,", "bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ), pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False,", "], train_img_dbs=[ data_root + 'coco_train2014/', data_root + 'coco_val2014', data_root +", "defined one to run vqa_cfg = dict( train_txt_dbs=[ data_root +", "), pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ), ) post_processor =", "'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480, # 5120, val_batch_size=40960,", "data_root + 'vqa_train.db', data_root + 'vqa_trainval.db', data_root + 'vqa_vg.db', ],", "train_or_val=True, ), ) test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler',", "data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ), ) post_processor = dict( type='Evaluator',", "'vqa_train.db', data_root + 'vqa_trainval.db', data_root + 'vqa_vg.db', ], train_img_dbs=[ data_root", "type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ), data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True,", "+ 'coco_val2014', data_root + 'vg/', ], val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root", "5120, val_batch_size=40960, # 10240, ) BUCKET_SIZE = 8192 train_data =", "= ['minival'] # name not in use, but have defined", "+ 'vqa_train.db', data_root + 'vqa_trainval.db', data_root + 'vqa_vg.db', ], train_img_dbs=[", "train_txt_dbs=[ data_root + 'vqa_train.db', data_root + 'vqa_trainval.db', data_root + 'vqa_vg.db',", "one to run vqa_cfg = dict( train_txt_dbs=[ data_root + 'vqa_train.db',", "['minival'] # name not in use, but have defined one", "+ 'coco_train2014/', data_root + 'coco_val2014', data_root + 'vg/', ], val_txt_db=data_root", "), data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ), ) test_data = dict(", "'coco_train2014/', data_root + 'coco_val2014', data_root + 'vg/', ], val_txt_db=data_root +", "train_batch_size=20480, # 5120, val_batch_size=40960, # 10240, ) BUCKET_SIZE = 8192", "# 10240, ) BUCKET_SIZE = 8192 train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'],", "'vqa_vg.db', ], train_img_dbs=[ data_root + 'coco_train2014/', data_root + 'coco_val2014', data_root", "data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ), ) test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'],", "'/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train'] test_datasets = ['minival'] # name not", "'vqa_devval.db', val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root + 'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100,", "conf_th=0.2, max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480, # 5120, val_batch_size=40960, # 10240,", "type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ), ) post_processor = dict( type='Evaluator', metrics=[dict(type='UNITER_AccuracyMetric')],", "data_root + 'vg/', ], val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root + 'coco_val2014/',", "max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480, # 5120, val_batch_size=40960, #", "'vg/', ], val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root +", ") test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'],", "datacfg=vqa_cfg, train_or_val=True, ), ) test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict(", "test_data = dict( samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False,", "data_root + 'vqa_vg.db', ], train_img_dbs=[ data_root + 'coco_train2014/', data_root +", "min_bb=10, num_bb=36, train_batch_size=20480, # 5120, val_batch_size=40960, # 10240, ) BUCKET_SIZE", "dict( train_txt_dbs=[ data_root + 'vqa_train.db', data_root + 'vqa_trainval.db', data_root +", "'coco_val2014/', ans2label_file=data_root + 'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480,", "+ 'ans2label.json', max_txt_len=60, conf_th=0.2, max_bb=100, min_bb=10, num_bb=36, train_batch_size=20480, # 5120,", "= ['train'] test_datasets = ['minival'] # name not in use,", "datacfg=vqa_cfg, train_or_val=False, ), ) post_processor = dict( type='Evaluator', metrics=[dict(type='UNITER_AccuracyMetric')], dataset_converters=[dict(type='UNITER_DatasetConverter')],", "= dict( train_txt_dbs=[ data_root + 'vqa_train.db', data_root + 'vqa_trainval.db', data_root", "have defined one to run vqa_cfg = dict( train_txt_dbs=[ data_root", "'UNITER_VqaDataset' data_root = '/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train'] test_datasets = ['minival']", "= dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True,", ") BUCKET_SIZE = 8192 train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True,", "'vqa_trainval.db', data_root + 'vqa_vg.db', ], train_img_dbs=[ data_root + 'coco_train2014/', data_root", "in use, but have defined one to run vqa_cfg =", "train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'],", "type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ), pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg,", "samples_per_gpu=vqa_cfg['val_batch_size'], workers_per_gpu=4, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ), pin_memory=True,", "], val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root + 'ans2label.json',", "dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8,", "train_or_val=False, ), ) post_processor = dict( type='Evaluator', metrics=[dict(type='UNITER_AccuracyMetric')], dataset_converters=[dict(type='UNITER_DatasetConverter')], )", "batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ), pin_memory=True, data=dict( type=dataset_type,", "BUCKET_SIZE = 8192 train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict(", "val_txt_db=data_root + 'vqa_devval.db', val_img_db=data_root + 'coco_val2014/', ans2label_file=data_root + 'ans2label.json', max_txt_len=60,", "train_img_dbs=[ data_root + 'coco_train2014/', data_root + 'coco_val2014', data_root + 'vg/',", "size_multiple=8, ), data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ), ) test_data =", "data_root = '/home/datasets/mix_data/UNITER/VQA/' train_datasets = ['train'] test_datasets = ['minival'] #", "train_datasets = ['train'] test_datasets = ['minival'] # name not in", "workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ), data=dict(", "use, but have defined one to run vqa_cfg = dict(", "8192 train_data = dict( samples_per_gpu=vqa_cfg['train_batch_size'], workers_per_gpu=4, pin_memory=True, batch_sampler=dict( type='TokenBucketSampler', bucket_size=BUCKET_SIZE,", "# 5120, val_batch_size=40960, # 10240, ) BUCKET_SIZE = 8192 train_data", "batch_size=vqa_cfg['val_batch_size'], drop_last=False, size_multiple=8, ), pin_memory=True, data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=False, ),", "bucket_size=BUCKET_SIZE, batch_size=vqa_cfg['train_batch_size'], drop_last=True, size_multiple=8, ), data=dict( type=dataset_type, datacfg=vqa_cfg, train_or_val=True, ),", "data_root + 'coco_val2014', data_root + 'vg/', ], val_txt_db=data_root + 'vqa_devval.db'," ]
[ "= [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls),", "import static from django.contrib import admin from django.urls import path,", "from django.views.generic import TemplateView urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/',", "import settings from django.conf.urls.static import static from django.contrib import admin", "TemplateView urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')),", "path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('core.api.urls')), ] if", "path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('core.api.urls')),", "django.views.generic import TemplateView urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')),", "django.conf import settings from django.conf.urls.static import static from django.contrib import", "[ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/',", "include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('core.api.urls')), ] if settings.DEBUG: urlpatterns +=", "import admin from django.urls import path, include, re_path from django.views.generic", "admin.site.urls), path('api/', include('core.api.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)", "from django.urls import path, include, re_path from django.views.generic import TemplateView", "+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG: urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]", "re_path from django.views.generic import TemplateView urlpatterns = [ path('api-auth/', include('rest_framework.urls')),", "include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('core.api.urls')), ]", "admin from django.urls import path, include, re_path from django.views.generic import", "import TemplateView urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/',", "from django.conf import settings from django.conf.urls.static import static from django.contrib", "urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/',", "include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('core.api.urls')), ] if settings.DEBUG:", "static from django.contrib import admin from django.urls import path, include,", "path('rest-auth/registration/', include('rest_auth.registration.urls')), path('admin/', admin.site.urls), path('api/', include('core.api.urls')), ] if settings.DEBUG: urlpatterns", "] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG:", "settings from django.conf.urls.static import static from django.contrib import admin from", "if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG: urlpatterns", "from django.conf.urls.static import static from django.contrib import admin from django.urls", "from django.contrib import admin from django.urls import path, include, re_path", "django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns", "include, re_path from django.views.generic import TemplateView urlpatterns = [ path('api-auth/',", "urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG: urlpatterns += [re_path(r'^.*',", "path, include, re_path from django.views.generic import TemplateView urlpatterns = [", "django.conf.urls.static import static from django.contrib import admin from django.urls import", "settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG: urlpatterns +=", "django.contrib import admin from django.urls import path, include, re_path from", "import path, include, re_path from django.views.generic import TemplateView urlpatterns =", "path('api/', include('core.api.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if", "path('admin/', admin.site.urls), path('api/', include('core.api.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,", "include('core.api.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not" ]
[ "self.in_smtp_host = QLineEdit() self.in_smtp_port = QLineEdit() self.in_smtp_user = QLineEdit() self.in_smtp_password", "self.in_smtp_password = QLineEdit() self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test = QLineEdit() self.btn_smtp_save", "labels = [\"寄件人 :\", \"寄件人名稱 :\", \" 是否加入附件 :\", \"附件名稱", "server.sendmail import Smtp from server.client import Client from email import", "sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if self.data_smtp else Smtp()", "self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml", "self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) #", "[\"SMTP HOST :\", \"SMTP PORT :\", \"SMTP 帳號 :\", \"SMTP", "2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1, 2) def display_logs(self): self.data_temp_logs =", "def open_excel(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel", "主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db", "#!/bin/bash # -*- coding: UTF-8 -*- # 基本控件都在这里面 from PyQt5.QtWebEngineWidgets", "'使用者群組':'user_group', '使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText() content = self.in_logs_data.text() row_num =", "qApp.quit() def main(): app = QApplication(sys.argv) gui = MailserverUi() gui.show()", "= QGridLayout() self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html", "1, 4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1, 7) self.right_layout.addWidget(self.in_edit_annex,", "else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self): # sender 是发送信号的对象", "0, 1, 3) # 主要功能查詢 self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data,", "org_files else file_name obj.setText(all_files) def print_html(self, index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText())", "SSL :\", \" 測試信件內容 :\"] for i, label in enumerate(labels):", "3, 12, 8) # 右側物件: sendmail self.in_eml_type = QLineEdit() self.in_eml_template", "True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j", "update eml self.in_edit_sender = QLineEdit() self.in_edit_sender_name = QLineEdit() self.cb_edit_annex =", "self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in range(row_num): row_data = list(self.data_logs[i].values())", "except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__() def get_items_from_layout(self, layout):", "if error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else: QMessageBox.information(self, 'Success!',", "1, 4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1, 1) self.right_layout.addWidget(self.in_recipient_group,", "0, 1, 3) self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1, 3) self.left_layout.addWidget(self.btn_download_logs, 7,", "= QLabel(label) self.right_layout.addWidget(self.label, i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0,", "try: if self.data_smtp: mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg", "PyQt5.QtCore import Qt, QDateTime from pyqtgraph import GraphicsLayoutWidget, setConfigOption, setConfigOptions", "= QLineEdit() self.in_db_user = QLineEdit() self.in_db_password = QLineEdit() self.in_db_database =", "client = Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file, user_group, mail_excel, annex_file,", "mail_excel, sm, db, annex=annex_file, url=url) sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!',", "eml_file, user_group, mail_excel, sm, db, annex=annex_file, url=url) sm.close() db.__disconnect__() QMessageBox.information(self,", "\"收件人資料 :\", '附件資料 :',\"設定排程 :\"] for i, label in enumerate(labels):", "super().__init__() self.resize(400,100) self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0,", "<EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet(", "1, 3) # 主要功能查詢 self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1,", "for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self, obj): file_name, _", "self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in range(row_num): row_data = list(self.data_logs[i].values()) for", "4, 4, 1, 6) self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1, 1) self.right_layout.addWidget(self.in_scheduler,", "self.sub_win.show() else: QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP 資料!', QMessageBox.Ok) def send_test(self):", "label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type,", "item) def logs_download(self): if self.data_temp_logs: try: file_path, _ = QFileDialog.getSaveFileName(self,", "# 在右邊新增物件 labels = [\"資料庫 HOST :\", \"資料庫 PORT :\",", "4, 1, 7) self.right_layout.addWidget(self.btn_db_save, 6, 9, 1, 2) def display_update_eml(self):", "obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word Files (*.doc", "QCheckBox('是') self.in_edit_annex = QLineEdit() self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject", "QMessageBox.Ok) else: QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!',", "創建主部件的網格佈局 self.main_layout = QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget", "\" 是否加入附件 :\", \"附件名稱 :\", \"主旨 :\", \"內容 :\"] for", "int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db else Database() insert_send_mail(eml_type, eml_file,", "Qt, QDateTime from pyqtgraph import GraphicsLayoutWidget, setConfigOption, setConfigOptions import qdarkstyle,", "db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok)", "QMessageBox.Ok) def quit_act(self): # sender 是发送信号的对象 sender = self.sender() print(sender.text()", "row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item)", "= self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText() if not any(header[:3]) or not", "1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_port, 1, 4,", "QWidget() # 創建主部件的網格佈局 self.main_layout = QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) #", "import insert_send_mail from server.database import Database from server.sendmail import Smtp", "return self.data_temp_logs = [] self.tbw_logs.setRowCount(0) # header = {'郵件類型':'type', '郵件主旨':'subject',", "mail_excel, annex_file, url, my_time) QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok) else: sm", "self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked { height: 12px; border: 1px", "= self.get_items_from_layout(self.right_layout) for item in items: if type(item) == type(QLineEdit()):", "self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 = QGridLayout() self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0)", "3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name,", "in range(row_num): row_data = list(self.data_logs[i].values()) for j in range(col_num): temp_data", "QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i, j, item) except: QMessageBox.warning(self, 'Failed!',", "收件人群組 :\", \"收件人資料 :\", '附件資料 :',\"設定排程 :\"] for i, label", "self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self): header, msg = [], ''", "QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) print(data) def clear_layout(self, layout):", "Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1,", "int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()],", "self.in_logs_data.text() row_num = len(self.data_logs) col_num = len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num)", "7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1, 7) self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1,", "not file_name: return header, html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0])", "from server.client import Client from email import generator from pandas", "file_name if org_files else file_name obj.setText(all_files) def print_html(self, index): if", "self.left_layout.addWidget(self.quit_btn, 8, 0, 1, 3) # 主要功能查詢 self.in_data = QLineEdit()", "QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem,", "QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml)", "condition = self.cmb_logs_choice.currentText() content = self.in_logs_data.text() row_num = len(self.data_logs) col_num", "import QWebEngineView from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QGridLayout, QMessageBox,", "self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1, 3)", ":\"] for i, label in enumerate(labels): self.label = QLabel(label) self.right_layout.addWidget(self.label,", "self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1, 2)", "self.tab_1 = QGridLayout() self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2)", "html) file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.eml)')", "QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex Files (*.jpg *.png *.zip)\") org_files =", "def save_data(self, data): items = self.get_items_from_layout(self.right_layout) data.clear() try: for item", "== 'date' and content in str(self.data_logs[i][condition]): switch = True elif", "self.in_smtp_port = QLineEdit() self.in_smtp_user = QLineEdit() self.in_smtp_password = QLineEdit() self.cb_smtp_ssl", "_ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.xlsx)') if not", "7) self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1,", "self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1, 2)", "左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0, 12, 3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0,", "= QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db self.in_db_host = QLineEdit() self.in_db_port", "右側物件: logs self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox() self.in_logs_data", "row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i, j, item)", "1, 3) self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1, 3) self.left_layout.addWidget(self.quit_btn, 8, 0,", "deepcopy(self.data_logs) if self.data_logs: row_num = len(self.data_logs) col_num = len(self.data_logs[0]) col_lst", "2, 4, 1, 7) self.right_layout.addWidget(self.in_db_password, 3, 4, 1, 7) self.right_layout.addWidget(self.in_db_database,", "QGridLayout, QMessageBox, QFileDialog, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QDateTimeEdit, QTextEdit,", "range(row_num): row_data = list(self.data_logs[i].values()) for j in range(col_num): temp_data =", ":\", \" 收件人群組 :\", \"收件人資料 :\", '附件資料 :',\"設定排程 :\"] for", "SubWindow(QWidget): def __init__(self): super().__init__() self.resize(400,100) self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())", "solid #32414B; margin-top: 0px; margin-bottom: 0px; padding: 4px; padding-left: 0px;", "HOST :\", \"SMTP PORT :\", \"SMTP 帳號 :\", \"SMTP 密碼", "self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout) labels =", "= QLineEdit() self.in_eml_template = QLineEdit() self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template))", "= QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp self.in_smtp_host", "self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1, 2)", "with open(file_path, 'w') as outfile: gen = generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self,", "1, 2) self.right_layout.addWidget(self.in_logs_data, 0, 6, 1, 3) self.right_layout.addWidget(self.btn_logs_search, 0, 9,", "'Excel Files (*.eml)') with open(file_path, 'w') as outfile: gen =", "self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs self.tbw_logs =", "1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1, 1) self.right_layout.addWidget(self.in_annex_file , 4,", "print(sender.text() + '键被按下') qApp = QApplication.instance() qApp.quit() def main(): app", "items: if type(item) == type(QLineEdit()): data.append(item.text()) elif type(item) == type(QCheckBox()):", "QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.eml)') with open(file_path, 'w') as", "= QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout) labels = [ \"信件類型", "*.zip)\") org_files = obj.text() all_files = org_files + ',' +", "def open_word(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word", "sendmail self.in_eml_type = QLineEdit() self.in_eml_template = QLineEdit() self.btn_eml_browse = QPushButton('瀏覽')", "obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\")", "= QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit() self.in_recipient_excel = QLineEdit()", "= QLineEdit() self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime())", "= QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1, 1, 1) self.tab_2.addWidget(self.in_edit_web, 1, 1,", "7, 1, 2) def display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels =", "self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit() self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html)", "self.cb_edit_annex = QCheckBox('是') self.in_edit_annex = QLineEdit() self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda:", "_ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex Files (*.jpg *.png *.zip)\")", "setConfigOption('background', '#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias = True) # self.resize(720,500) self.init_ui()", "QLineEdit() self.in_db_user = QLineEdit() self.in_db_password = QLineEdit() self.in_db_database = QLineEdit()", "QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit() self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda:", ":\", \"回收網址 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i,", "self.in_db_port = QLineEdit() self.in_db_user = QLineEdit() self.in_db_password = QLineEdit() self.in_db_database", "= QLineEdit() self.in_db_password = QLineEdit() self.in_db_database = QLineEdit() self.in_db_domain =", "self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db self.in_db_host = QLineEdit() self.in_db_port = QLineEdit()", "self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked {", "QMessageBox.Ok) print(data) def clear_layout(self, layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None)", "\"SMTP 密碼 :\", \"SMTP SSL :\", \" 測試信件內容 :\"] for", "4, 1, 7) self.right_layout.addWidget(self.in_db_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_db_user, 2,", "'./', 'Excel Files (*.xlsx)') if not file_path: return df =", "self.data_db[5] if self.data_db else 'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked(): my_time =", "self.right_layout.addWidget(self.in_scheduler, 5, 4, 1, 6) self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1, 1)", "except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) print(data) def clear_layout(self, layout): for", "from PyQt5.QtGui import QPalette, QColor, QBrush from PyQt5.QtCore import Qt,", "\"./\", \"Excel Files (*.xlsx)\") obj.setText(file_name) def open_word(self, obj): file_name, _", "3) # 主要功能 log self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0,", "self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd", "\"\"\" QComboBox::item:checked { height: 12px; border: 1px solid #32414B; margin-top:", "\"Eml Files (*.eml)\") if not file_name: return header, html =", "\"內容 :\"] for i, label in enumerate(labels): self.label = QLabel(label)", "self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self):", "1, 7) self.right_layout.addWidget(self.in_db_domain, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_db_save, 6, 9,", ":\", \"SMTP 帳號 :\", \"SMTP 密碼 :\", \"SMTP SSL :\",", "self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0, 1, 3) # 主要功能 log self.query_result", "except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok)", "QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok)", "init_ui(self): # 創建視窗主部件 self.main_widget = QWidget() # 創建主部件的網格佈局 self.main_layout =", "= True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for", "layout): return [layout.itemAt(i).widget() for i in range(layout.count())] def save_data(self, data):", "1, 7) self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_user, 2, 4,", "self.right_layout.addWidget(self.in_db_database, 4, 4, 1, 7) self.right_layout.addWidget(self.in_db_domain, 5, 4, 1, 7)", "Files (*.eml)\") if not file_name: return header, html = gm.get_msg(file_name)", "self.cmb_logs_choice.currentText() content = self.in_logs_data.text() row_num = len(self.data_logs) col_num = len(self.data_logs[0])", "QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0,", "gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html) file_path, _", "= [] self.data_logs = [] self.data_temp_logs = [] # self.sub_win", "db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db else", "'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 = QGridLayout() self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0)", "1, 3) self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1, 3) self.left_layout.addWidget(self.btn_get_logs, 6, 0,", "eml self.in_edit_sender = QLineEdit() self.in_edit_sender_name = QLineEdit() self.cb_edit_annex = QCheckBox('是')", "or not self.in_logs_data.text(): return self.data_temp_logs = [] self.tbw_logs.setRowCount(0) # header", "_ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.eml)') with open(file_path,", "self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit() self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1", "QTableWidgetItem, QHeaderView) from PyQt5.QtGui import QPalette, QColor, QBrush from PyQt5.QtCore", "items = self.get_items_from_layout(self.right_layout) for item in items: if type(item) ==", "self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if error: QMessageBox.warning(self,", "def display_send_mail(self): self.clear_layout(self.right_layout) labels = [ \"信件類型 :\", \"信件模板 :\",", "4, 4, 1, 7) self.right_layout.addWidget(self.in_db_domain, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_db_save,", "setConfigOptions(antialias = True) # self.resize(720,500) self.init_ui() self.data_smtp = [] self.data_db", ":\", \"使用資料庫名稱 :\", \"回收網址 :\"] for i, label in enumerate(labels):", "= Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test Email', '測試寄件人',", "# 創建主部件的網格佈局 self.main_layout = QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件", "# self.sub_win = SubWindow() # 默認狀態欄 self.status = self.statusBar() self.status.showMessage(\"開發者:", "self.left_layout.addWidget(self.btn_db, 4, 0, 1, 3) self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1, 3)", "= QCheckBox('是') self.in_edit_annex = QLineEdit() self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex))", "DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!',", "= QLineEdit() self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda:", "padding-left: 0px; } \"\"\" ) def init_ui(self): # 創建視窗主部件 self.main_widget", "= self.in_edit_html.toPlainText() if not any(header[:3]) or not html: return try:", "QLineEdit() self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit() self.mail_tab", "j, item) def logs_download(self): if self.data_temp_logs: try: file_path, _ =", "self.right_layout.addWidget(self.in_logs_data, 0, 6, 1, 3) self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1, 2)", "def init_ui(self): # 創建視窗主部件 self.main_widget = QWidget() # 創建主部件的網格佈局 self.main_layout", "= mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning:", "7) self.right_layout.addWidget(self.in_db_domain, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_db_save, 6, 9, 1,", "QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting)", "QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp self.in_smtp_host = QLineEdit() self.in_smtp_port =", "3) self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3, 12, 8)", "PORT :\", \"SMTP 帳號 :\", \"SMTP 密碼 :\", \"SMTP SSL", "else: sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if self.data_smtp else", "11, 9, 1, 2) def display_logs(self): self.data_temp_logs = [] self.tbw_logs.setRowCount(0)", "True elif self.data_logs[i][condition] == content: switch = True if switch:", "self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0, 1, 3) #", "# sender 是发送信号的对象 sender = self.sender() print(sender.text() + '键被按下') qApp", "\"./\", \"Annex Files (*.jpg *.png *.zip)\") org_files = obj.text() all_files", "= gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(),", "quit_act(self): # sender 是发送信号的对象 sender = self.sender() print(sender.text() + '键被按下')", "'儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self): #", "',' + file_name if org_files else file_name obj.setText(all_files) def print_html(self,", "self.right_layout.addWidget(self.in_db_password, 3, 4, 1, 7) self.right_layout.addWidget(self.in_db_database, 4, 4, 1, 7)", "logs_download(self): if self.data_temp_logs: try: file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './',", "= True elif self.data_logs[i][condition] == content: switch = True if", "帳號 :\", \"資料庫 密碼 :\", \"使用資料庫名稱 :\", \"回收網址 :\"] for", "self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1, 2)", "QWidget, QGridLayout, QMessageBox, QFileDialog, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QDateTimeEdit,", "7) self.right_layout.addWidget(self.btn_db_save, 6, 9, 1, 2) def display_update_eml(self): self.clear_layout(self.right_layout) labels", "self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self): header, msg = [],", "def eml_open(self): self.in_edit_html.clear() file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml", "# 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3, 12, 8) # 設置視窗主部件 self.setCentralWidget(self.main_widget)", "content = self.in_logs_data.text() row_num = len(self.data_logs) col_num = len(self.data_logs[0]) #", "db.get_logs() self.data_temp_logs = deepcopy(self.data_logs) if self.data_logs: row_num = len(self.data_logs) col_num", "8) self.right_layout.addWidget(QLabel('查詢 :'), 0, 3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4,", "in range(row_num): switch = False if condition == 'date' and", "= QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\")", ":\", \"主旨 :\", \"內容 :\"] for i, label in enumerate(labels):", "self.sub_win.in_recipient.text()], self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if error:", "1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1, 2) def display_smtp_setting(self): self.clear_layout(self.right_layout)", "QLabel(label) self.right_layout.addWidget(self.label, i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4,", "self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1, 7)", "1, 3, 11, 8) self.right_layout.addWidget(QLabel('查詢 :'), 0, 3, 1, 1)", "帳號 :\", \"SMTP 密碼 :\", \"SMTP SSL :\", \" 測試信件內容", "# 默認狀態欄 self.status = self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\") #", "self.left_layout.addWidget(self.in_data, 1, 0, 1, 3) # 主要功能 log self.query_result =", "3, 10, 1, 1) self.right_layout.addWidget(self.in_annex_file , 4, 4, 1, 6)", "1, 3) self.left_layout.addWidget(self.btn_smtp, 3, 0, 1, 3) self.left_layout.addWidget(self.btn_db, 4, 0,", "= len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)", "obj.text() all_files = org_files + ',' + file_name if org_files", "主要功能 log self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0, 2, 3)", "QLineEdit() self.cb_edit_annex = QCheckBox('是') self.in_edit_annex = QLineEdit() self.btn_edit_annex = QPushButton('瀏覽')", "= [] self.data_temp_logs = [] # self.sub_win = SubWindow() #", "eml_type, eml_file, user_group, mail_excel, annex_file, url, my_time) QMessageBox.information(self, 'Success!', '排程設定成功!',", "QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView) from PyQt5.QtGui import QPalette,", "3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3, 12, 8) # 設置視窗主部件", "8) # 設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail)", "\"寄件人名稱 :\", \" 是否加入附件 :\", \"附件名稱 :\", \"主旨 :\", \"內容", "2, 4, 1, 7) self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex,", "\"Eml Files (*.eml)\") obj.setText(file_name) def open_excel(self, obj): file_name, _ =", "_ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word Files (*.doc *.docx)\") obj.setText(file_name)", "self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn", "資料!', QMessageBox.Ok) def send_test(self): try: if self.data_smtp: mailserver = Smtp(self.data_smtp[0],", "range(col_num): temp_data = row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240)))", "'另存為...', './', 'Excel Files (*.eml)') with open(file_path, 'w') as outfile:", "1, 7) self.right_layout.addWidget(self.btn_db_save, 6, 9, 1, 2) def display_update_eml(self): self.clear_layout(self.right_layout)", "or not html: return try: msg = gm.gen_eml(header, html, annex_file)", "self.data_logs or not self.in_logs_data.text(): return self.data_temp_logs = [] self.tbw_logs.setRowCount(0) #", "3, 4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1, 1) self.right_layout.addWidget(self.in_annex_file", "# self.resize(720,500) self.init_ui() self.data_smtp = [] self.data_db = [] self.data_logs", "# 創建視窗主部件 self.main_widget = QWidget() # 創建主部件的網格佈局 self.main_layout = QGridLayout()", "\" 測試信件內容 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i,", "sm, db, annex=annex_file, url=url) sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok)", "try: for item in items: if type(item) == type(QLineEdit()): data.append(item.text())", "insert_send_mail from server.database import Database from server.sendmail import Smtp from", "import Database from server.sendmail import Smtp from server.client import Client", "是发送信号的对象 sender = self.sender() print(sender.text() + '键被按下') qApp = QApplication.instance()", "4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2,", "0, 0, 1, 1) self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1,", "temp_data = row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i,", "coding: UTF-8 -*- # 基本控件都在这里面 from PyQt5.QtWebEngineWidgets import QWebEngineView from", "QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__() def get_items_from_layout(self, layout): return", "self.right_layout.addWidget(self.mail_tab, 5, 4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1, 2)", "display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"資料庫 HOST :\", \"資料庫", "+ file_name if org_files else file_name obj.setText(all_files) def print_html(self, index):", "'信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else: QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except:", "QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self): if self.data_smtp: self.sub_win =", "= QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.eml)') with open(file_path, 'w')", "server.client import Client from email import generator from pandas import", "默認狀態欄 self.status = self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\") # 標題欄", "setConfigOption, setConfigOptions import qdarkstyle, sys import mylibrary.genmail as gm from", "import QPalette, QColor, QBrush from PyQt5.QtCore import Qt, QDateTime from", ":\", \" 測試信件內容 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label),", "return df = DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok)", "= QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget = QWidget()", "data): items = self.get_items_from_layout(self.right_layout) data.clear() try: for item in items:", "11, 7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1, 2) def", "4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6,", "1, 1) self.right_layout.addWidget(self.in_scheduler, 5, 4, 1, 6) self.right_layout.addWidget(self.cb_scheduler, 5, 10,", "self.data_db else Database() insert_send_mail(eml_type, eml_file, user_group, mail_excel, sm, db, annex=annex_file,", "self.data_temp_logs = [] self.tbw_logs.setRowCount(0) # header = {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group',", "QMessageBox, QFileDialog, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget,", "# 右側物件: logs self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox()", "4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1, 7) self.right_layout.addWidget(self.in_edit_annex, 3,", "else file_name obj.setText(all_files) def print_html(self, index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def", "Database() insert_send_mail(eml_type, eml_file, user_group, mail_excel, sm, db, annex=annex_file, url=url) sm.close()", "# 主要功能查詢 self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0, 1,", "= len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i in range(row_num): switch", "for i, label in enumerate(labels): self.label = QLabel(label) self.right_layout.addWidget(self.label, i,", "self.get_items_from_layout(self.right_layout) for item in items: if type(item) == type(QLineEdit()): item.clear()", "= [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3, 11, 8) self.right_layout.addWidget(QLabel('查詢", "self.get_items_from_layout(self.right_layout) data.clear() try: for item in items: if type(item) ==", "for i in range(row_num): row_data = list(self.data_logs[i].values()) for j in", "items: if type(item) == type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self):", "self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in range(row_num): row_data =", "self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\")", "open_word(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word Files", "QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget = QWidget() self.left_widget.setObjectName('left_widget')", "self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit() self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1,", "0, 4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex,", "self.resize(720,500) self.init_ui() self.data_smtp = [] self.data_db = [] self.data_logs =", "print_html(self, index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type = self.in_eml_type.text()", "index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type = self.in_eml_type.text() eml_file", "5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11,", "1, 1) self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open)", ":\", \"資料庫 密碼 :\", \"使用資料庫名稱 :\", \"回收網址 :\"] for i,", "def open_eml(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml", "self.data_smtp[2], self.data_smtp[3]) if self.data_smtp else Smtp() db = Database(self.data_db[0], int(self.data_db[1]),", "Files (*.eml)\") obj.setText(file_name) def open_excel(self, obj): file_name, _ = QFileDialog.getOpenFileName(self,", "= QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False)", "i in range(row_num): switch = False if condition == 'date'", "1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_port, 1,", "QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0, 12, 3) #", "QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget =", "QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1, 1) self.in_recipient =", "= QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件: update eml self.in_edit_sender =", "右側物件: db self.in_db_host = QLineEdit() self.in_db_port = QLineEdit() self.in_db_user =", "1, 7) self.right_layout.addWidget(self.in_db_database, 4, 4, 1, 7) self.right_layout.addWidget(self.in_db_domain, 5, 4,", "5, 1, 1) class MailserverUi(QMainWindow): def __init__(self): super().__init__() setConfigOption('background', '#19232D')", "padding: 4px; padding-left: 0px; } \"\"\" ) def init_ui(self): #", "QApplication(sys.argv) gui = MailserverUi() gui.show() sys.exit(app.exec_()) if __name__ == '__main__':", "1, 1, 1) self.tab_2.addWidget(self.in_edit_web, 1, 1, 1, 1) self.btn_edit_eml_reset =", "import qdarkstyle, sys import mylibrary.genmail as gm from GenAndSendMail import", "QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit() self.btn_annex_file", "5, 4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test,", "= [], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',')", "SubWindow() # 默認狀態欄 self.status = self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\")", "Database() self.data_logs = db.get_logs() self.data_temp_logs = deepcopy(self.data_logs) if self.data_logs: row_num", "0, 1, 3) self.left_layout.addWidget(self.btn_smtp, 3, 0, 1, 3) self.left_layout.addWidget(self.btn_db, 4,", "self.data_db[3], self.data_db[4]) if self.data_db[:5] else Database() self.data_logs = db.get_logs() self.data_temp_logs", "3) self.left_layout.addWidget(self.btn_db, 4, 0, 1, 3) self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1,", "# 設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp", "QLineEdit() self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db))", "# 在右邊新增物件 labels = [\"SMTP HOST :\", \"SMTP PORT :\",", "log self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0, 2, 3) self.query_result.verticalHeader().setVisible(False)", "1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4, 1, 7) self.right_layout.addWidget(self.in_eml_template, 1,", "QBrush from PyQt5.QtCore import Qt, QDateTime from pyqtgraph import GraphicsLayoutWidget,", "設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget = QWidget() self.left_widget.setObjectName('left_widget') self.left_layout =", "[] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3, 11, 8) self.right_layout.addWidget(QLabel('查詢 :'),", "QLineEdit() self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True)", "mylibrary.genmail as gm from GenAndSendMail import insert_send_mail from server.database import", "def main(): app = QApplication(sys.argv) gui = MailserverUi() gui.show() sys.exit(app.exec_())", "self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn =", "self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1, 7)", "copy import deepcopy class SubWindow(QWidget): def __init__(self): super().__init__() self.resize(400,100) self.main_layout", "PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QGridLayout, QMessageBox, QFileDialog, QLabel, QLineEdit,", "row_num = len(self.data_logs) col_num = len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear()", "= [] self.data_db = [] self.data_logs = [] self.data_temp_logs =", "def display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"資料庫 HOST :\",", "2) try: db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if", "else Database() insert_send_mail(eml_type, eml_file, user_group, mail_excel, sm, db, annex=annex_file, url=url)", "enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4,", "def logs_download(self): if self.data_temp_logs: try: file_path, _ = QFileDialog.getSaveFileName(self, '另存為...',", "'Failed!', '信件寄出失敗!', QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear() file_name, _ = QFileDialog.getOpenFileName(self,", "1, 7) self.right_layout.addWidget(self.in_db_password, 3, 4, 1, 7) self.right_layout.addWidget(self.in_db_database, 4, 4,", "6, 9, 1, 2) def display_update_eml(self): self.clear_layout(self.right_layout) labels = [\"寄件人", "self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked { height: 12px; border: 1px solid", ":\", '附件資料 :',\"設定排程 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label),", "(*.doc *.docx)\") obj.setText(file_name) def open_annex(self, obj): file_name, _ = QFileDialog.getOpenFileName(self,", "str(self.data_logs[i][condition]): switch = True elif self.data_logs[i][condition] == content: switch =", "gm from GenAndSendMail import insert_send_mail from server.database import Database from", "= org_files + ',' + file_name if org_files else file_name", "header, msg = [], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file", "= QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") obj.setText(file_name) def open_excel(self,", "eml_save(self): header, msg = [], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>')", "7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1,", "self.right_layout.addWidget(self.label, i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1,", "1) class MailserverUi(QMainWindow): def __init__(self): super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground', 'd')", "1, 3) self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1, 3) self.left_layout.addWidget(self.btn_download_logs, 7, 0,", "QHeaderView) from PyQt5.QtGui import QPalette, QColor, QBrush from PyQt5.QtCore import", "= obj.text() all_files = org_files + ',' + file_name if", "True) # self.resize(720,500) self.init_ui() self.data_smtp = [] self.data_db = []", "2, 0, 1, 3) self.left_layout.addWidget(self.btn_smtp, 3, 0, 1, 3) self.left_layout.addWidget(self.btn_db,", "self.mail_tab_1 = QWidget() self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web')", "QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act)", "= self.cmb_logs_choice.currentText() content = self.in_logs_data.text() row_num = len(self.data_logs) col_num =", "11, 5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save,", "len(self.data_logs) col_num = len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num)", "self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4, 1,", "4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1, 1) self.right_layout.addWidget(self.in_recipient_group, 2,", "from GenAndSendMail import insert_send_mail from server.database import Database from server.sendmail", "QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") if not file_name: return", "3, 4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_test,", "7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1, 2) def display_logs(self):", "in str(self.data_logs[i][condition]): switch = True elif self.data_logs[i][condition] == content: switch", "self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db[:5] else Database() self.data_logs = db.get_logs()", "'' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',') html =", "self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件: update eml self.in_edit_sender", "= QApplication(sys.argv) gui = MailserverUi() gui.show() sys.exit(app.exec_()) if __name__ ==", "4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3,", "'郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText() content = self.in_logs_data.text() row_num", "self.right_layout.addWidget(self.in_eml_template, 1, 4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1, 1)", "import (QApplication, QMainWindow, QWidget, QGridLayout, QMessageBox, QFileDialog, QLabel, QLineEdit, QPushButton,", "QFileDialog, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget,", "= False if condition == 'date' and content in str(self.data_logs[i][condition]):", "= list(self.data_logs[i].values()) for j in range(col_num): temp_data = row_data[j] item", "'键被按下') qApp = QApplication.instance() qApp.quit() def main(): app = QApplication(sys.argv)", "in items: if type(item) == type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def", "data.append(item.text()) elif type(item) == type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok)", "self.left_layout.addWidget(self.btn_smtp, 3, 0, 1, 3) self.left_layout.addWidget(self.btn_db, 4, 0, 1, 3)", "gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok)", "self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) #", "file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") if", "self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1, 1, 1) self.tab_2.addWidget(self.in_edit_web, 1,", "Files (*.eml)') with open(file_path, 'w') as outfile: gen = generator.Generator(outfile)", "4, 1, 7) self.right_layout.addWidget(self.in_db_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_db_password, 3,", "(*.xlsx)') if not file_path: return df = DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False)", "QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件: update", "self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit() self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file))", "QMessageBox.Ok) def send_test(self): try: if self.data_smtp: mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]),", "2, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl,", "\"回收網址 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3,", "self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget() self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html')", "class SubWindow(QWidget): def __init__(self): super().__init__() self.resize(400,100) self.main_layout = QGridLayout() self.setLayout(self.main_layout)", "hh:mm') self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件:", "self.right_layout.addWidget(self.in_eml_type, 0, 4, 1, 7) self.right_layout.addWidget(self.in_eml_template, 1, 4, 1, 6)", "def get_items_from_layout(self, layout): return [layout.itemAt(i).widget() for i in range(layout.count())] def", "QMainWindow, QWidget, QGridLayout, QMessageBox, QFileDialog, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox,", "= QLineEdit() self.in_smtp_port = QLineEdit() self.in_smtp_user = QLineEdit() self.in_smtp_password =", "if self.data_temp_logs: try: file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel", "self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText() if not any(header[:3]) or not html:", "self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs =", "self.data_temp_logs = [] # self.sub_win = SubWindow() # 默認狀態欄 self.status", "QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1, 3) self.left_layout.addWidget(self.btn_smtp, 3, 0,", "if not any(header[:3]) or not html: return try: msg =", "2) def display_logs(self): self.data_temp_logs = [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1,", "1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1,", "== type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self): if not self.data_logs", "self.in_db_host = QLineEdit() self.in_db_port = QLineEdit() self.in_db_user = QLineEdit() self.in_db_password", "= QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit() self.btn_annex_file = QPushButton('瀏覽')", "SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP 資料!', QMessageBox.Ok)", "12, 8) # 設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\")", "self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) #", "col_num = len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i in range(row_num):", "1, 1, 5) self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5, 1,", "6) self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1, 1) self.right_layout.addWidget(self.in_scheduler, 5, 4, 1,", "7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1,", "10, 1, 1) self.right_layout.addWidget(self.in_scheduler, 5, 4, 1, 6) self.right_layout.addWidget(self.cb_scheduler, 5,", "= self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1)", "eml_file, user_group, mail_excel, annex_file, url, my_time) QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok)", "display_send_mail(self): self.clear_layout(self.right_layout) labels = [ \"信件類型 :\", \"信件模板 :\", \"", "= QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\")", "3, 10, 1, 1) self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1, 7) self.right_layout.addWidget(self.mail_tab,", "= QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.xlsx)') if not file_path:", "self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1, 3) self.left_layout.addWidget(self.quit_btn, 8, 0, 1, 3)", "except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear() file_name, _", "as gm from GenAndSendMail import insert_send_mail from server.database import Database", "= [\"資料庫 HOST :\", \"資料庫 PORT :\", \"資料庫 帳號 :\",", "(*.eml)\") obj.setText(file_name) def open_excel(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\",", "QComboBox, QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView) from PyQt5.QtGui", "def eml_save(self): header, msg = [], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text())", "self.right_widget = QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列", "self.tab_2.addWidget(self.in_edit_web, 1, 1, 1, 1) self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read", "\"./\", \"Eml Files (*.eml)\") if not file_name: return header, html", "'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self,", "2) def display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"資料庫 HOST", "Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text())", "not self.in_logs_data.text(): return self.data_temp_logs = [] self.tbw_logs.setRowCount(0) # header =", "= QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp self.in_smtp_host = QLineEdit() self.in_smtp_port", "file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.xlsx)') if", "'儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) print(data) def clear_layout(self,", "len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i in range(row_num): switch =", "except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self): if self.data_smtp: self.sub_win", "'d') setConfigOptions(antialias = True) # self.resize(720,500) self.init_ui() self.data_smtp = []", "Files (*.doc *.docx)\") obj.setText(file_name) def open_annex(self, obj): file_name, _ =", "error = mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if error: QMessageBox.warning(self, 'Warning!',", "self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1, 2) def display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件", "return [layout.itemAt(i).widget() for i in range(layout.count())] def save_data(self, data): items", "self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db self.in_db_host", "html = self.in_edit_html.toPlainText() if not any(header[:3]) or not html: return", "super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias = True) # self.resize(720,500)", "= QLineEdit() self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit()", "header = {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText() content", "1, 6) self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1, 1) self.right_layout.addWidget(self.in_scheduler, 5, 4,", "self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget = QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout()", "labels = [\"資料庫 HOST :\", \"資料庫 PORT :\", \"資料庫 帳號", "= len(self.data_logs) col_num = len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst)", "file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word Files (*.doc *.docx)\")", "1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1, 1) self.right_layout.addWidget(self.in_edit_subject, 4, 4,", "1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1, 2) self.right_layout.addWidget(self.in_logs_data, 0, 6, 1,", "= QLineEdit() self.in_smtp_user = QLineEdit() self.in_smtp_password = QLineEdit() self.cb_smtp_ssl =", "self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1,", "show_sub_win(self): if self.data_smtp: self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self,", "send_test(self): try: if self.data_smtp: mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3])", "header, html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self):", "type(item) == type(QLineEdit()): data.append(item.text()) elif type(item) == type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self,", "\"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self): # sender 是发送信号的对象 sender =", "7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1,", "user_group, mail_excel, sm, db, annex=annex_file, url=url) sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!',", ":\", \" 是否加入附件 :\", \"附件名稱 :\", \"主旨 :\", \"內容 :\"]", "'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) def eml_reset(self):", "self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3, 12, 8) #", "if org_files else file_name obj.setText(all_files) def print_html(self, index): if index:", "# 右側物件: db self.in_db_host = QLineEdit() self.in_db_port = QLineEdit() self.in_db_user", "self.right_layout.addWidget(self.tbw_logs, 1, 3, 11, 8) self.right_layout.addWidget(QLabel('查詢 :'), 0, 3, 1,", "layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self, obj): file_name,", "# 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0, 12, 3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget,", "for item in items: if type(item) == type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False)", "1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4,", "int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if self.data_smtp else Smtp() db = Database(self.data_db[0],", "7) self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1,", "'附件資料 :',\"設定排程 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i,", "'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__() def get_items_from_layout(self, layout): return [layout.itemAt(i).widget()", "item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self): if not self.data_logs or not", "i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4, 1, 7)", "def logs_change(self): if not self.data_logs or not self.in_logs_data.text(): return self.data_temp_logs", "i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1, 7)", "not file_path: return df = DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!',", "[layout.itemAt(i).widget() for i in range(layout.count())] def save_data(self, data): items =", "file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel Files (*.xlsx)\") obj.setText(file_name)", "self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs", "7) self.right_layout.addWidget(self.in_eml_template, 1, 4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1,", "self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget() self.mail_tab_2 =", "j in range(col_num): temp_data = row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144,", "in range(col_num): temp_data = row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182,", "self.data_logs: row_num = len(self.data_logs) col_num = len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys())", "def send_test(self): try: if self.data_smtp: mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2],", "QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView) from PyQt5.QtGui import", "\"\"\" ) def init_ui(self): # 創建視窗主部件 self.main_widget = QWidget() #", "QLineEdit() self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test = QLineEdit() self.btn_smtp_save = QPushButton('儲存')", "= gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html) file_path,", "[] # self.sub_win = SubWindow() # 默認狀態欄 self.status = self.statusBar()", "self.data_db[3], self.data_db[4]) if self.data_db else Database() insert_send_mail(eml_type, eml_file, user_group, mail_excel,", "\"SMTP SSL :\", \" 測試信件內容 :\"] for i, label in", "label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host,", "if type(item) == type(QLineEdit()): data.append(item.text()) elif type(item) == type(QCheckBox()): data.append(item.isChecked())", "\"選取檔案\", \"./\", \"Eml Files (*.eml)\") if not file_name: return header,", "self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type = self.in_eml_type.text() eml_file = self.in_eml_template.text() user_group", "4, 1, 7) self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_user, 2,", "GenAndSendMail import insert_send_mail from server.database import Database from server.sendmail import", "1) self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1, 7) self.right_layout.addWidget(self.mail_tab, 5, 4, 6,", ":\", \"資料庫 PORT :\", \"資料庫 帳號 :\", \"資料庫 密碼 :\",", "= self.in_logs_data.text() row_num = len(self.data_logs) col_num = len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num)", "else gm.gen_eml(header, html) file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel", "1, 1, 1, 1) self.tab_2.addWidget(self.in_edit_web, 1, 1, 1, 1) self.btn_edit_eml_reset", "self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs self.tbw_logs = QTableWidget()", "QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget = QWidget() self.right_widget.setObjectName('right_widget') self.right_layout =", "_ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") if not", "= QLineEdit() self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test = QLineEdit() self.btn_smtp_save =", "QTableWidget, QTableWidgetItem, QHeaderView) from PyQt5.QtGui import QPalette, QColor, QBrush from", "content: switch = True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values())", "11, 8) self.right_layout.addWidget(QLabel('查詢 :'), 0, 3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0,", "4, 1, 7) self.right_layout.addWidget(self.mail_tab, 5, 4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11,", "右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3, 12, 8) # 設置視窗主部件 self.setCentralWidget(self.main_widget) #", "self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 = QGridLayout()", "1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1, 2) def display_db_setting(self): self.clear_layout(self.right_layout)", "= list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i", "9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1, 2) def display_db_setting(self):", "7, 0, 1, 3) self.left_layout.addWidget(self.quit_btn, 8, 0, 1, 3) #", "右側物件: smtp self.in_smtp_host = QLineEdit() self.in_smtp_port = QLineEdit() self.in_smtp_user =", "'請確認有無 SMTP 資料!', QMessageBox.Ok) def send_test(self): try: if self.data_smtp: mailserver", "9, 1, 2) def display_update_eml(self): self.clear_layout(self.right_layout) labels = [\"寄件人 :\",", "3) self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1, 3) self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1,", "4, 1, 7) self.right_layout.addWidget(self.in_db_database, 4, 4, 1, 7) self.right_layout.addWidget(self.in_db_domain, 5,", "save_data(self, data): items = self.get_items_from_layout(self.right_layout) data.clear() try: for item in", "qdarkstyle, sys import mylibrary.genmail as gm from GenAndSendMail import insert_send_mail", "12, 8) # 右側物件: sendmail self.in_eml_type = QLineEdit() self.in_eml_template =", "send_mail(self): eml_type = self.in_eml_type.text() eml_file = self.in_eml_template.text() user_group = self.in_recipient_group.text()", "QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") obj.setText(file_name) def open_excel(self, obj):", "sys import mylibrary.genmail as gm from GenAndSendMail import insert_send_mail from", "QLineEdit() self.in_db_database = QLineEdit() self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save =", "1, 2) def display_update_eml(self): self.clear_layout(self.right_layout) labels = [\"寄件人 :\", \"寄件人名稱", "self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp self.in_smtp_host = QLineEdit() self.in_smtp_port = QLineEdit()", "type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self): if not self.data_logs or", "3, 0, 1, 3) self.left_layout.addWidget(self.btn_db, 4, 0, 1, 3) self.left_layout.addWidget(self.btn_update_eml,", "setConfigOptions import qdarkstyle, sys import mylibrary.genmail as gm from GenAndSendMail", "self.data_db[4]) if self.data_db[:5] else Database() self.data_logs = db.get_logs() self.data_temp_logs =", "'另存為...', './', 'Excel Files (*.xlsx)') if not file_path: return df", "QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit() self.in_edit_web =", "col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for", "import deepcopy class SubWindow(QWidget): def __init__(self): super().__init__() self.resize(400,100) self.main_layout =", "= GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3, 12, 8) # 右側物件: sendmail", "except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) def eml_reset(self): items = self.get_items_from_layout(self.right_layout)", "= QTextEdit() self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1, 1, 1)", "switch = True elif self.data_logs[i][condition] == content: switch = True", "QLineEdit() self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit() self.in_recipient_excel", "# 右側物件: smtp self.in_smtp_host = QLineEdit() self.in_smtp_port = QLineEdit() self.in_smtp_user", "self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs", "= Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if self.data_smtp else Smtp() db", "1, 1) self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1, 7) self.right_layout.addWidget(self.mail_tab, 5, 4,", "import Smtp from server.client import Client from email import generator", "self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0,", "'儲存失敗!', QMessageBox.Ok) print(data) def clear_layout(self, layout): for i in reversed(range(layout.count())):", "type(item) == type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self): if not", "if self.data_smtp else Smtp() db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3],", "'Failed!', '請確認有無 SMTP 資料!', QMessageBox.Ok) def send_test(self): try: if self.data_smtp:", "qApp = QApplication.instance() qApp.quit() def main(): app = QApplication(sys.argv) gui", "self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit() self.btn_annex_file =", "= QLineEdit() self.in_db_port = QLineEdit() self.in_db_user = QLineEdit() self.in_db_password =", "items = self.get_items_from_layout(self.right_layout) data.clear() try: for item in items: if", "(QApplication, QMainWindow, QWidget, QGridLayout, QMessageBox, QFileDialog, QLabel, QLineEdit, QPushButton, QComboBox,", "QLineEdit() self.in_db_port = QLineEdit() self.in_db_user = QLineEdit() self.in_db_password = QLineEdit()", "self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1, 1) self.in_recipient = QLineEdit()", "enumerate(labels): self.label = QLabel(label) self.right_layout.addWidget(self.label, i, 3, 1, 1, Qt.AlignRight)", "4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11,", "QLineEdit() self.in_smtp_port = QLineEdit() self.in_smtp_user = QLineEdit() self.in_smtp_password = QLineEdit()", "= QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 = QGridLayout() self.tab_2", "(*.xlsx)\") obj.setText(file_name) def open_word(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\",", "msg = [], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file =", "QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) print(data) def clear_layout(self, layout): for i", "= QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget", "self.in_annex_file.text() url = self.data_db[5] if self.data_db else 'http://yumail.myvnc.com' try: if", "logs_change(self): if not self.data_logs or not self.in_logs_data.text(): return self.data_temp_logs =", "self.data_logs = [] self.data_temp_logs = [] # self.sub_win = SubWindow()", "= QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit() self.mail_tab = QTabWidget()", "0, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_user,", "1, 5) self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5, 1, 1)", "*.docx)\") obj.setText(file_name) def open_annex(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\",", "file_name obj.setText(all_files) def print_html(self, index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self):", "0, 1, 3) self.left_layout.addWidget(self.quit_btn, 8, 0, 1, 3) # 主要功能查詢", "3, 11, 8) self.right_layout.addWidget(QLabel('查詢 :'), 0, 3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice,", "1, 7) self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4,", "1, 2) def display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"資料庫", "Files (*.jpg *.png *.zip)\") org_files = obj.text() all_files = org_files", "self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"SMTP HOST :\", \"SMTP PORT", "'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else: QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear()", "= QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox() self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\")", "1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1, 2) def display_smtp_setting(self): self.clear_layout(self.right_layout) #", "QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self): if self.data_smtp:", "self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit() self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler", "all_files = org_files + ',' + file_name if org_files else", "在右邊新增物件 labels = [\"SMTP HOST :\", \"SMTP PORT :\", \"SMTP", "7) self.right_layout.addWidget(self.in_db_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_db_user, 2, 4, 1,", "html, annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html) file_path, _ =", "if self.data_db[:5] else Database() self.data_logs = db.get_logs() self.data_temp_logs = deepcopy(self.data_logs)", "7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1,", "密碼 :\", \"使用資料庫名稱 :\", \"回收網址 :\"] for i, label in", "2) self.right_layout.addWidget(self.in_logs_data, 0, 6, 1, 3) self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1,", "= QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\")", "self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2,", "10, 1, 1) self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3,", "i in range(layout.count())] def save_data(self, data): items = self.get_items_from_layout(self.right_layout) data.clear()", "6) self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1,", "self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1, 3) self.left_layout.addWidget(self.btn_smtp, 3, 0, 1,", "QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok) else: sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2],", "not any(header[:3]) or not html: return try: msg = gm.gen_eml(header,", "row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j in range(col_num): temp_data =", "1, 3) # 主要功能 log self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result, 9,", "聯絡資訊: <EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())", "QMessageBox.Ok) else: sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if self.data_smtp", "self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i in range(row_num): switch = False if", "elif self.data_logs[i][condition] == content: switch = True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount())", "self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1, 2)", "QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit() self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True)", "= QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存')", "try: if self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00' client = Client() client.send(self.data_smtp[:4],", "self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1, 1) self.right_layout.addWidget(self.in_annex_file , 4, 4, 1,", "db, annex=annex_file, url=url) sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) except:", "gen = generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self,", "240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def logs_download(self): if self.data_temp_logs: try: file_path,", "= QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs", "pandas import DataFrame from copy import deepcopy class SubWindow(QWidget): def", "self.data_smtp: mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test", "self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox() self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search =", "def print_html(self, index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type =", "= QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1, 1, 5) self.btn_send = QPushButton('寄送')", "0, 2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3,", "1, 7) self.right_layout.addWidget(self.in_db_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_db_user, 2, 4,", "\"主旨 :\", \"內容 :\"] for i, label in enumerate(labels): self.label", "self.in_edit_html.toPlainText() if not any(header[:3]) or not html: return try: msg", "return header, html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def", "4, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save,", "QColor, QBrush from PyQt5.QtCore import Qt, QDateTime from pyqtgraph import", "else: db.__disconnect__() def get_items_from_layout(self, layout): return [layout.itemAt(i).widget() for i in", "mailserver.close() if error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else: QMessageBox.information(self,", "self.sub_win.in_recipient.text()) mailserver.close() if error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else:", "7) self.right_layout.addWidget(self.mail_tab, 5, 4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1,", "基本控件都在这里面 from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import (QApplication, QMainWindow,", "from PyQt5.QtCore import Qt, QDateTime from pyqtgraph import GraphicsLayoutWidget, setConfigOption,", "0, 3, 12, 8) # 設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail", "PyQt5.QtGui import QPalette, QColor, QBrush from PyQt5.QtCore import Qt, QDateTime", "'Success!', '排程設定成功!', QMessageBox.Ok) else: sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3])", "my_time = self.in_scheduler.text()+':00' client = Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file,", "self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked { height: 12px; border: 1px solid #32414B;", "self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1, 1)", "0, 0, 12, 3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3, 12,", "self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1, 3) self.left_layout.addWidget(self.btn_smtp, 3, 0, 1, 3)", "obj.setText(file_name) def open_word(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\",", "eml_reset(self): items = self.get_items_from_layout(self.right_layout) for item in items: if type(item)", "self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox() self.in_logs_data = QLineEdit()", "QWebEngineView from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QGridLayout, QMessageBox, QFileDialog,", "else: QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!',", "UTF-8 -*- # 基本控件都在这里面 from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets", "= generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!',", "10, 1, 1) self.right_layout.addWidget(self.in_annex_file , 4, 4, 1, 6) self.right_layout.addWidget(self.btn_annex_file,", "from pandas import DataFrame from copy import deepcopy class SubWindow(QWidget):", "QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def", "self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail)", "# 主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting)", "item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i, j, item) except:", "self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1, 2) self.right_layout.addWidget(self.in_logs_data, 0, 6, 1, 3)", "labels = [ \"信件類型 :\", \"信件模板 :\", \" 收件人群組 :\",", "3) self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1, 3) self.left_layout.addWidget(self.quit_btn, 8, 0, 1,", "5, 10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1, 2) def", "i in range(row_num): row_data = list(self.data_logs[i].values()) for j in range(col_num):", "QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def logs_download(self): if", "html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self): header,", "try: db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db[:5]", "QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView) from PyQt5.QtGui import QPalette, QColor, QBrush", "\"SMTP PORT :\", \"SMTP 帳號 :\", \"SMTP 密碼 :\", \"SMTP", "QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit() self.in_recipient_excel = QLineEdit() self.btn_recipient_browse", "reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\",", "self.tbw_logs.setColumnCount(col_num) for i in range(row_num): switch = False if condition", "item in items: if type(item) == type(QLineEdit()): data.append(item.text()) elif type(item)", "self.data_db[:5], eml_type, eml_file, user_group, mail_excel, annex_file, url, my_time) QMessageBox.information(self, 'Success!',", "Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2],", "QTextEdit() self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1, 1, 1) self.tab_2.addWidget(self.in_edit_web,", "[\"寄件人 :\", \"寄件人名稱 :\", \" 是否加入附件 :\", \"附件名稱 :\", \"主旨", "self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit() self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1,", "'Excel Files (*.xlsx)') if not file_path: return df = DataFrame(self.data_temp_logs)", "3, 4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1, 1) self.right_layout.addWidget(self.in_edit_subject,", "def quit_act(self): # sender 是发送信号的对象 sender = self.sender() print(sender.text() +", "deepcopy class SubWindow(QWidget): def __init__(self): super().__init__() self.resize(400,100) self.main_layout = QGridLayout()", "182, 240))) self.tbw_logs.setItem(i, j, item) except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok)", "#32414B; margin-top: 0px; margin-bottom: 0px; padding: 4px; padding-left: 0px; }", "6, 0, 1, 3) self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1, 3) self.left_layout.addWidget(self.quit_btn,", "= QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\")", "self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start", "1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1, 7) self.right_layout.addWidget(self.in_edit_annex, 3, 4,", "list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j in range(col_num): temp_data = row_data[j] item", "annex=annex_file, url=url) sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self,", "0, 4, 1, 7) self.right_layout.addWidget(self.in_db_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_db_user,", "QLineEdit() self.in_edit_sender_name = QLineEdit() self.cb_edit_annex = QCheckBox('是') self.in_edit_annex = QLineEdit()", "self.clear_layout(self.right_layout) labels = [ \"信件類型 :\", \"信件模板 :\", \" 收件人群組", "self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1, 1) self.right_layout.addWidget(self.in_scheduler, 5, 4, 1, 6)", "self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text() annex_file = self.in_annex_file.text() url = self.data_db[5]", "\"Word Files (*.doc *.docx)\") obj.setText(file_name) def open_annex(self, obj): file_name, _", "1, 1) self.tab_2.addWidget(self.in_edit_web, 1, 1, 1, 1) self.btn_edit_eml_reset = QPushButton('清除')", "Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if self.data_smtp else Smtp() db =", "import mylibrary.genmail as gm from GenAndSendMail import insert_send_mail from server.database", "+ ',' + file_name if org_files else file_name obj.setText(all_files) def", "html: return try: msg = gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked()", "= QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件:", "Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4, 1, 7) self.right_layout.addWidget(self.in_eml_template, 1, 4, 1,", "240))) self.tbw_logs.setItem(i, j, item) except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else:", "= QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1, 1) self.in_recipient", "self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件: update eml self.in_edit_sender = QLineEdit() self.in_edit_sender_name", "= QLineEdit() self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試')", "self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def logs_download(self): if self.data_temp_logs: try: file_path, _", "1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4, 1, 7) self.right_layout.addWidget(self.in_eml_template, 1, 4,", "= [] # self.sub_win = SubWindow() # 默認狀態欄 self.status =", "0, 1, 3) # 主要功能 log self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result,", "\"選取檔案\", \"./\", \"Annex Files (*.jpg *.png *.zip)\") org_files = obj.text()", "i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight)", "4, 1, 7) self.right_layout.addWidget(self.in_db_password, 3, 4, 1, 7) self.right_layout.addWidget(self.in_db_database, 4,", "self.in_recipient_excel.text() annex_file = self.in_annex_file.text() url = self.data_db[5] if self.data_db else", "10, 1, 1) self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1, 7) self.right_layout.addWidget(self.mail_tab, 5,", "self.right_layout.addWidget(self.in_db_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_db_port, 1, 4, 1, 7)", "QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0, 2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget()", "'信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def eml_open(self):", "list(self.data_logs[i].values()) for j in range(col_num): temp_data = row_data[j] item =", "0, 1, 3) self.left_layout.addWidget(self.btn_db, 4, 0, 1, 3) self.left_layout.addWidget(self.btn_update_eml, 5,", "0, 3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1, 2) self.right_layout.addWidget(self.in_logs_data,", "(*.eml)\") if not file_name: return header, html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2])", "eml_open(self): self.in_edit_html.clear() file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files", "# 基本控件都在这里面 from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import (QApplication,", "clear_layout(self, layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self, obj):", "self.in_eml_type = QLineEdit() self.in_eml_template = QLineEdit() self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda:", "self.save_data(self.data_db)) # 右側物件: update eml self.in_edit_sender = QLineEdit() self.in_edit_sender_name =", "= QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout)", "self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget() self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2,", "self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in range(row_num):", "0px; padding: 4px; padding-left: 0px; } \"\"\" ) def init_ui(self):", "gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(), self.data_smtp[2],", "= self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text() annex_file = self.in_annex_file.text() url =", "QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self): # sender 是发送信号的对象 sender", "5, 4, 1, 6) self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start,", "\"SMTP 帳號 :\", \"SMTP 密碼 :\", \"SMTP SSL :\", \"", "db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db[:5] else", "3) # 主要功能查詢 self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0,", "gm.gen_eml(header, html) file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files", "= QLineEdit() self.cb_edit_annex = QCheckBox('是') self.in_edit_annex = QLineEdit() self.btn_edit_annex =", "self.data_db[4]) if self.data_db else Database() insert_send_mail(eml_type, eml_file, user_group, mail_excel, sm,", "url=url) sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!',", "= SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP 資料!',", "self.clear_layout(self.right_layout) labels = [\"寄件人 :\", \"寄件人名稱 :\", \" 是否加入附件 :\",", "from pyqtgraph import GraphicsLayoutWidget, setConfigOption, setConfigOptions import qdarkstyle, sys import", "from email import generator from pandas import DataFrame from copy", "item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i, j, item) except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!',", "server.database import Database from server.sendmail import Smtp from server.client import", "eml_file = self.in_eml_template.text() user_group = self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text() annex_file", "= QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i, j, item) except: QMessageBox.warning(self,", "1, 2) def display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"SMTP", "3) self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1, 3) self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1,", "self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1, 7)", "self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs =", "= QCheckBox('使用') self.in_smtp_test = QLineEdit() self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp))", "print(data) def clear_layout(self, layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def", "'排程設定成功!', QMessageBox.Ok) else: sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) if", "'信件寄出失敗!', QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear() file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\",", "0px; } \"\"\" ) def init_ui(self): # 創建視窗主部件 self.main_widget =", "主要功能查詢 self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0, 1, 3)", "QLineEdit() self.in_smtp_password = QLineEdit() self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test = QLineEdit()", "'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def", "url = self.data_db[5] if self.data_db else 'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked():", "obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel Files (*.xlsx)\")", "'./', 'Excel Files (*.eml)') with open(file_path, 'w') as outfile: gen", "QComboBox() self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def", "if self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00' client = Client() client.send(self.data_smtp[:4], self.data_db[:5],", "3) self.left_layout.addWidget(self.btn_smtp, 3, 0, 1, 3) self.left_layout.addWidget(self.btn_db, 4, 0, 1,", "# 主要功能 log self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0, 2,", "QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件: update eml self.in_edit_sender = QLineEdit()", "self.in_db_password = QLineEdit() self.in_db_database = QLineEdit() self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址')", "[] self.data_temp_logs = [] # self.sub_win = SubWindow() # 默認狀態欄", "if self.data_logs: row_num = len(self.data_logs) col_num = len(self.data_logs[0]) col_lst =", ":\", \"收件人資料 :\", '附件資料 :',\"設定排程 :\"] for i, label in", "enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4,", "# 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked { height: 12px;", "switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j in range(col_num):", "1, 10, 1, 1) self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel,", ":\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1,", "self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 = QGridLayout() self.tab_2 = QGridLayout()", "in items: if type(item) == type(QLineEdit()): data.append(item.text()) elif type(item) ==", "1, 2) try: db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4])", "import generator from pandas import DataFrame from copy import deepcopy", "== type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!',", "open(file_path, 'w') as outfile: gen = generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!',", "self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件:", "= DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self,", "self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1, 7)", "QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget() self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1,", "self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit() self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html,", "item in items: if type(item) == type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear()", "7) self.right_layout.addWidget(self.in_db_password, 3, 4, 1, 7) self.right_layout.addWidget(self.in_db_database, 4, 4, 1,", "= self.in_eml_template.text() user_group = self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text() annex_file =", "self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1, 2) def display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件", "for item in items: if type(item) == type(QLineEdit()): data.append(item.text()) elif", "header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText()", "-*- coding: UTF-8 -*- # 基本控件都在这里面 from PyQt5.QtWebEngineWidgets import QWebEngineView", "12, 3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3, 12, 8) #", "if not self.data_logs or not self.in_logs_data.text(): return self.data_temp_logs = []", "item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def logs_download(self): if self.data_temp_logs:", "enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4,", "self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3, 11, 8) self.right_layout.addWidget(QLabel('查詢 :'), 0,", "= SubWindow() # 默認狀態欄 self.status = self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊:", "obj.setText(file_name) def open_excel(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\",", "index=False) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok)", "self.data_logs[i][condition] == content: switch = True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data", "from server.database import Database from server.sendmail import Smtp from server.client", "= row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(i, j,", "= True) # self.resize(720,500) self.init_ui() self.data_smtp = [] self.data_db =", "4, 1, 7) self.right_layout.addWidget(self.in_eml_template, 1, 4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1,", "self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self): header, msg = [], '' header.append(self.in_edit_subject.text())", "= [] self.tbw_logs.setRowCount(0) # header = {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'}", "1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_test, 5, 4,", "def display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"SMTP HOST :\",", "[] self.data_db = [] self.data_logs = [] self.data_temp_logs = []", "self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit()", "self.data_temp_logs.append(self.data_logs[i]) for j in range(col_num): temp_data = row_data[j] item =", "3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4, 1, 7) self.right_layout.addWidget(self.in_eml_template,", "0, 1, 1, 5) self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5,", "1, 3) self.left_layout.addWidget(self.btn_db, 4, 0, 1, 3) self.left_layout.addWidget(self.btn_update_eml, 5, 0,", "self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1, 7)", "in enumerate(labels): self.label = QLabel(label) self.right_layout.addWidget(self.label, i, 3, 1, 1,", "'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00' client = Client()", "smtp self.in_smtp_host = QLineEdit() self.in_smtp_port = QLineEdit() self.in_smtp_user = QLineEdit()", "self.in_edit_html.clear() file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\")", "self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget = QWidget() self.right_widget.setObjectName('right_widget')", "self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject = QLineEdit() self.mail_tab =", "in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0,", "創建右側部件 self.right_widget = QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) #", "self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in range(row_num): row_data", "range(layout.count())] def save_data(self, data): items = self.get_items_from_layout(self.right_layout) data.clear() try: for", "self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1, 7)", "self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget = QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout()", "0, 9, 1, 2) try: db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2],", "label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host,", "QCheckBox('使用') self.in_smtp_test = QLineEdit() self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test", "self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok)", "1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1, 1) self.right_layout.addWidget(self.in_recipient_group, 2, 4,", "layout.itemAt(i).widget().setParent(None) def open_eml(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\",", "as outfile: gen = generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok)", "if not file_path: return df = DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self,", "0, 4, 1, 7) self.right_layout.addWidget(self.in_eml_template, 1, 4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse,", "6, 9, 1, 2) def display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels", "self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit() self.in_recipient_excel = QLineEdit() self.btn_recipient_browse =", "self.in_recipient_group = QLineEdit() self.in_recipient_excel = QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda:", "1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9,", "if self.data_smtp: mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg =", "self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00' client = Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type,", "def __init__(self): super().__init__() self.resize(400,100) self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'),", "9, 1, 2) def display_logs(self): self.data_temp_logs = [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout)", "self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db self.in_db_host = QLineEdit()", "QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 = QGridLayout() self.tab_2 =", "self.in_db_user = QLineEdit() self.in_db_password = QLineEdit() self.in_db_database = QLineEdit() self.in_db_domain", "open_eml(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files", "1, 7) self.right_layout.addWidget(self.in_eml_template, 1, 4, 1, 6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10,", "\"選取檔案\", \"./\", \"Word Files (*.doc *.docx)\") obj.setText(file_name) def open_annex(self, obj):", "'信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self): if self.data_smtp: self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test)", "if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html) file_path, _ = QFileDialog.getSaveFileName(self, '另存為...',", "col_num = len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num)", "QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp self.in_smtp_host =", "self.in_edit_annex = QLineEdit() self.btn_edit_annex = QPushButton('瀏覽') self.btn_edit_annex.clicked.connect(lambda: self.open_annex(self.in_edit_annex)) self.in_edit_subject =", "QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear()", "self.data_temp_logs = [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3, 11, 8)", "4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_test, 5,", "row_data = list(self.data_logs[i].values()) for j in range(col_num): temp_data = row_data[j]", "0px; margin-bottom: 0px; padding: 4px; padding-left: 0px; } \"\"\" )", "Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_db_port, 1, 4, 1,", "else Database() self.data_logs = db.get_logs() self.data_temp_logs = deepcopy(self.data_logs) if self.data_logs:", "temp_data = row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1,", "self.tbw_logs.setItem(i, j, item) except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__()", "QLineEdit() self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget() self.mail_tab_2", "1, 4, 1, 7) self.right_layout.addWidget(self.in_db_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_db_password,", "in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self, obj): file_name, _ = QFileDialog.getOpenFileName(self,", "SMTP 資料!', QMessageBox.Ok) def send_test(self): try: if self.data_smtp: mailserver =", "'儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) def eml_reset(self): items", "'測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close()", "2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1,", "user_group, mail_excel, annex_file, url, my_time) QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok) else:", "self.in_smtp_test = QLineEdit() self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test =", "\"./\", \"Word Files (*.doc *.docx)\") obj.setText(file_name) def open_annex(self, obj): file_name,", "-*- # 基本控件都在这里面 from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import", "= Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db[:5] else Database()", "self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test = QLineEdit() self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda:", "= QLineEdit() self.in_edit_sender_name = QLineEdit() self.cb_edit_annex = QCheckBox('是') self.in_edit_annex =", ":\", \"信件模板 :\", \" 收件人群組 :\", \"收件人資料 :\", '附件資料 :',\"設定排程", "= QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex Files (*.jpg *.png *.zip)\") org_files", "QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout) labels = [ \"信件類型 :\",", "i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self, obj): file_name, _ =", "= QLineEdit() self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit()", "self.status = self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\")", "[] self.tbw_logs.setRowCount(0) # header = {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition", "6, 9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1, 2) def", "QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self): # sender", "for i in range(layout.count())] def save_data(self, data): items = self.get_items_from_layout(self.right_layout)", "len(self.data_logs[0]) col_lst = list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst)", "\"資料庫 PORT :\", \"資料庫 帳號 :\", \"資料庫 密碼 :\", \"使用資料庫名稱", "QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel Files (*.xlsx)\") obj.setText(file_name) def open_word(self, obj):", "self.data_db else 'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00' client", "1) self.right_layout.addWidget(self.in_scheduler, 5, 4, 1, 6) self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1,", "= QLineEdit() self.in_db_database = QLineEdit() self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save", "# 右側物件: sendmail self.in_eml_type = QLineEdit() self.in_eml_template = QLineEdit() self.btn_eml_browse", "self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) #", "generator from pandas import DataFrame from copy import deepcopy class", "1) self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1,", "annex_file = self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText() if not any(header[:3]) or", "file_name: return header, html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html)", "QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db", "= QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file = QLineEdit()", "8) # 右側物件: sendmail self.in_eml_type = QLineEdit() self.in_eml_template = QLineEdit()", "QApplication.instance() qApp.quit() def main(): app = QApplication(sys.argv) gui = MailserverUi()", "else Smtp() db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if", "QMessageBox.Ok) else: db.__disconnect__() def get_items_from_layout(self, layout): return [layout.itemAt(i).widget() for i", "Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file, user_group, mail_excel, annex_file, url, my_time)", "self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1, 1) self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1, 7)", "try: file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.xlsx)')", "1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4,", "1, 1) self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1, 1, 5)", "gui = MailserverUi() gui.show() sys.exit(app.exec_()) if __name__ == '__main__': main()", "= db.get_logs() self.data_temp_logs = deepcopy(self.data_logs) if self.data_logs: row_num = len(self.data_logs)", "= [\"寄件人 :\", \"寄件人名稱 :\", \" 是否加入附件 :\", \"附件名稱 :\",", "content in str(self.data_logs[i][condition]): switch = True elif self.data_logs[i][condition] == content:", "from copy import deepcopy class SubWindow(QWidget): def __init__(self): super().__init__() self.resize(400,100)", "self.in_recipient_excel = QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file =", "range(row_num): switch = False if condition == 'date' and content", "0, 6, 1, 3) self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1, 2) try:", "QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) def eml_reset(self): items = self.get_items_from_layout(self.right_layout) for", "QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) def", "len(self.data_logs) col_num = len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i in", "def display_update_eml(self): self.clear_layout(self.right_layout) labels = [\"寄件人 :\", \"寄件人名稱 :\", \"", "self.main_widget = QWidget() # 創建主部件的網格佈局 self.main_layout = QGridLayout() # 設置窗口主部件佈局為網格佈局", "\"信件類型 :\", \"信件模板 :\", \" 收件人群組 :\", \"收件人資料 :\", '附件資料", "height: 12px; border: 1px solid #32414B; margin-top: 0px; margin-bottom: 0px;", "設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp =", "QLineEdit() self.in_recipient_excel = QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel)) self.in_annex_file", "1, 7) self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_password, 3, 4,", "self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1, 3) self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1, 3)", "QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice", "\"./\", \"Eml Files (*.eml)\") obj.setText(file_name) def open_excel(self, obj): file_name, _", "9, 1, 2) try: db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3],", "QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView) from PyQt5.QtGui import QPalette, QColor,", "QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download)", "switch = True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i])", "5) self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5, 1, 1) class", "from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,", "= len(self.data_logs) col_num = len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i", "self.in_edit_html.insertPlainText(html) def eml_save(self): header, msg = [], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text())", "= gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self): header, msg", "6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read, 11, 7,", "annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html) file_path, _ = QFileDialog.getSaveFileName(self,", "\"Excel Files (*.xlsx)\") obj.setText(file_name) def open_word(self, obj): file_name, _ =", "= QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget,", "GraphicsLayoutWidget, setConfigOption, setConfigOptions import qdarkstyle, sys import mylibrary.genmail as gm", "創建視窗主部件 self.main_widget = QWidget() # 創建主部件的網格佈局 self.main_layout = QGridLayout() #", "鄭鈺城, 聯絡資訊: <EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0)", ":\", \"寄件人名稱 :\", \" 是否加入附件 :\", \"附件名稱 :\", \"主旨 :\",", "= QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0, 2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display =", "Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db[:5] else Database() self.data_logs", "= QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm')", "self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self): if not self.data_logs or not self.in_logs_data.text():", "# 創建左側部件 self.left_widget = QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout)", "self.sender() print(sender.text() + '键被按下') qApp = QApplication.instance() qApp.quit() def main():", "get_items_from_layout(self, layout): return [layout.itemAt(i).widget() for i in range(layout.count())] def save_data(self,", "0, 1, 1) self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1, 1,", "3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_port,", "self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1, 1, 5) self.btn_send =", "1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1, 2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7,", "self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度", "sender 是发送信号的对象 sender = self.sender() print(sender.text() + '键被按下') qApp =", "= {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText() content =", "self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP 資料!', QMessageBox.Ok) def", "(*.jpg *.png *.zip)\") org_files = obj.text() all_files = org_files +", "1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1, 2) self.right_layout.addWidget(self.in_logs_data, 0, 6,", "label in enumerate(labels): self.label = QLabel(label) self.right_layout.addWidget(self.label, i, 3, 1,", "= QComboBox() self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change)", "QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5, 1, 1) class MailserverUi(QMainWindow): def __init__(self):", "from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QGridLayout, QMessageBox, QFileDialog, QLabel,", "0, 3, 12, 8) # 右側物件: sendmail self.in_eml_type = QLineEdit()", "self.data_smtp = [] self.data_db = [] self.data_logs = [] self.data_temp_logs", "\"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self): # sender 是发送信号的对象 sender = self.sender()", "self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1, 1) self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient,", "generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!',", "j, item) except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__() def", "1) self.right_layout.addWidget(self.in_annex_file , 4, 4, 1, 6) self.right_layout.addWidget(self.btn_annex_file, 4, 10,", "# 右側物件: update eml self.in_edit_sender = QLineEdit() self.in_edit_sender_name = QLineEdit()", "Database from server.sendmail import Smtp from server.client import Client from", "for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1,", "self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error = mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if", "182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def logs_download(self): if self.data_temp_logs: try:", "6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1, 1) self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1,", "QMessageBox.Ok) def show_sub_win(self): if self.data_smtp: self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show()", "1, 2) def display_logs(self): self.data_temp_logs = [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs,", "6, 1, 3) self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1, 2) try: db", "annex_file, url, my_time) QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok) else: sm =", "self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1, 7) self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1, 6)", "右側物件: sendmail self.in_eml_type = QLineEdit() self.in_eml_template = QLineEdit() self.btn_eml_browse =", "__init__(self): super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias = True) #", "elif type(item) == type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except:", "2, 4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse,", "self.main_layout.addWidget(self.right_widget, 0, 3, 12, 8) # 設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕", "self.in_db_database = QLineEdit() self.in_db_domain = QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存')", "import GraphicsLayoutWidget, setConfigOption, setConfigOptions import qdarkstyle, sys import mylibrary.genmail as", "1) self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save", "QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\") self.btn_update_eml.clicked.connect(self.display_update_eml) self.btn_get_logs = QPushButton(\"\b觸發明細\") self.btn_get_logs.clicked.connect(self.display_logs)", "5, 4, 1, 7) self.right_layout.addWidget(self.btn_db_save, 6, 9, 1, 2) def", "self.data_smtp: self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self, 'Failed!', '請確認有無", "'Web') self.tab_1 = QGridLayout() self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1)", "msg = gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header, html)", "sender = self.sender() print(sender.text() + '键被按下') qApp = QApplication.instance() qApp.quit()", "# -*- coding: UTF-8 -*- # 基本控件都在这里面 from PyQt5.QtWebEngineWidgets import", "self.right_layout.addWidget(QLabel('查詢 :'), 0, 3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1,", "list(self.data_logs[0].keys()) self.cmb_logs_choice.clear() self.cmb_logs_choice.addItems(col_lst) self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) self.tbw_logs.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in", "self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城, 聯絡資訊: <EMAIL>\") # 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) #", "display_update_eml(self): self.clear_layout(self.right_layout) labels = [\"寄件人 :\", \"寄件人名稱 :\", \" 是否加入附件", "self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error", "= QLineEdit() self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件:", "self.data_temp_logs: try: file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files", "self.right_layout.addWidget(self.right_display, 0, 3, 12, 8) # 右側物件: sendmail self.in_eml_type =", "QDateTime from pyqtgraph import GraphicsLayoutWidget, setConfigOption, setConfigOptions import qdarkstyle, sys", "QGridLayout() self.tab_2 = QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html =", "display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"SMTP HOST :\", \"SMTP", "QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox() self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search", "else: QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP 資料!', QMessageBox.Ok) def send_test(self): try:", "= self.sender() print(sender.text() + '键被按下') qApp = QApplication.instance() qApp.quit() def", "self.main_layout.addWidget(self.in_recipient, 0, 1, 1, 5) self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1,", "df = DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except:", "switch = False if condition == 'date' and content in", "0, 1, 3) self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1, 3) self.left_layout.addWidget(self.quit_btn, 8,", "i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1, 7)", "self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout) labels = [", "= [ \"信件類型 :\", \"信件模板 :\", \" 收件人群組 :\", \"收件人資料", "self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4, 1,", "if condition == 'date' and content in str(self.data_logs[i][condition]): switch =", "self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit() self.in_edit_web = QWebEngineView()", "Client from email import generator from pandas import DataFrame from", "self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit() self.in_recipient_excel = QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽')", "if self.data_db else 'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00'", "1, 7) self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9,", "self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1, 1) self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient, 0,", "user_group = self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text() annex_file = self.in_annex_file.text() url", "= QLineEdit() self.in_recipient_excel = QLineEdit() self.btn_recipient_browse = QPushButton('瀏覽') self.btn_recipient_browse.clicked.connect(lambda: self.open_excel(self.in_recipient_excel))", "1, 3) self.left_layout.addWidget(self.quit_btn, 8, 0, 1, 3) # 主要功能查詢 self.in_data", "[], '' header.append(self.in_edit_subject.text()) header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',') html", "9, 1, 2) def display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels =", "margin-bottom: 0px; padding: 4px; padding-left: 0px; } \"\"\" ) def", "} \"\"\" ) def init_ui(self): # 創建視窗主部件 self.main_widget = QWidget()", "6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1, 1) self.right_layout.addWidget(self.in_annex_file , 4, 4,", "self.left_layout.addWidget(self.query_result, 9, 0, 2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display,", "self.sub_win.in_recipient.clear() except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear() file_name,", "self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp", "self.in_smtp_user = QLineEdit() self.in_smtp_password = QLineEdit() self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test", "\"使用資料庫名稱 :\", \"回收網址 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label),", "= QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0, 1, 3) # 主要功能", "0, 1, 3) self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1, 3) self.left_layout.addWidget(self.btn_get_logs, 6,", "self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml =", "i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0, 4, 1, 7)", "self.label = QLabel(label) self.right_layout.addWidget(self.label, i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_edit_sender,", "'#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias = True) # self.resize(720,500) self.init_ui() self.data_smtp", "7) self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6, 9, 1,", "Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db else Database() insert_send_mail(eml_type,", "QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear() file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\",", "mailserver.send(mail_msg.as_string(), self.data_smtp[2], self.sub_win.in_recipient.text()) mailserver.close() if error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error,", "self.btn_sendmail = QPushButton(\"發送信件\") self.btn_sendmail.clicked.connect(self.display_send_mail) self.btn_smtp = QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db =", "\"選取檔案\", \"./\", \"Eml Files (*.eml)\") obj.setText(file_name) def open_excel(self, obj): file_name,", "1px solid #32414B; margin-top: 0px; margin-bottom: 0px; padding: 4px; padding-left:", "self.in_edit_html = QTextEdit() self.in_edit_web = QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1, 1,", "error: QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else: QMessageBox.information(self, 'Success!', '信件寄出成功!',", "QWidget() self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1 =", "'date' and content in str(self.data_logs[i][condition]): switch = True elif self.data_logs[i][condition]", "1, 7) self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10,", "= self.in_annex_file.text() url = self.data_db[5] if self.data_db else 'http://yumail.myvnc.com' try:", "any(header[:3]) or not html: return try: msg = gm.gen_eml(header, html,", "+ '键被按下') qApp = QApplication.instance() qApp.quit() def main(): app =", "GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3, 12, 8) # 右側物件: sendmail self.in_eml_type", "4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1, 1) self.right_layout.addWidget(self.in_annex_file ,", "self.in_edit_sender = QLineEdit() self.in_edit_sender_name = QLineEdit() self.cb_edit_annex = QCheckBox('是') self.in_edit_annex", "def send_mail(self): eml_type = self.in_eml_type.text() eml_file = self.in_eml_template.text() user_group =", "False if condition == 'date' and content in str(self.data_logs[i][condition]): switch", "QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save)", "mail_msg = gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5]) error =", "file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.eml)') with", "10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9, 1, 2) def display_smtp_setting(self):", ":\", \"SMTP PORT :\", \"SMTP 帳號 :\", \"SMTP 密碼 :\",", "QLineEdit() self.in_smtp_user = QLineEdit() self.in_smtp_password = QLineEdit() self.cb_smtp_ssl = QCheckBox('使用')", "self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler = QCheckBox('使用')", "self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"資料庫 HOST :\", \"資料庫 PORT", "self.data_smtp[3]) if self.data_smtp else Smtp() db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2],", "1, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_password,", "'Failed!', '儲存失敗!', QMessageBox.Ok) print(data) def clear_layout(self, layout): for i in", "'儲存失敗!', QMessageBox.Ok) def eml_reset(self): items = self.get_items_from_layout(self.right_layout) for item in", "self.left_widget = QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件", "1, 1, 1, 1) self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read =", "1, 5, 1, 1) class MailserverUi(QMainWindow): def __init__(self): super().__init__() setConfigOption('background',", "2) self.right_layout.addWidget(self.btn_smtp_test, 6, 7, 1, 2) def display_db_setting(self): self.clear_layout(self.right_layout) #", "display_logs(self): self.data_temp_logs = [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3, 11,", "= QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word Files (*.doc *.docx)\") obj.setText(file_name) def", "obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex Files (*.jpg", "QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def", "org_files = obj.text() all_files = org_files + ',' + file_name", "open_annex(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex Files", "if type(item) == type(QLineEdit()): item.clear() self.cb_edit_annex.setChecked(False) self.in_edit_html.clear() def logs_change(self): if", "self.data_temp_logs = deepcopy(self.data_logs) if self.data_logs: row_num = len(self.data_logs) col_num =", "= self.in_eml_type.text() eml_file = self.in_eml_template.text() user_group = self.in_recipient_group.text() mail_excel =", "7) self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4, 4, 1,", "\"資料庫 密碼 :\", \"使用資料庫名稱 :\", \"回收網址 :\"] for i, label", "= QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0,", "for i in range(row_num): switch = False if condition ==", "[ \"信件類型 :\", \"信件模板 :\", \" 收件人群組 :\", \"收件人資料 :\",", "QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\",", "and content in str(self.data_logs[i][condition]): switch = True elif self.data_logs[i][condition] ==", "4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1, 1) self.right_layout.addWidget(self.in_edit_subject, 4,", "= QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") if not file_name:", "self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group = QLineEdit() self.in_recipient_excel =", "7) self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1,", "= QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget() self.mail_tab_2 = QWidget()", "QLineEdit() self.in_eml_template = QLineEdit() self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group", "self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1, 2) try: db = Database(self.data_db[0], int(self.data_db[1]),", ":\", \"SMTP SSL :\", \" 測試信件內容 :\"] for i, label", "main(): app = QApplication(sys.argv) gui = MailserverUi() gui.show() sys.exit(app.exec_()) if", "self.right_layout.addWidget(self.in_edit_subject, 4, 4, 1, 7) self.right_layout.addWidget(self.mail_tab, 5, 4, 6, 7)", "self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3, 10, 1, 1)", "'儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\",", "else 'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked(): my_time = self.in_scheduler.text()+':00' client =", "self.main_layout.addWidget(self.left_widget, 0, 0, 12, 3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3,", "data.clear() try: for item in items: if type(item) == type(QLineEdit()):", "== content: switch = True if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data =", "QWebEngineView() self.tab_1.addWidget(self.in_edit_html, 1, 1, 1, 1) self.tab_2.addWidget(self.in_edit_web, 1, 1, 1,", "self.tab_1.addWidget(self.in_edit_html, 1, 1, 1, 1) self.tab_2.addWidget(self.in_edit_web, 1, 1, 1, 1)", "QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start = QPushButton('執行')", "8, 0, 1, 3) # 主要功能查詢 self.in_data = QLineEdit() self.in_data.setPlaceholderText(\"暫無\")", "'Failed!', '儲存失敗!', QMessageBox.Ok) else: QMessageBox.warning(self, \"缺少資料\", \"請確認是否有資料可以下載\", QMessageBox.Ok) def quit_act(self):", "type(item) == type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self,", "QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) print(data)", "QLineEdit, QPushButton, QComboBox, QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView)", "Files (*.xlsx)') if not file_path: return df = DataFrame(self.data_temp_logs) df.to_excel(file_path,", "1) self.in_recipient = QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1, 1, 5) self.btn_send", "QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save = QPushButton('儲存') self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs self.tbw_logs", "是否加入附件 :\", \"附件名稱 :\", \"主旨 :\", \"內容 :\"] for i,", "3) self.left_layout.addWidget(self.quit_btn, 8, 0, 1, 3) # 主要功能查詢 self.in_data =", "self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3, 12, 8) # 右側物件:", "{ height: 12px; border: 1px solid #32414B; margin-top: 0px; margin-bottom:", "9, 0, 2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0,", "self.right_layout.addWidget(self.in_db_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_db_password, 3, 4, 1, 7)", "1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10,", "self.sub_win = SubWindow() # 默認狀態欄 self.status = self.statusBar() self.status.showMessage(\"開發者: 鄭鈺城,", "'Success!', '信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self):", "app = QApplication(sys.argv) gui = MailserverUi() gui.show() sys.exit(app.exec_()) if __name__", ":\", \"附件名稱 :\", \"主旨 :\", \"內容 :\"] for i, label", "QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP 資料!', QMessageBox.Ok) def send_test(self): try: if", ", 4, 4, 1, 6) self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1, 1)", "type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!',", "self.right_layout.addWidget(self.btn_db_save, 6, 9, 1, 2) def display_update_eml(self): self.clear_layout(self.right_layout) labels =", "1, 1) self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4,", "3, 4, 1, 7) self.right_layout.addWidget(self.in_db_database, 4, 4, 1, 7) self.right_layout.addWidget(self.in_db_domain,", "= QPushButton(\"系統設定\") self.btn_smtp.clicked.connect(self.display_smtp_setting) self.btn_db = QPushButton(\"資料庫設定\") self.btn_db.clicked.connect(self.display_db_setting) self.btn_update_eml = QPushButton(\"修改樣板\")", "= [\"SMTP HOST :\", \"SMTP PORT :\", \"SMTP 帳號 :\",", "try: msg = gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked() else gm.gen_eml(header,", "self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1, 7) self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1, 6)", "file_path: return df = DataFrame(self.data_temp_logs) df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!', '儲存成功!',", "Smtp() db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db", "4, 1, 6) self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6,", "'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) print(data) def", "= QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0, 12, 3)", "obj.setText(all_files) def print_html(self, index): if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type", "7) self.right_layout.addWidget(self.in_db_database, 4, 4, 1, 7) self.right_layout.addWidget(self.in_db_domain, 5, 4, 1,", "header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText() if not any(header[:3])", "4, 1, 2) self.right_layout.addWidget(self.in_logs_data, 0, 6, 1, 3) self.right_layout.addWidget(self.btn_logs_search, 0,", "self.right_layout.addWidget(self.in_db_port, 1, 4, 1, 7) self.right_layout.addWidget(self.in_db_user, 2, 4, 1, 7)", "self.data_db[:5] else Database() self.data_logs = db.get_logs() self.data_temp_logs = deepcopy(self.data_logs) if", "QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1,", "pyqtgraph import GraphicsLayoutWidget, setConfigOption, setConfigOptions import qdarkstyle, sys import mylibrary.genmail", "self.resize(400,100) self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0, 0, 1,", "item) except: QMessageBox.warning(self, 'Failed!', '資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__() def get_items_from_layout(self,", "i, label in enumerate(labels): self.label = QLabel(label) self.right_layout.addWidget(self.label, i, 3,", "file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") obj.setText(file_name)", "'Failed!', '信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self): if self.data_smtp: self.sub_win = SubWindow()", "obj.setText(file_name) def open_annex(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\",", "self.in_logs_data.text(): return self.data_temp_logs = [] self.tbw_logs.setRowCount(0) # header = {'郵件類型':'type',", "密碼 :\", \"SMTP SSL :\", \" 測試信件內容 :\"] for i,", "url, my_time) QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok) else: sm = Smtp(self.data_smtp[0],", "self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db self.in_db_host =", "在右邊新增物件 labels = [\"資料庫 HOST :\", \"資料庫 PORT :\", \"資料庫", "def clear_layout(self, layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) def open_eml(self,", "6) self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1, 1) self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1,", "self.right_layout.addWidget(self.in_recipient_excel, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_recipient_browse, 3, 10, 1, 1)", "# self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for i in range(row_num): switch = False", "*.png *.zip)\") org_files = obj.text() all_files = org_files + ','", "\"附件名稱 :\", \"主旨 :\", \"內容 :\"] for i, label in", "client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file, user_group, mail_excel, annex_file, url, my_time) QMessageBox.information(self,", "__init__(self): super().__init__() self.resize(400,100) self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_layout.addWidget(QLabel('收件人'), 0,", "4, 1, 7) self.right_layout.addWidget(self.in_smtp_password, 3, 4, 1, 7) self.right_layout.addWidget(self.cb_smtp_ssl, 4,", "(*.eml)') with open(file_path, 'w') as outfile: gen = generator.Generator(outfile) gen.flatten(msg)", "4, 1, 7) self.right_layout.addWidget(self.in_edit_annex, 3, 4, 1, 6) self.right_layout.addWidget(self.btn_edit_annex, 3,", "= QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1, 3) self.left_layout.addWidget(self.btn_smtp, 3,", "QFileDialog.getSaveFileName(self, '另存為...', './', 'Excel Files (*.xlsx)') if not file_path: return", "self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler =", "self.right_layout.addWidget(self.in_edit_sender, 0, 4, 1, 7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1, 7)", "open_excel(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel Files", "mailserver = Smtp(self.data_smtp[0], int(self.data_smtp[1]), self.data_smtp[2], self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test Email',", "header.append(self.in_edit_sender_name.text()) header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText() if", "self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self, 'Failed!', '請確認有無 SMTP", "_ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Eml Files (*.eml)\") obj.setText(file_name) def", "QMessageBox.warning(self, 'Warning!', '信件寄出成功!\\nWaning: '+error, QMessageBox.Ok) else: QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok)", "Smtp from server.client import Client from email import generator from", "self.query_result = QTableWidget() self.left_layout.addWidget(self.query_result, 9, 0, 2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display", "\"選取檔案\", \"./\", \"Excel Files (*.xlsx)\") obj.setText(file_name) def open_word(self, obj): file_name,", "1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_db_port, 1, 4,", "3, 12, 8) # 設置視窗主部件 self.setCentralWidget(self.main_widget) # 主要功能按鈕 self.btn_sendmail =", "if not file_name: return header, html = gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1])", "self.in_edit_sender_name = QLineEdit() self.cb_edit_annex = QCheckBox('是') self.in_edit_annex = QLineEdit() self.btn_edit_annex", "# 標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\"", "MailserverUi(QMainWindow): def __init__(self): super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias =", "my_time) QMessageBox.information(self, 'Success!', '排程設定成功!', QMessageBox.Ok) else: sm = Smtp(self.data_smtp[0], int(self.data_smtp[1]),", "setConfigOption('foreground', 'd') setConfigOptions(antialias = True) # self.resize(720,500) self.init_ui() self.data_smtp =", "4, 1, 7) self.right_layout.addWidget(self.in_smtp_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_password, 3,", "from server.sendmail import Smtp from server.client import Client from email", "= QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget = QWidget() self.right_widget.setObjectName('right_widget') self.right_layout", "2) def display_smtp_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels = [\"SMTP HOST", "self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0, 12,", "= QLineEdit() self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 = QWidget()", "self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) # 創建右側部件 self.right_widget = QWidget()", "self.right_widget.setLayout(self.right_layout) # 左側部件在第0行第0列,佔12行3列 self.main_layout.addWidget(self.left_widget, 0, 0, 12, 3) # 右側部件在第0行第3列,佔12行8列", "data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok)", "_ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel Files (*.xlsx)\") obj.setText(file_name) def", "1, 1, 1) self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取')", "\"資料庫 帳號 :\", \"資料庫 密碼 :\", \"使用資料庫名稱 :\", \"回收網址 :\"]", "0, 12, 3) # 右側部件在第0行第3列,佔12行8列 self.main_layout.addWidget(self.right_widget, 0, 3, 12, 8)", "= Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db else Database()", "\"信件模板 :\", \" 收件人群組 :\", \"收件人資料 :\", '附件資料 :',\"設定排程 :\"]", "self.btn_get_logs.clicked.connect(self.display_logs) self.btn_download_logs = QPushButton(\"下載觸發明細\") self.btn_download_logs.clicked.connect(self.logs_download) self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail,", "return try: msg = gm.gen_eml(header, html, annex_file) if self.cb_edit_annex.isChecked() else", "0, 4, 1, 2) self.right_layout.addWidget(self.in_logs_data, 0, 6, 1, 3) self.right_layout.addWidget(self.btn_logs_search,", "import DataFrame from copy import deepcopy class SubWindow(QWidget): def __init__(self):", "= self.in_scheduler.text()+':00' client = Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file, user_group,", "= QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def logs_download(self):", "org_files + ',' + file_name if org_files else file_name obj.setText(all_files)", "= list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j in range(col_num): temp_data = row_data[j]", "self.btn_edit_eml_save.clicked.connect(self.eml_save) # 右側物件: logs self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice =", "Files (*.xlsx)\") obj.setText(file_name) def open_word(self, obj): file_name, _ = QFileDialog.getOpenFileName(self,", "1, 7) self.right_layout.addWidget(self.in_db_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_db_password, 3, 4,", "QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler = QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler", "self.right_layout.addWidget(self.in_annex_file , 4, 4, 1, 6) self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1,", "DataFrame from copy import deepcopy class SubWindow(QWidget): def __init__(self): super().__init__()", "12px; border: 1px solid #32414B; margin-top: 0px; margin-bottom: 0px; padding:", "if self.data_db else Database() insert_send_mail(eml_type, eml_file, user_group, mail_excel, sm, db,", "1, 1) class MailserverUi(QMainWindow): def __init__(self): super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground',", "'使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText() content = self.in_logs_data.text() row_num = len(self.data_logs)", "PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QGridLayout,", "self.data_smtp[2], self.data_smtp[3]) mail_msg = gm.gen_test_eml(['Test Email', '測試寄件人', self.data_smtp[2], self.sub_win.in_recipient.text()], self.data_smtp[5])", "self.quit_btn = QPushButton(\"退出\") self.quit_btn.clicked.connect(self.quit_act) self.left_layout.addWidget(self.btn_sendmail, 2, 0, 1, 3) self.left_layout.addWidget(self.btn_smtp,", "self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset) self.btn_edit_eml_read = QPushButton('讀取') self.btn_edit_eml_read.clicked.connect(self.eml_open) self.btn_edit_eml_save =", "= QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5, 1, 1) class MailserverUi(QMainWindow): def", "self.in_scheduler.text()+':00' client = Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file, user_group, mail_excel,", "header.append(self.in_edit_sender.text()) header.append('<EMAIL>') annex_file = self.in_edit_annex.text().split(',') html = self.in_edit_html.toPlainText() if not", "4px; padding-left: 0px; } \"\"\" ) def init_ui(self): # 創建視窗主部件", "= self.get_items_from_layout(self.right_layout) data.clear() try: for item in items: if type(item)", "self.in_edit_html.clear() def logs_change(self): if not self.data_logs or not self.in_logs_data.text(): return", "df.to_excel(file_path, index=False) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!',", "self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1, 2) def display_logs(self): self.data_temp_logs = []", "= QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Excel Files (*.xlsx)\") obj.setText(file_name) def open_word(self,", "self.main_layout.addWidget(self.btn_send, 1, 5, 1, 1) class MailserverUi(QMainWindow): def __init__(self): super().__init__()", "QMessageBox.Ok) def eml_reset(self): items = self.get_items_from_layout(self.right_layout) for item in items:", "標題欄 self.setWindowTitle(\"社交郵件工程\") self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked", "self.in_annex_file = QLineEdit() self.btn_annex_file = QPushButton('瀏覽') self.btn_annex_file.clicked.connect(lambda: self.open_word(self.in_annex_file)) self.in_scheduler =", "def open_annex(self, obj): file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex", "QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) def eml_reset(self): items =", "QLineEdit() self.btn_smtp_save = QPushButton('儲存') self.btn_smtp_save.clicked.connect(lambda: self.save_data(self.data_smtp)) self.btn_smtp_test = QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win)", "self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send, 1, 5, 1, 1) class MailserverUi(QMainWindow):", "item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j, item) def", "in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_eml_type, 0,", "self.cb_edit_annex.isChecked() else gm.gen_eml(header, html) file_path, _ = QFileDialog.getSaveFileName(self, '另存為...', './',", "index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type = self.in_eml_type.text() eml_file = self.in_eml_template.text()", "4, 1, 6) self.right_layout.addWidget(self.btn_annex_file, 4, 10, 1, 1) self.right_layout.addWidget(self.in_scheduler, 5,", "self.tbw_logs.setHorizontalHeaderLabels(col_lst) for i in range(row_num): row_data = list(self.data_logs[i].values()) for j", "self.right_layout.addWidget(self.btn_eml_browse, 1, 10, 1, 1) self.right_layout.addWidget(self.in_recipient_group, 2, 4, 1, 7)", "= QWidget() # 創建主部件的網格佈局 self.main_layout = QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout)", "self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db else Database() insert_send_mail(eml_type, eml_file, user_group,", "logs self.tbw_logs = QTableWidget() self.tbw_logs.verticalHeader().setVisible(False) self.cmb_logs_choice = QComboBox() self.in_logs_data =", "mail_excel = self.in_recipient_excel.text() annex_file = self.in_annex_file.text() url = self.data_db[5] if", "in range(layout.count())] def save_data(self, data): items = self.get_items_from_layout(self.right_layout) data.clear() try:", "self.in_eml_type.text() eml_file = self.in_eml_template.text() user_group = self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text()", "1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_db_port, 1,", "2) def display_update_eml(self): self.clear_layout(self.right_layout) labels = [\"寄件人 :\", \"寄件人名稱 :\",", "self.btn_sendmail_start = QPushButton('執行') self.btn_sendmail_start.clicked.connect(self.send_mail) # 右側物件: smtp self.in_smtp_host = QLineEdit()", "1, 7) self.right_layout.addWidget(self.mail_tab, 5, 4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5,", "import Qt, QDateTime from pyqtgraph import GraphicsLayoutWidget, setConfigOption, setConfigOptions import", "4, 1, 7) self.right_layout.addWidget(self.in_smtp_test, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_smtp_save, 6,", "4, 0, 1, 3) self.left_layout.addWidget(self.btn_update_eml, 5, 0, 1, 3) self.left_layout.addWidget(self.btn_get_logs,", "1, 3) self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1, 2) try: db =", "= QDateTimeEdit(QDateTime.currentDateTime()) self.in_scheduler.setCalendarPopup(True) self.in_scheduler.setDisplayFormat('yyyy-MM-dd hh:mm') self.cb_scheduler = QCheckBox('使用') self.btn_sendmail_start =", "創建左側部件 self.left_widget = QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QGridLayout() self.left_widget.setLayout(self.left_layout) #", "4, 10, 1, 1) self.right_layout.addWidget(self.in_scheduler, 5, 4, 1, 6) self.right_layout.addWidget(self.cb_scheduler,", "QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行') self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout) labels", "3) self.right_layout.addWidget(self.btn_logs_search, 0, 9, 1, 2) try: db = Database(self.data_db[0],", "5, 0, 1, 3) self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1, 3) self.left_layout.addWidget(self.btn_download_logs,", "\"Annex Files (*.jpg *.png *.zip)\") org_files = obj.text() all_files =", "self.in_eml_template.text() user_group = self.in_recipient_group.text() mail_excel = self.in_recipient_excel.text() annex_file = self.in_annex_file.text()", "def eml_reset(self): items = self.get_items_from_layout(self.right_layout) for item in items: if", "'w') as outfile: gen = generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!',", "self.in_db_domain.setPlaceholderText('回收風險資訊動作的網址') self.btn_db_save = QPushButton('儲存') self.btn_db_save.clicked.connect(lambda: self.save_data(self.data_db)) # 右側物件: update eml", "= QApplication.instance() qApp.quit() def main(): app = QApplication(sys.argv) gui =", "'+error, QMessageBox.Ok) else: QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) self.sub_win.in_recipient.clear() except: QMessageBox.warning(self,", "border: 1px solid #32414B; margin-top: 0px; margin-bottom: 0px; padding: 4px;", "1) self.tab_2.addWidget(self.in_edit_web, 1, 1, 1, 1) self.btn_edit_eml_reset = QPushButton('清除') self.btn_edit_eml_reset.clicked.connect(self.eml_reset)", "eml_type = self.in_eml_type.text() eml_file = self.in_eml_template.text() user_group = self.in_recipient_group.text() mail_excel", "# 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget = QWidget() self.left_widget.setObjectName('left_widget') self.left_layout", "self.in_edit_subject = QLineEdit() self.mail_tab = QTabWidget() self.mail_tab.setDocumentMode(True) self.mail_tab.currentChanged.connect(self.print_html) self.mail_tab_1 =", "3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1, 2) self.right_layout.addWidget(self.in_logs_data, 0,", "type(QLineEdit()): data.append(item.text()) elif type(item) == type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!', '儲存成功!',", "condition == 'date' and content in str(self.data_logs[i][condition]): switch = True", "# header = {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText()", "self.data_logs = db.get_logs() self.data_temp_logs = deepcopy(self.data_logs) if self.data_logs: row_num =", "for j in range(col_num): temp_data = row_data[j] item = QTableWidgetItem(str(temp_data))", "= QGridLayout() self.tab_1.setContentsMargins(0,0,0,0) self.tab_2.setContentsMargins(0,0,0,0) self.mail_tab_1.setLayout(self.tab_1) self.mail_tab_2.setLayout(self.tab_2) self.in_edit_html = QTextEdit() self.in_edit_web", "7) self.right_layout.addWidget(self.in_edit_sender_name, 1, 4, 1, 7) self.right_layout.addWidget(self.cb_edit_annex, 2, 4, 1,", "3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_db_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_db_port,", "sm.close() db.__disconnect__() QMessageBox.information(self, 'Success!', '信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!',", "右側物件: update eml self.in_edit_sender = QLineEdit() self.in_edit_sender_name = QLineEdit() self.cb_edit_annex", "def __init__(self): super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias = True)", "[] self.data_logs = [] self.data_temp_logs = [] # self.sub_win =", "QPushButton, QComboBox, QCheckBox, QDateTimeEdit, QTextEdit, QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView) from", "QLineEdit() self.in_data.setPlaceholderText(\"暫無\") self.left_layout.addWidget(self.in_data, 1, 0, 1, 3) # 主要功能 log", "[\"資料庫 HOST :\", \"資料庫 PORT :\", \"資料庫 帳號 :\", \"資料庫", "6, 7, 1, 2) def display_db_setting(self): self.clear_layout(self.right_layout) # 在右邊新增物件 labels", "int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4]) if self.data_db[:5] else Database() self.data_logs =", "if self.data_smtp: self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else: QMessageBox.warning(self, 'Failed!',", "self.main_layout = QGridLayout() # 設置窗口主部件佈局為網格佈局 self.main_widget.setLayout(self.main_layout) # 創建左側部件 self.left_widget =", "# 創建右側部件 self.right_widget = QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QGridLayout() self.right_widget.setLayout(self.right_layout)", "def show_sub_win(self): if self.data_smtp: self.sub_win = SubWindow() self.sub_win.btn_send.clicked.connect(self.send_test) self.sub_win.show() else:", "QLineEdit() self.main_layout.addWidget(self.in_recipient, 0, 1, 1, 5) self.btn_send = QPushButton('寄送') self.main_layout.addWidget(self.btn_send,", "QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '儲存失敗!', QMessageBox.Ok) else:", "self.setWindowOpacity(1) # 窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked { height:", "QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def eml_open(self): self.in_edit_html.clear() file_name, _ =", "self.data_db = [] self.data_logs = [] self.data_temp_logs = [] #", "QComboBox::item:checked { height: 12px; border: 1px solid #32414B; margin-top: 0px;", "file_name, _ = QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Annex Files (*.jpg *.png", "1, 0, 1, 3) # 主要功能 log self.query_result = QTableWidget()", "import Client from email import generator from pandas import DataFrame", "HOST :\", \"資料庫 PORT :\", \"資料庫 帳號 :\", \"資料庫 密碼", "self.left_layout.addWidget(self.btn_get_logs, 6, 0, 1, 3) self.left_layout.addWidget(self.btn_download_logs, 7, 0, 1, 3)", "= QWidget() self.mail_tab_2 = QWidget() self.mail_tab.addTab(self.mail_tab_1, 'Html') self.mail_tab.addTab(self.mail_tab_2, 'Web') self.tab_1", "Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0, 4, 1, 7) self.right_layout.addWidget(self.in_smtp_port, 1, 4, 1,", "self.in_eml_template = QLineEdit() self.btn_eml_browse = QPushButton('瀏覽') self.btn_eml_browse.clicked.connect(lambda: self.open_eml(self.in_eml_template)) self.in_recipient_group =", "self.cmb_logs_choice = QComboBox() self.in_logs_data = QLineEdit() self.in_logs_data.setPlaceholderText(\"輸入資料\") self.btn_logs_search = QPushButton('執行')", "self.right_layout.addWidget(self.in_db_domain, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_db_save, 6, 9, 1, 2)", "1, 1) self.right_layout.addWidget(self.in_annex_file , 4, 4, 1, 6) self.right_layout.addWidget(self.btn_annex_file, 4,", "4, 4, 1, 7) self.right_layout.addWidget(self.mail_tab, 5, 4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset,", "4, 1, 7) self.right_layout.addWidget(self.in_db_domain, 5, 4, 1, 7) self.right_layout.addWidget(self.btn_db_save, 6,", "if switch: self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j in", "self.init_ui() self.data_smtp = [] self.data_db = [] self.data_logs = []", "PORT :\", \"資料庫 帳號 :\", \"資料庫 密碼 :\", \"使用資料庫名稱 :\",", "= self.in_recipient_excel.text() annex_file = self.in_annex_file.text() url = self.data_db[5] if self.data_db", "self.data_smtp else Smtp() db = Database(self.data_db[0], int(self.data_db[1]), self.data_db[2], self.data_db[3], self.data_db[4])", "self.tbw_logs.insertRow(self.tbw_logs.rowCount()) row_data = list(self.data_logs[i].values()) self.data_temp_logs.append(self.data_logs[i]) for j in range(col_num): temp_data", "QLineEdit() self.in_db_password = QLineEdit() self.in_db_database = QLineEdit() self.in_db_domain = QLineEdit()", "self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3, 11, 8) self.right_layout.addWidget(QLabel('查詢 :'), 0, 3,", "def display_logs(self): self.data_temp_logs = [] self.tbw_logs.setRowCount(0) self.clear_layout(self.right_layout) self.right_layout.addWidget(self.tbw_logs, 1, 3,", "7) self.right_layout.addWidget(self.in_db_user, 2, 4, 1, 7) self.right_layout.addWidget(self.in_db_password, 3, 4, 1,", "== type(QLineEdit()): data.append(item.text()) elif type(item) == type(QCheckBox()): data.append(item.isChecked()) QMessageBox.information(self, 'Success!',", "= self.data_db[5] if self.data_db else 'http://yumail.myvnc.com' try: if self.cb_scheduler.isChecked(): my_time", ":'), 0, 3, 1, 1) self.right_layout.addWidget(self.cmb_logs_choice, 0, 4, 1, 2)", "email import generator from pandas import DataFrame from copy import", "QPushButton('測試') self.btn_smtp_test.clicked.connect(self.show_sub_win) # 右側物件: db self.in_db_host = QLineEdit() self.in_db_port =", ":\", \"資料庫 帳號 :\", \"資料庫 密碼 :\", \"使用資料庫名稱 :\", \"回收網址", "2, 3) self.query_result.verticalHeader().setVisible(False) self.right_display = GraphicsLayoutWidget() self.right_layout.addWidget(self.right_display, 0, 3, 12,", "QFileDialog.getOpenFileName(self, \"選取檔案\", \"./\", \"Word Files (*.doc *.docx)\") obj.setText(file_name) def open_annex(self,", "測試信件內容 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3,", "{'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition = self.cmb_logs_choice.currentText() content = self.in_logs_data.text()", ") def init_ui(self): # 創建視窗主部件 self.main_widget = QWidget() # 創建主部件的網格佈局", "1, 6) self.right_layout.addWidget(self.cb_scheduler, 5, 10, 1, 1) self.right_layout.addWidget(self.btn_sendmail_start, 6, 9,", "QPalette, QColor, QBrush from PyQt5.QtCore import Qt, QDateTime from pyqtgraph", "if index: self.in_edit_web.setHtml(self.in_edit_html.toPlainText()) def send_mail(self): eml_type = self.in_eml_type.text() eml_file =", "insert_send_mail(eml_type, eml_file, user_group, mail_excel, sm, db, annex=annex_file, url=url) sm.close() db.__disconnect__()", "'Failed!', '儲存失敗!', QMessageBox.Ok) def eml_reset(self): items = self.get_items_from_layout(self.right_layout) for item", "窗口透明度 self.main_layout.setSpacing(0) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.main_widget.setStyleSheet( \"\"\" QComboBox::item:checked { height: 12px; border:", "self.tbw_logs.setRowCount(0) # header = {'郵件類型':'type', '郵件主旨':'subject', '使用者群組':'user_group', '使用者信箱':'user_email'} condition =", "db.__disconnect__() def get_items_from_layout(self, layout): return [layout.itemAt(i).widget() for i in range(layout.count())]", ":',\"設定排程 :\"] for i, label in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3,", "= deepcopy(self.data_logs) if self.data_logs: row_num = len(self.data_logs) col_num = len(self.data_logs[0])", "not self.data_logs or not self.in_logs_data.text(): return self.data_temp_logs = [] self.tbw_logs.setRowCount(0)", "not html: return try: msg = gm.gen_eml(header, html, annex_file) if", "labels = [\"SMTP HOST :\", \"SMTP PORT :\", \"SMTP 帳號", ":\", \"SMTP 密碼 :\", \"SMTP SSL :\", \" 測試信件內容 :\"]", "1, 2) self.right_layout.addWidget(self.btn_edit_eml_save, 11, 9, 1, 2) def display_logs(self): self.data_temp_logs", "gm.get_msg(file_name) self.in_edit_sender.setText(header[2]) self.in_edit_sender_name.setText(header[1]) self.in_edit_subject.setText(header[0]) self.in_edit_html.insertPlainText(html) def eml_save(self): header, msg =", ":\", \"內容 :\"] for i, label in enumerate(labels): self.label =", "'信件寄出成功!', QMessageBox.Ok) except: QMessageBox.warning(self, 'Failed!', '信件寄出失敗!', QMessageBox.Ok) def show_sub_win(self): if", "5, 4, 6, 7) self.right_layout.addWidget(self.btn_edit_eml_reset, 11, 5, 1, 2) self.right_layout.addWidget(self.btn_edit_eml_read,", "row_num = len(self.data_logs) col_num = len(self.data_logs[0]) # self.tbw_logs.setRowCount(row_num) self.tbw_logs.setColumnCount(col_num) for", "= QLineEdit() self.in_smtp_password = QLineEdit() self.cb_smtp_ssl = QCheckBox('使用') self.in_smtp_test =", "class MailserverUi(QMainWindow): def __init__(self): super().__init__() setConfigOption('background', '#19232D') setConfigOption('foreground', 'd') setConfigOptions(antialias", "\" 收件人群組 :\", \"收件人資料 :\", '附件資料 :',\"設定排程 :\"] for i,", "db self.in_db_host = QLineEdit() self.in_db_port = QLineEdit() self.in_db_user = QLineEdit()", "margin-top: 0px; margin-bottom: 0px; padding: 4px; padding-left: 0px; } \"\"\"", "annex_file = self.in_annex_file.text() url = self.data_db[5] if self.data_db else 'http://yumail.myvnc.com'", "outfile: gen = generator.Generator(outfile) gen.flatten(msg) QMessageBox.information(self, 'Success!', '儲存成功!', QMessageBox.Ok) except:", "self.btn_logs_search.clicked.connect(self.logs_change) def display_send_mail(self): self.clear_layout(self.right_layout) labels = [ \"信件類型 :\", \"信件模板", "= row_data[j] item = QTableWidgetItem(str(temp_data)) item.setForeground(QBrush(QColor(144, 182, 240))) self.tbw_logs.setItem(self.tbw_logs.rowCount()-1, j,", "= Client() client.send(self.data_smtp[:4], self.data_db[:5], eml_type, eml_file, user_group, mail_excel, annex_file, url,", "in enumerate(labels): self.right_layout.addWidget(QLabel(label), i, 3, 1, 1, Qt.AlignRight) self.right_layout.addWidget(self.in_smtp_host, 0,", "'資料庫連結失敗!', QMessageBox.Ok) else: db.__disconnect__() def get_items_from_layout(self, layout): return [layout.itemAt(i).widget() for" ]
[ "To avoid ambiguity, please specify only one of them.\") elif", "Conv2DMMLayer: %s\" % border_mode) else: self.pad = pad self.W =", "[self.b] if self.b is not None else [] def get_output_shape_for(self,", "self.corr_mm_op(contiguous_input, contiguous_filters) if self.b is None: activation = conved elif", "self.b is not None else [] def get_output_shape_for(self, input_shape): batch_size", "T from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM from", "all layers that rely on GpuCorrMM directly class MMLayer(base.Layer): pass", "super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity is None: self.nonlinearity = nonlinearities.identity else:", "import theano.tensor as T from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas", "num_input_channels, self.filter_size[0], self.filter_size[1]) def get_params(self): return [self.W] + self.get_bias_params() def", "return (self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1]) def get_params(self): return [self.W] +", "import base # base class for all layers that rely", "self.W if self.flip_filters: filters = filters[:, :, ::-1, ::-1] #", "# only works for odd filter size, but the even", "self.flip_filters: filters = filters[:, :, ::-1, ::-1] # flip width,", "None and pad is None: # no option specified, default", "None: self.b = None elif self.untie_biases: output_shape = self.get_output_shape() self.b", "self.filter_size = filter_size self.strides = strides self.untie_biases = untie_biases self.flip_filters", "1) // 2) else: raise RuntimeError(\"Unsupported border_mode for Conv2DMMLayer: %s\"", "works for odd filter size, but the even filter size", "border_mode for Conv2DMMLayer: %s\" % border_mode) else: self.pad = pad", "theano import theano.tensor as T from theano.sandbox.cuda.basic_ops import gpu_contiguous from", "import nonlinearities from . import base # base class for", "self.flip_filters = flip_filters if border_mode is not None and pad", "rely on GpuCorrMM directly class MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer): def", "::-1] # flip width, height contiguous_filters = gpu_contiguous(filters) contiguous_input =", "+ self.get_bias_params() def get_bias_params(self): return [self.b] if self.b is not", "[] def get_output_shape_for(self, input_shape): batch_size = input_shape[0] input_width, input_height =", "only one of them.\") elif border_mode is None and pad", "input_width, input_height = input_shape[2:4] output_width = (input_width + 2*self.pad[0] -", "if nonlinearity is None: self.nonlinearity = nonlinearities.identity else: self.nonlinearity =", "num_filters self.filter_size = filter_size self.strides = strides self.untie_biases = untie_biases", "'border_mode' and 'pad'. To avoid ambiguity, please specify only one", "self.num_filters, output_width, output_height) def get_output_for(self, input, *args, **kwargs): filters =", "self.b.dimshuffle('x', 0, 1, 2) else: activation = conved + self.b.dimshuffle('x',", "filter_size self.strides = strides self.untie_biases = untie_biases self.flip_filters = flip_filters", "RuntimeError(\"Unsupported border_mode for Conv2DMMLayer: %s\" % border_mode) else: self.pad =", "np import theano import theano.tensor as T from theano.sandbox.cuda.basic_ops import", "elif border_mode == 'same': # only works for odd filter", "self.b = self.create_param(b, (num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self):", "self.W = self.create_param(W, self.get_W_shape()) if b is None: self.b =", "one of them.\") elif border_mode is None and pad is", "is None: self.b = None elif self.untie_biases: output_shape = self.get_output_shape()", "// self.strides[1] + 1 return (batch_size, self.num_filters, output_width, output_height) def", "2, (self.filter_size[1] - 1) // 2) else: raise RuntimeError(\"Unsupported border_mode", "def get_output_shape_for(self, input_shape): batch_size = input_shape[0] input_width, input_height = input_shape[2:4]", "# base class for all layers that rely on GpuCorrMM", "and pad is None: # no option specified, default to", "pad self.W = self.create_param(W, self.get_W_shape()) if b is None: self.b", ":, ::-1, ::-1] # flip width, height contiguous_filters = gpu_contiguous(filters)", "contiguous_input = gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input, contiguous_filters) if self.b is", "layers that rely on GpuCorrMM directly class MMLayer(base.Layer): pass class", "'full': self.pad = (self.filter_size[0] - 1, self.filter_size[1] -1) elif border_mode", "from .. import nonlinearities from . import base # base", "elif border_mode is None and pad is None: # no", "= nonlinearities.identity else: self.nonlinearity = nonlinearity self.num_filters = num_filters self.filter_size", "import GpuCorrMM from .. import init from .. import nonlinearities", "filter_size, strides=(1, 1), border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False):", "not worth supporting. self.pad = ((self.filter_size[0] - 1) // 2,", "None: activation = conved elif self.untie_biases: activation = conved +", "= ((self.filter_size[0] - 1) // 2, (self.filter_size[1] - 1) //", "border_mode is not None: if border_mode == 'valid': self.pad =", "else: activation = conved + self.b.dimshuffle('x', 0, 'x', 'x') return", "b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity is None:", "import gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM from .. import init", "self.pad = ((self.filter_size[0] - 1) // 2, (self.filter_size[1] - 1)", "is not None and pad is not None: raise RuntimeError(\"You", "RuntimeError(\"You cannot specify both 'border_mode' and 'pad'. To avoid ambiguity,", "= GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1] return (self.num_filters,", "output_width = (input_width + 2*self.pad[0] - self.filter_size[0]) // self.strides[0] +", "else: self.b = self.create_param(b, (num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad) def", "= conved elif self.untie_biases: activation = conved + self.b.dimshuffle('x', 0,", "border_mode is None and pad is None: # no option", "option specified, default to valid mode self.pad = (0, 0)", "None else [] def get_output_shape_for(self, input_shape): batch_size = input_shape[0] input_width,", "import init from .. import nonlinearities from . import base", "supporting. self.pad = ((self.filter_size[0] - 1) // 2, (self.filter_size[1] -", "no option specified, default to valid mode self.pad = (0,", "output_shape[3])) else: self.b = self.create_param(b, (num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad)", "= pad self.W = self.create_param(W, self.get_W_shape()) if b is None:", "self.nonlinearity = nonlinearity self.num_filters = num_filters self.filter_size = filter_size self.strides", "as T from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM", "nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity is None: self.nonlinearity", "for all layers that rely on GpuCorrMM directly class MMLayer(base.Layer):", "get_output_for(self, input, *args, **kwargs): filters = self.W if self.flip_filters: filters", "and 'pad'. To avoid ambiguity, please specify only one of", ".. import nonlinearities from . import base # base class", "if border_mode == 'valid': self.pad = (0, 0) elif border_mode", "on GpuCorrMM directly class MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer): def __init__(self,", "border_mode == 'same': # only works for odd filter size,", "None elif self.untie_biases: output_shape = self.get_output_shape() self.b = self.create_param(b, (num_filters,", "size case is probably not worth supporting. self.pad = ((self.filter_size[0]", "0) elif border_mode is not None: if border_mode == 'valid':", "but the even filter size case is probably not worth", "None: # no option specified, default to valid mode self.pad", "self).__init__(input_layer) if nonlinearity is None: self.nonlinearity = nonlinearities.identity else: self.nonlinearity", "contiguous_filters) if self.b is None: activation = conved elif self.untie_biases:", "filters = self.W if self.flip_filters: filters = filters[:, :, ::-1,", "contiguous_filters = gpu_contiguous(filters) contiguous_input = gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input, contiguous_filters)", "Conv2DMMLayer(MMLayer): def __init__(self, input_layer, num_filters, filter_size, strides=(1, 1), border_mode=None, untie_biases=False,", "'pad'. To avoid ambiguity, please specify only one of them.\")", "GpuCorrMM from .. import init from .. import nonlinearities from", "::-1, ::-1] # flip width, height contiguous_filters = gpu_contiguous(filters) contiguous_input", "return [self.W] + self.get_bias_params() def get_bias_params(self): return [self.b] if self.b", "flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity is None: self.nonlinearity = nonlinearities.identity", "self.strides = strides self.untie_biases = untie_biases self.flip_filters = flip_filters if", "gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input, contiguous_filters) if self.b is None: activation", "self.filter_size[1] -1) elif border_mode == 'same': # only works for", "def get_params(self): return [self.W] + self.get_bias_params() def get_bias_params(self): return [self.b]", "nonlinearity is None: self.nonlinearity = nonlinearities.identity else: self.nonlinearity = nonlinearity", "self.filter_size[0], self.filter_size[1]) def get_params(self): return [self.W] + self.get_bias_params() def get_bias_params(self):", "+ self.b.dimshuffle('x', 0, 1, 2) else: activation = conved +", "input_height = input_shape[2:4] output_width = (input_width + 2*self.pad[0] - self.filter_size[0])", "border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if", "output_shape = self.get_output_shape() self.b = self.create_param(b, (num_filters, output_shape[2], output_shape[3])) else:", "to valid mode self.pad = (0, 0) elif border_mode is", "not None and pad is not None: raise RuntimeError(\"You cannot", "untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity", "size, but the even filter size case is probably not", "= num_filters self.filter_size = filter_size self.strides = strides self.untie_biases =", "theano.sandbox.cuda.blas import GpuCorrMM from .. import init from .. import", "both 'border_mode' and 'pad'. To avoid ambiguity, please specify only", "that rely on GpuCorrMM directly class MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer):", "+ 1 return (batch_size, self.num_filters, output_width, output_height) def get_output_for(self, input,", "only works for odd filter size, but the even filter", "is None and pad is None: # no option specified,", "= gpu_contiguous(filters) contiguous_input = gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input, contiguous_filters) if", "output_height) def get_output_for(self, input, *args, **kwargs): filters = self.W if", "1, self.filter_size[1] -1) elif border_mode == 'same': # only works", "== 'valid': self.pad = (0, 0) elif border_mode == 'full':", "import theano import theano.tensor as T from theano.sandbox.cuda.basic_ops import gpu_contiguous", "= self.create_param(b, (num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self): num_input_channels", "gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM from .. import init from", "activation = conved + self.b.dimshuffle('x', 0, 'x', 'x') return self.nonlinearity(activation)", "%s\" % border_mode) else: self.pad = pad self.W = self.create_param(W,", "= conved + self.b.dimshuffle('x', 0, 1, 2) else: activation =", "filter size, but the even filter size case is probably", "elif self.untie_biases: output_shape = self.get_output_shape() self.b = self.create_param(b, (num_filters, output_shape[2],", "gpu_contiguous(filters) contiguous_input = gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input, contiguous_filters) if self.b", "self.nonlinearity = nonlinearities.identity else: self.nonlinearity = nonlinearity self.num_filters = num_filters", "raise RuntimeError(\"Unsupported border_mode for Conv2DMMLayer: %s\" % border_mode) else: self.pad", "base class for all layers that rely on GpuCorrMM directly", "pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity is None: self.nonlinearity =", "'same': # only works for odd filter size, but the", "is None: self.nonlinearity = nonlinearities.identity else: self.nonlinearity = nonlinearity self.num_filters", "self.pad = pad self.W = self.create_param(W, self.get_W_shape()) if b is", "(self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1]) def get_params(self): return [self.W] + self.get_bias_params()", "init from .. import nonlinearities from . import base #", "(num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1]", ". import base # base class for all layers that", "is not None else [] def get_output_shape_for(self, input_shape): batch_size =", "layers \"\"\" import numpy as np import theano import theano.tensor", "def get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1])", "+ 2*self.pad[1] - self.filter_size[1]) // self.strides[1] + 1 return (batch_size,", "= None elif self.untie_biases: output_shape = self.get_output_shape() self.b = self.create_param(b,", "border_mode == 'valid': self.pad = (0, 0) elif border_mode ==", "get_output_shape_for(self, input_shape): batch_size = input_shape[0] input_width, input_height = input_shape[2:4] output_width", "not None: raise RuntimeError(\"You cannot specify both 'border_mode' and 'pad'.", "raise RuntimeError(\"You cannot specify both 'border_mode' and 'pad'. To avoid", "self.get_bias_params() def get_bias_params(self): return [self.b] if self.b is not None", "get_bias_params(self): return [self.b] if self.b is not None else []", "// 2) else: raise RuntimeError(\"Unsupported border_mode for Conv2DMMLayer: %s\" %", "MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer): def __init__(self, input_layer, num_filters, filter_size, strides=(1,", "# no option specified, default to valid mode self.pad =", "def get_bias_params(self): return [self.b] if self.b is not None else", "1 return (batch_size, self.num_filters, output_width, output_height) def get_output_for(self, input, *args,", "(num_filters, output_shape[2], output_shape[3])) else: self.b = self.create_param(b, (num_filters,)) self.corr_mm_op =", "nonlinearities from . import base # base class for all", "for Conv2DMMLayer: %s\" % border_mode) else: self.pad = pad self.W", "= self.corr_mm_op(contiguous_input, contiguous_filters) if self.b is None: activation = conved", "output_height = (input_height + 2*self.pad[1] - self.filter_size[1]) // self.strides[1] +", "self.create_param(W, self.get_W_shape()) if b is None: self.b = None elif", "nonlinearities.identity else: self.nonlinearity = nonlinearity self.num_filters = num_filters self.filter_size =", "= self.W if self.flip_filters: filters = filters[:, :, ::-1, ::-1]", "self.filter_size[0]) // self.strides[0] + 1 output_height = (input_height + 2*self.pad[1]", "class Conv2DMMLayer(MMLayer): def __init__(self, input_layer, num_filters, filter_size, strides=(1, 1), border_mode=None,", "conved elif self.untie_biases: activation = conved + self.b.dimshuffle('x', 0, 1,", "activation = conved + self.b.dimshuffle('x', 0, 1, 2) else: activation", "untie_biases self.flip_filters = flip_filters if border_mode is not None and", "valid mode self.pad = (0, 0) elif border_mode is not", "if self.b is not None else [] def get_output_shape_for(self, input_shape):", "the even filter size case is probably not worth supporting.", "from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM from ..", "width, height contiguous_filters = gpu_contiguous(filters) contiguous_input = gpu_contiguous(input) conved =", "= (self.filter_size[0] - 1, self.filter_size[1] -1) elif border_mode == 'same':", "None and pad is not None: raise RuntimeError(\"You cannot specify", "input_layer, num_filters, filter_size, strides=(1, 1), border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify,", "- 1) // 2, (self.filter_size[1] - 1) // 2) else:", "None: raise RuntimeError(\"You cannot specify both 'border_mode' and 'pad'. To", "output_shape[2], output_shape[3])) else: self.b = self.create_param(b, (num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides,", "height contiguous_filters = gpu_contiguous(filters) contiguous_input = gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input,", "convolutional layers \"\"\" import numpy as np import theano import", "= input_shape[0] input_width, input_height = input_shape[2:4] output_width = (input_width +", "self.strides[1] + 1 return (batch_size, self.num_filters, output_width, output_height) def get_output_for(self,", "worth supporting. self.pad = ((self.filter_size[0] - 1) // 2, (self.filter_size[1]", "self.pad = (self.filter_size[0] - 1, self.filter_size[1] -1) elif border_mode ==", "for odd filter size, but the even filter size case", "pad is not None: raise RuntimeError(\"You cannot specify both 'border_mode'", "GpuCorrMM directly class MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer): def __init__(self, input_layer,", "== 'same': # only works for odd filter size, but", "strides=(1, 1), border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer,", "*args, **kwargs): filters = self.W if self.flip_filters: filters = filters[:,", "'valid': self.pad = (0, 0) elif border_mode == 'full': self.pad", "flip width, height contiguous_filters = gpu_contiguous(filters) contiguous_input = gpu_contiguous(input) conved", "self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1] return", "theano.tensor as T from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas import", "output_width, output_height) def get_output_for(self, input, *args, **kwargs): filters = self.W", "specify both 'border_mode' and 'pad'. To avoid ambiguity, please specify", "nonlinearity self.num_filters = num_filters self.filter_size = filter_size self.strides = strides", "flip_filters if border_mode is not None and pad is not", "= gpu_contiguous(input) conved = self.corr_mm_op(contiguous_input, contiguous_filters) if self.b is None:", "= self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1]) def get_params(self): return", "import numpy as np import theano import theano.tensor as T", "__init__(self, input_layer, num_filters, filter_size, strides=(1, 1), border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.),", "self.get_W_shape()) if b is None: self.b = None elif self.untie_biases:", "def __init__(self, input_layer, num_filters, filter_size, strides=(1, 1), border_mode=None, untie_biases=False, W=init.Uniform(),", "pad is None: # no option specified, default to valid", "self.b = self.create_param(b, (num_filters, output_shape[2], output_shape[3])) else: self.b = self.create_param(b,", "odd filter size, but the even filter size case is", "0, 1, 2) else: activation = conved + self.b.dimshuffle('x', 0,", "def get_output_for(self, input, *args, **kwargs): filters = self.W if self.flip_filters:", "- self.filter_size[1]) // self.strides[1] + 1 return (batch_size, self.num_filters, output_width,", "num_filters, filter_size, strides=(1, 1), border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None,", "[self.W] + self.get_bias_params() def get_bias_params(self): return [self.b] if self.b is", "- 1, self.filter_size[1] -1) elif border_mode == 'same': # only", "self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1]) def get_params(self): return [self.W]", "is probably not worth supporting. self.pad = ((self.filter_size[0] - 1)", "(input_width + 2*self.pad[0] - self.filter_size[0]) // self.strides[0] + 1 output_height", "+ 2*self.pad[0] - self.filter_size[0]) // self.strides[0] + 1 output_height =", "mode self.pad = (0, 0) elif border_mode is not None:", "strides self.untie_biases = untie_biases self.flip_filters = flip_filters if border_mode is", "= self.create_param(b, (num_filters, output_shape[2], output_shape[3])) else: self.b = self.create_param(b, (num_filters,))", "= (0, 0) elif border_mode is not None: if border_mode", "is None: # no option specified, default to valid mode", "1) // 2, (self.filter_size[1] - 1) // 2) else: raise", "self.pad = (0, 0) elif border_mode is not None: if", "((self.filter_size[0] - 1) // 2, (self.filter_size[1] - 1) // 2)", "input_shape[0] input_width, input_height = input_shape[2:4] output_width = (input_width + 2*self.pad[0]", "= (input_height + 2*self.pad[1] - self.filter_size[1]) // self.strides[1] + 1", "2) else: activation = conved + self.b.dimshuffle('x', 0, 'x', 'x')", "directly class MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer): def __init__(self, input_layer, num_filters,", "conved = self.corr_mm_op(contiguous_input, contiguous_filters) if self.b is None: activation =", "else: raise RuntimeError(\"Unsupported border_mode for Conv2DMMLayer: %s\" % border_mode) else:", "self.filter_size[1]) def get_params(self): return [self.W] + self.get_bias_params() def get_bias_params(self): return", "self.b = None elif self.untie_biases: output_shape = self.get_output_shape() self.b =", "= filters[:, :, ::-1, ::-1] # flip width, height contiguous_filters", "% border_mode) else: self.pad = pad self.W = self.create_param(W, self.get_W_shape())", "probably not worth supporting. self.pad = ((self.filter_size[0] - 1) //", "if self.b is None: activation = conved elif self.untie_biases: activation", "please specify only one of them.\") elif border_mode is None", "else: self.pad = pad self.W = self.create_param(W, self.get_W_shape()) if b", "= self.create_param(W, self.get_W_shape()) if b is None: self.b = None", "from . import base # base class for all layers", "= untie_biases self.flip_filters = flip_filters if border_mode is not None", "(input_height + 2*self.pad[1] - self.filter_size[1]) // self.strides[1] + 1 return", "= (0, 0) elif border_mode == 'full': self.pad = (self.filter_size[0]", "ambiguity, please specify only one of them.\") elif border_mode is", "**kwargs): filters = self.W if self.flip_filters: filters = filters[:, :,", "self.untie_biases: activation = conved + self.b.dimshuffle('x', 0, 1, 2) else:", "case is probably not worth supporting. self.pad = ((self.filter_size[0] -", "0) elif border_mode == 'full': self.pad = (self.filter_size[0] - 1,", "self.strides[0] + 1 output_height = (input_height + 2*self.pad[1] - self.filter_size[1])", "even filter size case is probably not worth supporting. self.pad", "b is None: self.b = None elif self.untie_biases: output_shape =", "1, 2) else: activation = conved + self.b.dimshuffle('x', 0, 'x',", "2) else: raise RuntimeError(\"Unsupported border_mode for Conv2DMMLayer: %s\" % border_mode)", "get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1]) def", "self.untie_biases = untie_biases self.flip_filters = flip_filters if border_mode is not", "get_params(self): return [self.W] + self.get_bias_params() def get_bias_params(self): return [self.b] if", "pad=self.pad) def get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels, self.filter_size[0],", "2*self.pad[0] - self.filter_size[0]) // self.strides[0] + 1 output_height = (input_height", "(batch_size, self.num_filters, output_width, output_height) def get_output_for(self, input, *args, **kwargs): filters", "from theano.sandbox.cuda.blas import GpuCorrMM from .. import init from ..", "activation = conved elif self.untie_biases: activation = conved + self.b.dimshuffle('x',", "= nonlinearity self.num_filters = num_filters self.filter_size = filter_size self.strides =", "= self.get_output_shape() self.b = self.create_param(b, (num_filters, output_shape[2], output_shape[3])) else: self.b", "as np import theano import theano.tensor as T from theano.sandbox.cuda.basic_ops", "elif self.untie_biases: activation = conved + self.b.dimshuffle('x', 0, 1, 2)", "not None else [] def get_output_shape_for(self, input_shape): batch_size = input_shape[0]", "+ 1 output_height = (input_height + 2*self.pad[1] - self.filter_size[1]) //", "None: if border_mode == 'valid': self.pad = (0, 0) elif", "filter size case is probably not worth supporting. self.pad =", "# flip width, height contiguous_filters = gpu_contiguous(filters) contiguous_input = gpu_contiguous(input)", "\"\"\" import numpy as np import theano import theano.tensor as", "input_shape[2:4] output_width = (input_width + 2*self.pad[0] - self.filter_size[0]) // self.strides[0]", "not None: if border_mode == 'valid': self.pad = (0, 0)", "(0, 0) elif border_mode == 'full': self.pad = (self.filter_size[0] -", "GpuCorrMM-based convolutional layers \"\"\" import numpy as np import theano", "and pad is not None: raise RuntimeError(\"You cannot specify both", "if self.flip_filters: filters = filters[:, :, ::-1, ::-1] # flip", "self.filter_size[1]) // self.strides[1] + 1 return (batch_size, self.num_filters, output_width, output_height)", "from .. import init from .. import nonlinearities from .", "numpy as np import theano import theano.tensor as T from", "self.pad = (0, 0) elif border_mode == 'full': self.pad =", "// self.strides[0] + 1 output_height = (input_height + 2*self.pad[1] -", "border_mode == 'full': self.pad = (self.filter_size[0] - 1, self.filter_size[1] -1)", "self.untie_biases: output_shape = self.get_output_shape() self.b = self.create_param(b, (num_filters, output_shape[2], output_shape[3]))", "= flip_filters if border_mode is not None and pad is", "(self.filter_size[0] - 1, self.filter_size[1] -1) elif border_mode == 'same': #", "if b is None: self.b = None elif self.untie_biases: output_shape", "pass class Conv2DMMLayer(MMLayer): def __init__(self, input_layer, num_filters, filter_size, strides=(1, 1),", "(self.filter_size[1] - 1) // 2) else: raise RuntimeError(\"Unsupported border_mode for", "num_input_channels = self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels, self.filter_size[0], self.filter_size[1]) def get_params(self):", "is None: activation = conved elif self.untie_biases: activation = conved", "= filter_size self.strides = strides self.untie_biases = untie_biases self.flip_filters =", "-1) elif border_mode == 'same': # only works for odd", "= strides self.untie_biases = untie_biases self.flip_filters = flip_filters if border_mode", "- self.filter_size[0]) // self.strides[0] + 1 output_height = (input_height +", "self.num_filters = num_filters self.filter_size = filter_size self.strides = strides self.untie_biases", "self.create_param(b, (num_filters,)) self.corr_mm_op = GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self): num_input_channels =", "input, *args, **kwargs): filters = self.W if self.flip_filters: filters =", "them.\") elif border_mode is None and pad is None: #", "2*self.pad[1] - self.filter_size[1]) // self.strides[1] + 1 return (batch_size, self.num_filters,", "theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM from .. import", "border_mode is not None and pad is not None: raise", "specify only one of them.\") elif border_mode is None and", "of them.\") elif border_mode is None and pad is None:", "// 2, (self.filter_size[1] - 1) // 2) else: raise RuntimeError(\"Unsupported", "= input_shape[2:4] output_width = (input_width + 2*self.pad[0] - self.filter_size[0]) //", "return [self.b] if self.b is not None else [] def", "GpuCorrMM(subsample=self.strides, pad=self.pad) def get_W_shape(self): num_input_channels = self.input_layer.get_output_shape()[1] return (self.num_filters, num_input_channels,", "None: self.nonlinearity = nonlinearities.identity else: self.nonlinearity = nonlinearity self.num_filters =", "input_shape): batch_size = input_shape[0] input_width, input_height = input_shape[2:4] output_width =", "filters[:, :, ::-1, ::-1] # flip width, height contiguous_filters =", "elif border_mode is not None: if border_mode == 'valid': self.pad", "avoid ambiguity, please specify only one of them.\") elif border_mode", "return (batch_size, self.num_filters, output_width, output_height) def get_output_for(self, input, *args, **kwargs):", "is not None: if border_mode == 'valid': self.pad = (0,", "specified, default to valid mode self.pad = (0, 0) elif", "1 output_height = (input_height + 2*self.pad[1] - self.filter_size[1]) // self.strides[1]", "if border_mode is not None and pad is not None:", "1), border_mode=None, untie_biases=False, W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer)", "elif border_mode == 'full': self.pad = (self.filter_size[0] - 1, self.filter_size[1]", "base # base class for all layers that rely on", "class MMLayer(base.Layer): pass class Conv2DMMLayer(MMLayer): def __init__(self, input_layer, num_filters, filter_size,", "cannot specify both 'border_mode' and 'pad'. To avoid ambiguity, please", "border_mode) else: self.pad = pad self.W = self.create_param(W, self.get_W_shape()) if", "default to valid mode self.pad = (0, 0) elif border_mode", "W=init.Uniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, pad=None, flip_filters=False): super(Conv2DMMLayer, self).__init__(input_layer) if nonlinearity is", "\"\"\" GpuCorrMM-based convolutional layers \"\"\" import numpy as np import", "else: self.nonlinearity = nonlinearity self.num_filters = num_filters self.filter_size = filter_size", "conved + self.b.dimshuffle('x', 0, 1, 2) else: activation = conved", "class for all layers that rely on GpuCorrMM directly class", "filters = filters[:, :, ::-1, ::-1] # flip width, height", "- 1) // 2) else: raise RuntimeError(\"Unsupported border_mode for Conv2DMMLayer:", "is not None: raise RuntimeError(\"You cannot specify both 'border_mode' and", "(0, 0) elif border_mode is not None: if border_mode ==", "batch_size = input_shape[0] input_width, input_height = input_shape[2:4] output_width = (input_width", "self.b is None: activation = conved elif self.untie_biases: activation =", "else [] def get_output_shape_for(self, input_shape): batch_size = input_shape[0] input_width, input_height", "= (input_width + 2*self.pad[0] - self.filter_size[0]) // self.strides[0] + 1", "self.create_param(b, (num_filters, output_shape[2], output_shape[3])) else: self.b = self.create_param(b, (num_filters,)) self.corr_mm_op", ".. import init from .. import nonlinearities from . import", "self.get_output_shape() self.b = self.create_param(b, (num_filters, output_shape[2], output_shape[3])) else: self.b =", "== 'full': self.pad = (self.filter_size[0] - 1, self.filter_size[1] -1) elif" ]
[ "handle as before c.begin_tx() c.create_node('ayush') try: c.end_tx() assert False, 'create", "c.end_tx() # 10. list all the people who like egs's", "9. add auxiliary handles to nodes c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r',", "assert False, 'create node passed' except client.WeaverError: pass # 8.", "bad node handle' # 11. get node and check it", "'type' in ad.properties assert 'user' in ad.properties['type'] assert 'age' in", "5. 'like' the post c.begin_tx() e4 = c.create_edge('post', 'ayush') c.set_edge_property(edge=e4,", "import client config_file='' if len(sys.argv) > 1: config_file = sys.argv[1]", "c.set_node_property('type', 'user', 'egs') c.end_tx() # 3. ayush follows egs c.begin_tx()", "followers only c.begin_tx() c.create_node('post') c.set_node_property('type', 'post', 'post') c.set_node_property('visibility', 'followers', 'post')", "try to create edge with same handle as before c.begin_tx()", "the people who like egs's post # this time with", "16:42:52 # # Author: <NAME>, <EMAIL> # # Copyright (C)", "# 5. 'like' the post c.begin_tx() e4 = c.create_edge('post', 'ayush')", "'traversal returned bad node handle' # 7. try to create", "c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx() # 4. add a post and", "assert 'type' in ad.properties assert 'user' in ad.properties['type'] assert 'age'", "all the people who like egs's post # this time", "'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) == 1, 'traversal", "egs c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user', 'egs') c.end_tx() # 3. ayush", "# Copyright (C) 2013, Cornell University, see the LICENSE file", "LICENSE file # for licensing agreement # =============================================================== # import", "/usr/bin/env python # # =============================================================== # Description: Sanity check for", "'followers', 'post') e3 = c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx()", "visibility to followers only c.begin_tx() c.create_node('post') c.set_node_property('type', 'post', 'post') c.set_node_property('visibility',", "assert '25' in ad.properties['age'] assert 'e1' in ad.out_edges print 'Correctly", "node for user ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user', 'age': '25'},", "<filename>tests/python/correctness/simple_test_aux_index.py #! /usr/bin/env python # # =============================================================== # Description: Sanity", "only c.begin_tx() c.create_node('post') c.set_node_property('type', 'post', 'post') c.set_node_property('visibility', 'followers', 'post') e3", "'age' in ad.properties assert '25' in ad.properties['age'] assert 'e1' in", "in ad.aliases assert 'type' in ad.properties assert 'user' in ad.properties['type']", "'ayush', 'e2') c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx() # 4. add a", "c.add_alias('el33th4x0r', 'egs') c.end_tx() # 10. list all the people who", "pass # 9. add auxiliary handles to nodes c.begin_tx() c.add_alias('ad688',", "create edge with same handle as before c.begin_tx() c.create_edge('ayush', 'egs',", "assert 'age' in ad.properties assert '25' in ad.properties['age'] assert 'e1'", "passed' except client.WeaverError: pass # 8. try to create edge", "handle' # 7. try to create node with same handle", "handle' # 11. get node and check it is valid", "key='type', value='follows') c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx() #", "transactions of varying complexity, pass simple_test.' print 'Success, you have", "try: c.end_tx() assert False, 'create node passed' except client.WeaverError: pass", "2002, config_file) # check aux index assert c.aux_index() # 1.", "aux index assert c.aux_index() # 1. create node for user", "like egs's post # this time with aliases instead of", "assert False, 'create edge passed' except client.WeaverError: pass # 9.", "create node with same handle as before c.begin_tx() c.create_node('ayush') try:", "to create edge with same handle as before c.begin_tx() c.create_edge('ayush',", "node for user egs c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user', 'egs') c.end_tx()", "c.begin_tx() c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs', 'ayush', 'e2')", "for licensing agreement # =============================================================== # import sys try: import", "c.create_node('post') c.set_node_property('type', 'post', 'post') c.set_node_property('visibility', 'followers', 'post') e3 = c.create_edge('egs',", "object c = client.Client('172.16.17.32', 2002, config_file) # check aux index", "varying complexity, pass simple_test.' print 'Success, you have a working", "Cornell University, see the LICENSE file # for licensing agreement", "'25' in ad.properties['age'] assert 'e1' in ad.out_edges print 'Correctly executed", "user ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user', 'age': '25'}, 'ayush') c.end_tx()", "= sys.argv[1] # create client object c = client.Client('172.16.17.32', 2002,", "if len(sys.argv) > 1: config_file = sys.argv[1] # create client", "'egs') c.end_tx() # 10. list all the people who like", "'user' in ad.properties['type'] assert 'age' in ad.properties assert '25' in", "'create edge passed' except client.WeaverError: pass # 9. add auxiliary", "= client.Client('172.16.17.32', 2002, config_file) # check aux index assert c.aux_index()", "# 2. create node for user egs c.begin_tx() c.create_node('egs') c.set_node_property('type',", "ad = c.get_node('ayush') assert 'ad688' in ad.aliases assert 'type' in", "aliases instead of handles return_nodes = c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type':", "assert len(return_nodes) == 1, 'traversal returned incorrect #nodes' assert 'ayush'", "return_nodes, 'traversal returned bad node handle' # 7. try to", "see the LICENSE file # for licensing agreement # ===============================================================", "like egs's post return_nodes = c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type':", "2014-08-12 16:42:52 # # Author: <NAME>, <EMAIL> # # Copyright", "licensing agreement # =============================================================== # import sys try: import weaver.client", "'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) == 1, 'traversal returned", "client.Client('172.16.17.32', 2002, config_file) # check aux index assert c.aux_index() #", "the post c.begin_tx() e4 = c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by')", "is valid ad = c.get_node('ayush') assert 'ad688' in ad.aliases assert", "as before c.begin_tx() c.create_edge('ayush', 'egs', 'e1') try: c.end_tx() assert False,", "ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user', 'age': '25'}, 'ayush') c.end_tx() #", "config_file) # check aux index assert c.aux_index() # 1. create", "c.aux_index() # 1. create node for user ayush c.begin_tx() c.create_node('ayush')", "node handle' # 7. try to create node with same", "client config_file='' if len(sys.argv) > 1: config_file = sys.argv[1] #", "c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx()", "in return_nodes, 'traversal returned bad node handle' # 7. try", "who like egs's post return_nodes = c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type':", "# for licensing agreement # =============================================================== # import sys try:", "config_file = sys.argv[1] # create client object c = client.Client('172.16.17.32',", "value='posted') c.end_tx() # 5. 'like' the post c.begin_tx() e4 =", "with same handle as before c.begin_tx() c.create_node('ayush') try: c.end_tx() assert", "False, 'create edge passed' except client.WeaverError: pass # 9. add", "'e1') try: c.end_tx() assert False, 'create edge passed' except client.WeaverError:", "handles return_nodes = c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute()", "import weaver.client as client except ImportError: import client config_file='' if", "1. create node for user ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user',", "import sys try: import weaver.client as client except ImportError: import", "c.begin_tx() c.create_node('ayush') try: c.end_tx() assert False, 'create node passed' except", "to followers only c.begin_tx() c.create_node('post') c.set_node_property('type', 'post', 'post') c.set_node_property('visibility', 'followers',", "complexity, pass simple_test.' print 'Success, you have a working Weaver", "'ayush') c.end_tx() # 2. create node for user egs c.begin_tx()", "= c.get_node('ayush') assert 'ad688' in ad.aliases assert 'type' in ad.properties", "= c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx() # 6. list", "Sanity check for fresh install. # # Created: 2014-08-12 16:42:52", "before c.begin_tx() c.create_edge('ayush', 'egs', 'e1') try: c.end_tx() assert False, 'create", "returned bad node handle' # 11. get node and check", "'egs', 'e1') try: c.end_tx() assert False, 'create edge passed' except", "edge with same handle as before c.begin_tx() c.create_edge('ayush', 'egs', 'e1')", "'ad688' in ad.aliases assert 'type' in ad.properties assert 'user' in", "# Author: <NAME>, <EMAIL> # # Copyright (C) 2013, Cornell", "# 6. list all the people who like egs's post", "egs's post return_nodes = c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type':", "e4 = c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx() # 6.", "c.end_tx() # 5. 'like' the post c.begin_tx() e4 = c.create_edge('post',", "ad.out_edges print 'Correctly executed 11 transactions of varying complexity, pass", "assert 'ayush' in return_nodes, 'traversal returned bad node handle' #", "check for fresh install. # # Created: 2014-08-12 16:42:52 #", "len(sys.argv) > 1: config_file = sys.argv[1] # create client object", "c.end_tx() assert False, 'create node passed' except client.WeaverError: pass #", "# import sys try: import weaver.client as client except ImportError:", "=============================================================== # import sys try: import weaver.client as client except", "'e2') c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx() # 4. add a post", "11. get node and check it is valid ad =", "'ayush' in return_nodes, 'traversal returned bad node handle' # 7.", "# 8. try to create edge with same handle as", "3. ayush follows egs c.begin_tx() c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1', key='type',", "'post') c.set_node_property('visibility', 'followers', 'post') e3 = c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type',", "c.end_tx() # 3. ayush follows egs c.begin_tx() c.create_edge('ayush', 'egs', 'e1')", "c.create_node('ayush') try: c.end_tx() assert False, 'create node passed' except client.WeaverError:", "valid ad = c.get_node('ayush') assert 'ad688' in ad.aliases assert 'type'", "ad.properties['age'] assert 'e1' in ad.out_edges print 'Correctly executed 11 transactions", "ad.properties['type'] assert 'age' in ad.properties assert '25' in ad.properties['age'] assert", "'like' the post c.begin_tx() e4 = c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type',", "in ad.properties['age'] assert 'e1' in ad.out_edges print 'Correctly executed 11", "c.set_node_property('type', 'post', 'post') c.set_node_property('visibility', 'followers', 'post') e3 = c.create_edge('egs', 'post')", "8. try to create edge with same handle as before", "value='follows') c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx() # 4.", "instead of handles return_nodes = c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type':", "c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2', key='type', value='followed_by') c.end_tx() # 4. add", "node passed' except client.WeaverError: pass # 8. try to create", "'ayush' in return_nodes, 'traversal returned bad node handle' # 11.", "c.end_tx() assert False, 'create edge passed' except client.WeaverError: pass #", "and restrict visibility to followers only c.begin_tx() c.create_node('post') c.set_node_property('type', 'post',", "same handle as before c.begin_tx() c.create_edge('ayush', 'egs', 'e1') try: c.end_tx()", "the people who like egs's post return_nodes = c.traverse('egs', {'type':", "nodes c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx() # 10. list", "value='liked_by') c.end_tx() # 6. list all the people who like", "file # for licensing agreement # =============================================================== # import sys", "1, 'traversal returned incorrect #nodes' assert 'ayush' in return_nodes, 'traversal", "# =============================================================== # Description: Sanity check for fresh install. #", "# # Created: 2014-08-12 16:42:52 # # Author: <NAME>, <EMAIL>", "c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx() # 6. list all the people", "# # Author: <NAME>, <EMAIL> # # Copyright (C) 2013,", "c.begin_tx() e4 = c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx() #", "key='type', value='liked_by') c.end_tx() # 6. list all the people who", "edge passed' except client.WeaverError: pass # 9. add auxiliary handles", "with same handle as before c.begin_tx() c.create_edge('ayush', 'egs', 'e1') try:", "add a post and restrict visibility to followers only c.begin_tx()", "== 1, 'traversal returned incorrect #nodes' assert 'ayush' in return_nodes,", "# # =============================================================== # Description: Sanity check for fresh install.", "Description: Sanity check for fresh install. # # Created: 2014-08-12", "Copyright (C) 2013, Cornell University, see the LICENSE file #", "client.WeaverError: pass # 9. add auxiliary handles to nodes c.begin_tx()", "# Created: 2014-08-12 16:42:52 # # Author: <NAME>, <EMAIL> #", "c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx() # 5. 'like' the", "{'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) == 1,", "c.get_node('ayush') assert 'ad688' in ad.aliases assert 'type' in ad.properties assert", "fresh install. # # Created: 2014-08-12 16:42:52 # # Author:", "2013, Cornell University, see the LICENSE file # for licensing", "c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) ==", "c.set_node_property('visibility', 'followers', 'post') e3 = c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type', value='posted')", "# 1. create node for user ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type':", "pass simple_test.' print 'Success, you have a working Weaver setup!'", "of varying complexity, pass simple_test.' print 'Success, you have a", "# check aux index assert c.aux_index() # 1. create node", "index assert c.aux_index() # 1. create node for user ayush", "node handle' # 11. get node and check it is", "# 7. try to create node with same handle as", "c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user', 'age': '25'}, 'ayush') c.end_tx() # 2.", "except client.WeaverError: pass # 8. try to create edge with", "print 'Correctly executed 11 transactions of varying complexity, pass simple_test.'", "'age': '25'}, 'ayush') c.end_tx() # 2. create node for user", "'e1' in ad.out_edges print 'Correctly executed 11 transactions of varying", "list all the people who like egs's post # this", "and check it is valid ad = c.get_node('ayush') assert 'ad688'", "key='type', value='posted') c.end_tx() # 5. 'like' the post c.begin_tx() e4", "passed' except client.WeaverError: pass # 9. add auxiliary handles to", "ad.properties assert '25' in ad.properties['age'] assert 'e1' in ad.out_edges print", "create node for user ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user', 'age':", "c.end_tx() # 6. list all the people who like egs's", "assert 'e1' in ad.out_edges print 'Correctly executed 11 transactions of", "all the people who like egs's post return_nodes = c.traverse('egs',", "'egs', 'e1') c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2', key='type',", "incorrect #nodes' assert 'ayush' in return_nodes, 'traversal returned bad node", "c.end_tx() # 2. create node for user egs c.begin_tx() c.create_node('egs')", "6. list all the people who like egs's post return_nodes", "<EMAIL> # # Copyright (C) 2013, Cornell University, see the", "4. add a post and restrict visibility to followers only", "in ad.properties['type'] assert 'age' in ad.properties assert '25' in ad.properties['age']", "'traversal returned bad node handle' # 11. get node and", "add auxiliary handles to nodes c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs')", "config_file='' if len(sys.argv) > 1: config_file = sys.argv[1] # create", "get node and check it is valid ad = c.get_node('ayush')", "post and restrict visibility to followers only c.begin_tx() c.create_node('post') c.set_node_property('type',", "assert 'ad688' in ad.aliases assert 'type' in ad.properties assert 'user'", "ad.aliases assert 'type' in ad.properties assert 'user' in ad.properties['type'] assert", "who like egs's post # this time with aliases instead", "egs's post # this time with aliases instead of handles", "people who like egs's post # this time with aliases", "client object c = client.Client('172.16.17.32', 2002, config_file) # check aux", "in ad.properties assert 'user' in ad.properties['type'] assert 'age' in ad.properties", "1: config_file = sys.argv[1] # create client object c =", "same handle as before c.begin_tx() c.create_node('ayush') try: c.end_tx() assert False,", "'post') c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx() # 5. 'like' the post", "'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) == 1, 'traversal returned incorrect #nodes'", "# # Copyright (C) 2013, Cornell University, see the LICENSE", "this time with aliases instead of handles return_nodes = c.traverse('el33th4x0r',", "in ad.out_edges print 'Correctly executed 11 transactions of varying complexity,", "c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2',", "c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) ==", "try: import weaver.client as client except ImportError: import client config_file=''", "returned incorrect #nodes' assert 'ayush' in return_nodes, 'traversal returned bad", "assert 'user' in ad.properties['type'] assert 'age' in ad.properties assert '25'", "# 3. ayush follows egs c.begin_tx() c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1',", "bad node handle' # 7. try to create node with", "Author: <NAME>, <EMAIL> # # Copyright (C) 2013, Cornell University,", "'Correctly executed 11 transactions of varying complexity, pass simple_test.' print", "c.begin_tx() c.create_node('post') c.set_node_property('type', 'post', 'post') c.set_node_property('visibility', 'followers', 'post') e3 =", "a post and restrict visibility to followers only c.begin_tx() c.create_node('post')", "'user', 'age': '25'}, 'ayush') c.end_tx() # 2. create node for", "#nodes' assert 'ayush' in return_nodes, 'traversal returned bad node handle'", "try to create node with same handle as before c.begin_tx()", "'egs') c.end_tx() # 3. ayush follows egs c.begin_tx() c.create_edge('ayush', 'egs',", "as before c.begin_tx() c.create_node('ayush') try: c.end_tx() assert False, 'create node", "ayush follows egs c.begin_tx() c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1', key='type', value='follows')", "create client object c = client.Client('172.16.17.32', 2002, config_file) # check", "to create node with same handle as before c.begin_tx() c.create_node('ayush')", "# 11. get node and check it is valid ad", "agreement # =============================================================== # import sys try: import weaver.client as", "# =============================================================== # import sys try: import weaver.client as client", "'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes) == 1, 'traversal returned incorrect", "except ImportError: import client config_file='' if len(sys.argv) > 1: config_file", "c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx() # 10. list all the", "client.WeaverError: pass # 8. try to create edge with same", "'traversal returned incorrect #nodes' assert 'ayush' in return_nodes, 'traversal returned", "it is valid ad = c.get_node('ayush') assert 'ad688' in ad.aliases", "value='followed_by') c.end_tx() # 4. add a post and restrict visibility", "the LICENSE file # for licensing agreement # =============================================================== #", "# 9. add auxiliary handles to nodes c.begin_tx() c.add_alias('ad688', 'ayush')", "<NAME>, <EMAIL> # # Copyright (C) 2013, Cornell University, see", "sys try: import weaver.client as client except ImportError: import client", "time with aliases instead of handles return_nodes = c.traverse('el33th4x0r', {'type':", "python # # =============================================================== # Description: Sanity check for fresh", "len(return_nodes) == 1, 'traversal returned incorrect #nodes' assert 'ayush' in", "=============================================================== # Description: Sanity check for fresh install. # #", "of handles return_nodes = c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type':", "for user egs c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user', 'egs') c.end_tx() #", "= c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes)", "c.create_node('egs') c.set_node_property('type', 'user', 'egs') c.end_tx() # 3. ayush follows egs", "return_nodes = c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert", "# 10. list all the people who like egs's post", "create node for user egs c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user', 'egs')", "check it is valid ad = c.get_node('ayush') assert 'ad688' in", "# this time with aliases instead of handles return_nodes =", "to nodes c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx() # 10.", "c.set_node_properties({'type': 'user', 'age': '25'}, 'ayush') c.end_tx() # 2. create node", "in return_nodes, 'traversal returned bad node handle' # 11. get", "return_nodes, 'traversal returned bad node handle' # 11. get node", "c.end_tx() # 4. add a post and restrict visibility to", "handle as before c.begin_tx() c.create_edge('ayush', 'egs', 'e1') try: c.end_tx() assert", "assert c.aux_index() # 1. create node for user ayush c.begin_tx()", "'post') e3 = c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx() #", "try: c.end_tx() assert False, 'create edge passed' except client.WeaverError: pass", "c.begin_tx() c.create_edge('ayush', 'egs', 'e1') try: c.end_tx() assert False, 'create edge", "key='type', value='followed_by') c.end_tx() # 4. add a post and restrict", "node with same handle as before c.begin_tx() c.create_node('ayush') try: c.end_tx()", "returned bad node handle' # 7. try to create node", "for user ayush c.begin_tx() c.create_node('ayush') c.set_node_properties({'type': 'user', 'age': '25'}, 'ayush')", "> 1: config_file = sys.argv[1] # create client object c", "user egs c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user', 'egs') c.end_tx() # 3.", "University, see the LICENSE file # for licensing agreement #", "11 transactions of varying complexity, pass simple_test.' print 'Success, you", "executed 11 transactions of varying complexity, pass simple_test.' print 'Success,", "c = client.Client('172.16.17.32', 2002, config_file) # check aux index assert", "ImportError: import client config_file='' if len(sys.argv) > 1: config_file =", "for fresh install. # # Created: 2014-08-12 16:42:52 # #", "# 4. add a post and restrict visibility to followers", "'user', 'egs') c.end_tx() # 3. ayush follows egs c.begin_tx() c.create_edge('ayush',", "with aliases instead of handles return_nodes = c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type':", "post return_nodes = c.traverse('egs', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute()", "list all the people who like egs's post return_nodes =", "pass # 8. try to create edge with same handle", "c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx() # 10. list all", "return_nodes = c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert", "'user'}).execute() assert len(return_nodes) == 1, 'traversal returned incorrect #nodes' assert", "2. create node for user egs c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user',", "except client.WeaverError: pass # 9. add auxiliary handles to nodes", "10. list all the people who like egs's post #", "'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx() # 6. list all the", "#! /usr/bin/env python # # =============================================================== # Description: Sanity check", "ad.properties assert 'user' in ad.properties['type'] assert 'age' in ad.properties assert", "c.create_node('ayush') c.set_node_properties({'type': 'user', 'age': '25'}, 'ayush') c.end_tx() # 2. create", "weaver.client as client except ImportError: import client config_file='' if len(sys.argv)", "post c.begin_tx() e4 = c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx()", "post # this time with aliases instead of handles return_nodes", "e3 = c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx() # 5.", "check aux index assert c.aux_index() # 1. create node for", "c.create_edge('post', 'ayush') c.set_edge_property(edge=e4, key='type', value='liked_by') c.end_tx() # 6. list all", "7. try to create node with same handle as before", "as client except ImportError: import client config_file='' if len(sys.argv) >", "'create node passed' except client.WeaverError: pass # 8. try to", "people who like egs's post return_nodes = c.traverse('egs', {'type': 'user'}).out_edge({'type':", "= c.create_edge('egs', 'post') c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx() # 5. 'like'", "'post', 'post') c.set_node_property('visibility', 'followers', 'post') e3 = c.create_edge('egs', 'post') c.set_edge_property(edge=e3,", "c.begin_tx() c.create_node('egs') c.set_node_property('type', 'user', 'egs') c.end_tx() # 3. ayush follows", "node and check it is valid ad = c.get_node('ayush') assert", "# create client object c = client.Client('172.16.17.32', 2002, config_file) #", "follows egs c.begin_tx() c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs',", "# Description: Sanity check for fresh install. # # Created:", "= c.traverse('el33th4x0r', {'type': 'user'}).out_edge({'type': 'posted'}).node({'type': 'post'}).out_edge({'type': 'liked_by'}).node({'type': 'user'}).execute() assert len(return_nodes)", "False, 'create node passed' except client.WeaverError: pass # 8. try", "before c.begin_tx() c.create_node('ayush') try: c.end_tx() assert False, 'create node passed'", "in ad.properties assert '25' in ad.properties['age'] assert 'e1' in ad.out_edges", "'25'}, 'ayush') c.end_tx() # 2. create node for user egs", "client except ImportError: import client config_file='' if len(sys.argv) > 1:", "'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx() # 10. list all the people", "install. # # Created: 2014-08-12 16:42:52 # # Author: <NAME>,", "Created: 2014-08-12 16:42:52 # # Author: <NAME>, <EMAIL> # #", "(C) 2013, Cornell University, see the LICENSE file # for", "egs c.begin_tx() c.create_edge('ayush', 'egs', 'e1') c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs', 'ayush',", "c.create_edge('ayush', 'egs', 'e1') try: c.end_tx() assert False, 'create edge passed'", "sys.argv[1] # create client object c = client.Client('172.16.17.32', 2002, config_file)", "restrict visibility to followers only c.begin_tx() c.create_node('post') c.set_node_property('type', 'post', 'post')", "handles to nodes c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx() #", "auxiliary handles to nodes c.begin_tx() c.add_alias('ad688', 'ayush') c.add_alias('el33th4x0r', 'egs') c.end_tx()", "c.set_edge_property(edge=e3, key='type', value='posted') c.end_tx() # 5. 'like' the post c.begin_tx()", "'e1') c.set_edge_property(edge='e1', key='type', value='follows') c.create_edge('egs', 'ayush', 'e2') c.set_edge_property(edge='e2', key='type', value='followed_by')" ]
[ "graphs are isomorphic iso1 = compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2) if", "u\"The 2 '%s' Graphs\" % graph1.identifier else: str_bit = (u\"Graphs", "COL: record.levelname = COLOR_SEQ % ( 30 + COL[record.levelname]) +", "== type(graph2) == rdflib.Graph: if type(graph1) == rdflib.ConjunctiveGraph: g1contexts =", "def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def format(self, record): if record.levelname in", "YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) COL = {", "else: str_bit = (u\"Graphs '%s' and '%s'\" % (graph1.identifier, graph2.identifier))", "'%s' and '%s'\" % (graph1.identifier, graph2.identifier)) if iso1 == iso2:", "logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO)", "formatter = ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\") handler =", "record.levelname in COL: record.levelname = COLOR_SEQ % ( 30 +", "4: logging.ERROR, 5: None} try: log_level = mapper[verbosity_level] except KeyError:", "formatter)) except ImportError: logger.info(\"Install pygments for colored diffs\") print(u'\\n'.join(diff)) except", "= \"\\033[1m\" # The background is set with 40 plus", "unicode_literals try: unicode except NameError: basestring = unicode = str", "= compare.to_isomorphic(graph2) if graph1.identifier == graph2.identifier: str_bit = u\"The 2", "rdflib from rdflib import compare logger = logging.getLogger(\"ldtools\") RESET_SEQ =", "try: from pygments import highlight from pygments.formatters import terminal from", "graph1 and highlights everything that changed. Colored if pygments available\"\"\"", "MAGENTA, 'WARNING': YELLOW, 'CRITICAL': YELLOW, 'ERROR': RED} def set_colored_logger(verbosity_level): class", "unicode = str # Python 3 import logging import rdflib", "= \"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\" # The", "compare logger = logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\"", "1 graph2 = g2contexts[0] # Return if both graphs are", "str_bit) in_both, in_first, in_second = compare.graph_diff(iso1, iso2) def dump_nt_sorted(g): return", "for colored diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only in first\", unicode(sorted_first))", "the number of the color, and # the foreground with", "'WARNING': YELLOW, 'CRITICAL': YELLOW, 'ERROR': RED} def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter):", "in_first, in_second = compare.graph_diff(iso1, iso2) def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first", "print_function, unicode_literals try: unicode except NameError: basestring = unicode =", "sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second) import difflib diff", "import compare logger = logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\" COLOR_SEQ =", "and highlights everything that changed. Colored if pygments available\"\"\" #", "= g1contexts[0] if type(graph2) == rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts()) assert", "% (30 + GREEN) + record.msg + RESET_SEQ return logging.Formatter.format(self,", "list(graph1.contexts()) assert len(g1contexts) == 1 graph1 = g1contexts[0] if type(graph2)", "5: None} try: log_level = mapper[verbosity_level] except KeyError: log_level =", "3: logging.WARNING, 4: logging.ERROR, 5: None} try: log_level = mapper[verbosity_level]", "# the foreground with 30 # These are the sequences", "ouput BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE =", "1 graph1 = g1contexts[0] if type(graph2) == rdflib.ConjunctiveGraph: g2contexts =", "and # the foreground with 30 # These are the", "= compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2) if graph1.identifier == graph2.identifier: str_bit", "logger def my_graph_diff(graph1, graph2): \"\"\"Compares graph2 to graph1 and highlights", "isomorphic\" % str_bit) return print(u\"Differences between %s.\" % str_bit) in_both,", "# quick fix for wrong type if not type(graph1) ==", "in_both, in_first, in_second = compare.graph_diff(iso1, iso2) def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines())", "the color, and # the foreground with 30 # These", "compare.to_isomorphic(graph2) if graph1.identifier == graph2.identifier: str_bit = u\"The 2 '%s'", "try: log_level = mapper[verbosity_level] except KeyError: log_level = mapper[2] if", "everything that changed. Colored if pygments available\"\"\" # quick fix", "diff = difflib.unified_diff( sorted_first, sorted_second, u'Original', u'Current', lineterm='' ) try:", "( 30 + COL[record.levelname]) + record.levelname + RESET_SEQ record.msg =", "= list(graph1.contexts()) assert len(g1contexts) == 1 graph1 = g1contexts[0] if", "logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper = {1: logging.DEBUG, 2: logging.INFO,", "colored ouput BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE", "= difflib.unified_diff( sorted_first, sorted_second, u'Original', u'Current', lineterm='' ) try: from", "import difflib diff = difflib.unified_diff( sorted_first, sorted_second, u'Original', u'Current', lineterm=''", "return print(u\"Differences between %s.\" % str_bit) in_both, in_first, in_second =", "NameError: basestring = unicode = str # Python 3 import", "wrong type if not type(graph1) == type(graph2) == rdflib.Graph: if", "{1: logging.DEBUG, 2: logging.INFO, 3: logging.WARNING, 4: logging.ERROR, 5: None}", "logging.INFO, 3: logging.WARNING, 4: logging.ERROR, 5: None} try: log_level =", "= compare.graph_diff(iso1, iso2) def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first)", "g1contexts = list(graph1.contexts()) assert len(g1contexts) == 1 graph1 = g1contexts[0]", "try: unicode except NameError: basestring = unicode = str #", "= COLOR_SEQ % ( 30 + COL[record.levelname]) + record.levelname +", "COLOR_SEQ % (30 + GREEN) + record.msg + RESET_SEQ return", "BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)", "%(levelname)s: %(message)s\") handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler)", "'%s'\" % (graph1.identifier, graph2.identifier)) if iso1 == iso2: logger.debug(u\"%s are", "Colored if pygments available\"\"\" # quick fix for wrong type", "in_second = compare.graph_diff(iso1, iso2) def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first =", "the foreground with 30 # These are the sequences need", "record.msg + RESET_SEQ return logging.Formatter.format(self, record) formatter = ColoredFormatter(\"%(asctime)s %(name)s", "range(8) COL = { 'DEBUG': BLUE, 'INFO': MAGENTA, 'WARNING': YELLOW,", "terminal from pygments.lexers import web lexer = web.XmlLexer() formatter =", "== 1 graph2 = g2contexts[0] # Return if both graphs", "record.msg = COLOR_SEQ % (30 + GREEN) + record.msg +", "% str_bit) return print(u\"Differences between %s.\" % str_bit) in_both, in_first,", "import rdflib from rdflib import compare logger = logging.getLogger(\"ldtools\") RESET_SEQ", "% (graph1.identifier, graph2.identifier)) if iso1 == iso2: logger.debug(u\"%s are isomorphic\"", "logging.Formatter.format(self, record) formatter = ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\")", "+ COL[record.levelname]) + record.levelname + RESET_SEQ record.msg = unicode(record.msg) record.msg", "u'Original', u'Current', lineterm='' ) try: from pygments import highlight from", "from __future__ import print_function, unicode_literals try: unicode except NameError: basestring", "assert len(g1contexts) == 1 graph1 = g1contexts[0] if type(graph2) ==", "graph2 = g2contexts[0] # Return if both graphs are isomorphic", "30 + COL[record.levelname]) + record.levelname + RESET_SEQ record.msg = unicode(record.msg)", "record): if record.levelname in COL: record.levelname = COLOR_SEQ % (", "sequences need to get colored ouput BLACK, RED, GREEN, YELLOW,", "mapper[2] if log_level: logger.setLevel(log_level) return logger def my_graph_diff(graph1, graph2): \"\"\"Compares", "def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second)", "graph2 to graph1 and highlights everything that changed. Colored if", "formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter)) except ImportError: logger.info(\"Install pygments", "handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper", "-*- coding: utf-8 -*- from __future__ import print_function, unicode_literals try:", "iso2: logger.debug(u\"%s are isomorphic\" % str_bit) return print(u\"Differences between %s.\"", "for wrong type if not type(graph1) == type(graph2) == rdflib.Graph:", "record.levelname + RESET_SEQ record.msg = unicode(record.msg) record.msg = COLOR_SEQ %", "import print_function, unicode_literals try: unicode except NameError: basestring = unicode", "== graph2.identifier: str_bit = u\"The 2 '%s' Graphs\" % graph1.identifier", "print(highlight(u'\\n'.join(diff), lexer, formatter)) except ImportError: logger.info(\"Install pygments for colored diffs\")", "if pygments available\"\"\" # quick fix for wrong type if", "iso1 == iso2: logger.debug(u\"%s are isomorphic\" % str_bit) return print(u\"Differences", "dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second) import difflib diff = difflib.unified_diff( sorted_first,", "== iso2: logger.debug(u\"%s are isomorphic\" % str_bit) return print(u\"Differences between", "= \"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\" # The background is set", "= range(8) COL = { 'DEBUG': BLUE, 'INFO': MAGENTA, 'WARNING':", "graph1.identifier == graph2.identifier: str_bit = u\"The 2 '%s' Graphs\" %", "record) formatter = ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\") handler", "to get colored ouput BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA,", "and '%s'\" % (graph1.identifier, graph2.identifier)) if iso1 == iso2: logger.debug(u\"%s", "= list(graph2.contexts()) assert len(g2contexts) == 1 graph2 = g2contexts[0] #", "iso2 = compare.to_isomorphic(graph2) if graph1.identifier == graph2.identifier: str_bit = u\"The", "changed. Colored if pygments available\"\"\" # quick fix for wrong", "if type(graph1) == rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts()) assert len(g1contexts) ==", "{ 'DEBUG': BLUE, 'INFO': MAGENTA, 'WARNING': YELLOW, 'CRITICAL': YELLOW, 'ERROR':", "GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) COL =", "len(g1contexts) == 1 graph1 = g1contexts[0] if type(graph2) == rdflib.ConjunctiveGraph:", "\"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\" # The background is set with", "BLUE, 'INFO': MAGENTA, 'WARNING': YELLOW, 'CRITICAL': YELLOW, 'ERROR': RED} def", "%s.\" % str_bit) in_both, in_first, in_second = compare.graph_diff(iso1, iso2) def", "sorted_second = dump_nt_sorted(in_second) import difflib diff = difflib.unified_diff( sorted_first, sorted_second,", "\" %(levelname)s: %(message)s\") handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger()", "pygments import highlight from pygments.formatters import terminal from pygments.lexers import", "COL = { 'DEBUG': BLUE, 'INFO': MAGENTA, 'WARNING': YELLOW, 'CRITICAL':", "30 # These are the sequences need to get colored", "+ record.levelname + RESET_SEQ record.msg = unicode(record.msg) record.msg = COLOR_SEQ", "difflib.unified_diff( sorted_first, sorted_second, u'Original', u'Current', lineterm='' ) try: from pygments", "highlights everything that changed. Colored if pygments available\"\"\" # quick", "logger.info(\"Install pygments for colored diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only in", "mapper = {1: logging.DEBUG, 2: logging.INFO, 3: logging.WARNING, 4: logging.ERROR,", "g1contexts[0] if type(graph2) == rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts()) assert len(g2contexts)", "pygments.formatters import terminal from pygments.lexers import web lexer = web.XmlLexer()", "<reponame>dmr/Ldtools<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import print_function,", "= mapper[2] if log_level: logger.setLevel(log_level) return logger def my_graph_diff(graph1, graph2):", "# These are the sequences need to get colored ouput", "\"\"\"Compares graph2 to graph1 and highlights everything that changed. Colored", "sorted_second, u'Original', u'Current', lineterm='' ) try: from pygments import highlight", "dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second) import", "__future__ import print_function, unicode_literals try: unicode except NameError: basestring =", "= g2contexts[0] # Return if both graphs are isomorphic iso1", "%(message)s\") handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger2", "are isomorphic\" % str_bit) return print(u\"Differences between %s.\" % str_bit)", "3 import logging import rdflib from rdflib import compare logger", "in COL: record.levelname = COLOR_SEQ % ( 30 + COL[record.levelname])", "str_bit) return print(u\"Differences between %s.\" % str_bit) in_both, in_first, in_second", "my_graph_diff(graph1, graph2): \"\"\"Compares graph2 to graph1 and highlights everything that", "== 1 graph1 = g1contexts[0] if type(graph2) == rdflib.ConjunctiveGraph: g2contexts", "graph2.identifier)) if iso1 == iso2: logger.debug(u\"%s are isomorphic\" % str_bit)", "YELLOW, 'ERROR': RED} def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def format(self, record):", "CYAN, WHITE = range(8) COL = { 'DEBUG': BLUE, 'INFO':", "'ERROR': RED} def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def format(self, record): if", "WHITE = range(8) COL = { 'DEBUG': BLUE, 'INFO': MAGENTA,", "= logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\")", "if record.levelname in COL: record.levelname = COLOR_SEQ % ( 30", "str_bit = u\"The 2 '%s' Graphs\" % graph1.identifier else: str_bit", "import terminal from pygments.lexers import web lexer = web.XmlLexer() formatter", "number of the color, and # the foreground with 30", "iso1 = compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2) if graph1.identifier == graph2.identifier:", "graph2): \"\"\"Compares graph2 to graph1 and highlights everything that changed.", "u'Current', lineterm='' ) try: from pygments import highlight from pygments.formatters", "= logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ =", "foreground with 30 # These are the sequences need to", "from pygments.lexers import web lexer = web.XmlLexer() formatter = terminal.TerminalFormatter()", "'CRITICAL': YELLOW, 'ERROR': RED} def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def format(self,", "40 plus the number of the color, and # the", "record.msg = unicode(record.msg) record.msg = COLOR_SEQ % (30 + GREEN)", "import logging import rdflib from rdflib import compare logger =", "(30 + GREEN) + record.msg + RESET_SEQ return logging.Formatter.format(self, record)", "== rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts()) assert len(g2contexts) == 1 graph2", "Python 3 import logging import rdflib from rdflib import compare", "%(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\") handler = logging.StreamHandler() handler.setFormatter(formatter) logger", "MAGENTA, CYAN, WHITE = range(8) COL = { 'DEBUG': BLUE,", "format(self, record): if record.levelname in COL: record.levelname = COLOR_SEQ %", "between %s.\" % str_bit) in_both, in_first, in_second = compare.graph_diff(iso1, iso2)", "if not type(graph1) == type(graph2) == rdflib.Graph: if type(graph1) ==", "compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2) if graph1.identifier == graph2.identifier: str_bit =", "str_bit = (u\"Graphs '%s' and '%s'\" % (graph1.identifier, graph2.identifier)) if", "logging import rdflib from rdflib import compare logger = logging.getLogger(\"ldtools\")", "+ GREEN) + record.msg + RESET_SEQ return logging.Formatter.format(self, record) formatter", "logger = logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ", "GREEN) + record.msg + RESET_SEQ return logging.Formatter.format(self, record) formatter =", "highlight from pygments.formatters import terminal from pygments.lexers import web lexer", "if both graphs are isomorphic iso1 = compare.to_isomorphic(graph1) iso2 =", "= logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper = {1: logging.DEBUG, 2: logging.INFO, 3:", "% ( 30 + COL[record.levelname]) + record.levelname + RESET_SEQ record.msg", "are the sequences need to get colored ouput BLACK, RED,", "def format(self, record): if record.levelname in COL: record.levelname = COLOR_SEQ", "RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) COL", "plus the number of the color, and # the foreground", "to graph1 and highlights everything that changed. Colored if pygments", "set with 40 plus the number of the color, and", "KeyError: log_level = mapper[2] if log_level: logger.setLevel(log_level) return logger def", "from pygments import highlight from pygments.formatters import terminal from pygments.lexers", "= logging.getLogger() logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper = {1:", "isomorphic iso1 = compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2) if graph1.identifier ==", "= {1: logging.DEBUG, 2: logging.INFO, 3: logging.WARNING, 4: logging.ERROR, 5:", "assert len(g2contexts) == 1 graph2 = g2contexts[0] # Return if", "import highlight from pygments.formatters import terminal from pygments.lexers import web", "except ImportError: logger.info(\"Install pygments for colored diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError:", "str # Python 3 import logging import rdflib from rdflib", "None} try: log_level = mapper[verbosity_level] except KeyError: log_level = mapper[2]", "if log_level: logger.setLevel(log_level) return logger def my_graph_diff(graph1, graph2): \"\"\"Compares graph2", "from rdflib import compare logger = logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\"", "coding: utf-8 -*- from __future__ import print_function, unicode_literals try: unicode", "if iso1 == iso2: logger.debug(u\"%s are isomorphic\" % str_bit) return", "logging.DEBUG, 2: logging.INFO, 3: logging.WARNING, 4: logging.ERROR, 5: None} try:", "pygments.lexers import web lexer = web.XmlLexer() formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff),", "background is set with 40 plus the number of the", "def my_graph_diff(graph1, graph2): \"\"\"Compares graph2 to graph1 and highlights everything", "graph1.identifier else: str_bit = (u\"Graphs '%s' and '%s'\" % (graph1.identifier,", "RESET_SEQ = \"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\" #", "logger = logging.getLogger() logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper =", "logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper = {1: logging.DEBUG, 2: logging.INFO, 3: logging.WARNING,", "log_level = mapper[verbosity_level] except KeyError: log_level = mapper[2] if log_level:", "logger.setLevel(log_level) return logger def my_graph_diff(graph1, graph2): \"\"\"Compares graph2 to graph1", "= unicode(record.msg) record.msg = COLOR_SEQ % (30 + GREEN) +", "basestring = unicode = str # Python 3 import logging", "The background is set with 40 plus the number of", "unicode(record.msg) record.msg = COLOR_SEQ % (30 + GREEN) + record.msg", "logging.WARNING, 4: logging.ERROR, 5: None} try: log_level = mapper[verbosity_level] except", "that changed. Colored if pygments available\"\"\" # quick fix for", "rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts()) assert len(g1contexts) == 1 graph1 =", "+ RESET_SEQ return logging.Formatter.format(self, record) formatter = ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\"", "RED} def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def format(self, record): if record.levelname", "= { 'DEBUG': BLUE, 'INFO': MAGENTA, 'WARNING': YELLOW, 'CRITICAL': YELLOW,", "record.levelname = COLOR_SEQ % ( 30 + COL[record.levelname]) + record.levelname", "from pygments.formatters import terminal from pygments.lexers import web lexer =", "pygments for colored diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only in first\",", "return logger def my_graph_diff(graph1, graph2): \"\"\"Compares graph2 to graph1 and", "\"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\" # The background", "ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\") handler = logging.StreamHandler() handler.setFormatter(formatter)", "'%s' Graphs\" % graph1.identifier else: str_bit = (u\"Graphs '%s' and", "RESET_SEQ return logging.Formatter.format(self, record) formatter = ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \"", "the sequences need to get colored ouput BLACK, RED, GREEN,", "difflib diff = difflib.unified_diff( sorted_first, sorted_second, u'Original', u'Current', lineterm='' )", "COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\" # The background is", "except UnicodeDecodeError: print(u\"Only in first\", unicode(sorted_first)) print(u\"Only in second\", unicode(sorted_second))", "RESET_SEQ record.msg = unicode(record.msg) record.msg = COLOR_SEQ % (30 +", "(u\"Graphs '%s' and '%s'\" % (graph1.identifier, graph2.identifier)) if iso1 ==", "with 40 plus the number of the color, and #", ") try: from pygments import highlight from pygments.formatters import terminal", "color, and # the foreground with 30 # These are", "lineterm='' ) try: from pygments import highlight from pygments.formatters import", "type(graph2) == rdflib.Graph: if type(graph1) == rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts())", "with 30 # These are the sequences need to get", "YELLOW, 'CRITICAL': YELLOW, 'ERROR': RED} def set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def", "unicode except NameError: basestring = unicode = str # Python", "COLOR_SEQ % ( 30 + COL[record.levelname]) + record.levelname + RESET_SEQ", "BLUE, MAGENTA, CYAN, WHITE = range(8) COL = { 'DEBUG':", "colored diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only in first\", unicode(sorted_first)) print(u\"Only", "logging.ERROR, 5: None} try: log_level = mapper[verbosity_level] except KeyError: log_level", "Return if both graphs are isomorphic iso1 = compare.to_isomorphic(graph1) iso2", "+ RESET_SEQ record.msg = unicode(record.msg) record.msg = COLOR_SEQ % (30", "# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals", "g2contexts = list(graph2.contexts()) assert len(g2contexts) == 1 graph2 = g2contexts[0]", "diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only in first\", unicode(sorted_first)) print(u\"Only in", "compare.graph_diff(iso1, iso2) def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first) sorted_second", "% graph1.identifier else: str_bit = (u\"Graphs '%s' and '%s'\" %", "# Return if both graphs are isomorphic iso1 = compare.to_isomorphic(graph1)", "ColoredFormatter(logging.Formatter): def format(self, record): if record.levelname in COL: record.levelname =", "both graphs are isomorphic iso1 = compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2)", "print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only in first\", unicode(sorted_first)) print(u\"Only in second\",", "COL[record.levelname]) + record.levelname + RESET_SEQ record.msg = unicode(record.msg) record.msg =", "2: logging.INFO, 3: logging.WARNING, 4: logging.ERROR, 5: None} try: log_level", "== rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts()) assert len(g1contexts) == 1 graph1", "is set with 40 plus the number of the color,", "print(u\"Differences between %s.\" % str_bit) in_both, in_first, in_second = compare.graph_diff(iso1,", "get colored ouput BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN,", "\"\\033[1m\" # The background is set with 40 plus the", "dump_nt_sorted(in_second) import difflib diff = difflib.unified_diff( sorted_first, sorted_second, u'Original', u'Current',", "lexer, formatter)) except ImportError: logger.info(\"Install pygments for colored diffs\") print(u'\\n'.join(diff))", "import web lexer = web.XmlLexer() formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer,", "= str # Python 3 import logging import rdflib from", "= mapper[verbosity_level] except KeyError: log_level = mapper[2] if log_level: logger.setLevel(log_level)", "= COLOR_SEQ % (30 + GREEN) + record.msg + RESET_SEQ", "return logging.Formatter.format(self, record) formatter = ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s:", "Graphs\" % graph1.identifier else: str_bit = (u\"Graphs '%s' and '%s'\"", "except KeyError: log_level = mapper[2] if log_level: logger.setLevel(log_level) return logger", "need to get colored ouput BLACK, RED, GREEN, YELLOW, BLUE,", "mapper[verbosity_level] except KeyError: log_level = mapper[2] if log_level: logger.setLevel(log_level) return", "type(graph1) == rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts()) assert len(g1contexts) == 1", "logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\" COLOR_SEQ = \"\\033[1;%dm\" BOLD_SEQ = \"\\033[1m\"", "= u\"The 2 '%s' Graphs\" % graph1.identifier else: str_bit =", "if graph1.identifier == graph2.identifier: str_bit = u\"The 2 '%s' Graphs\"", "sorted_first, sorted_second, u'Original', u'Current', lineterm='' ) try: from pygments import", "quick fix for wrong type if not type(graph1) == type(graph2)", "lexer = web.XmlLexer() formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter)) except", "logging.getLogger() logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper = {1: logging.DEBUG,", "not type(graph1) == type(graph2) == rdflib.Graph: if type(graph1) == rdflib.ConjunctiveGraph:", "= (u\"Graphs '%s' and '%s'\" % (graph1.identifier, graph2.identifier)) if iso1", "These are the sequences need to get colored ouput BLACK,", "2 '%s' Graphs\" % graph1.identifier else: str_bit = (u\"Graphs '%s'", "terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter)) except ImportError: logger.info(\"Install pygments for colored", "'DEBUG': BLUE, 'INFO': MAGENTA, 'WARNING': YELLOW, 'CRITICAL': YELLOW, 'ERROR': RED}", "fix for wrong type if not type(graph1) == type(graph2) ==", "# Python 3 import logging import rdflib from rdflib import", "return sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second) import difflib", "BOLD_SEQ = \"\\033[1m\" # The background is set with 40", "handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger2 =", "-*- from __future__ import print_function, unicode_literals try: unicode except NameError:", "= terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter)) except ImportError: logger.info(\"Install pygments for", "# The background is set with 40 plus the number", "except NameError: basestring = unicode = str # Python 3", "ImportError: logger.info(\"Install pygments for colored diffs\") print(u'\\n'.join(diff)) except UnicodeDecodeError: print(u\"Only", "+ record.msg + RESET_SEQ return logging.Formatter.format(self, record) formatter = ColoredFormatter(\"%(asctime)s", "utf-8 -*- from __future__ import print_function, unicode_literals try: unicode except", "type(graph2) == rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts()) assert len(g2contexts) == 1", "type if not type(graph1) == type(graph2) == rdflib.Graph: if type(graph1)", "type(graph1) == type(graph2) == rdflib.Graph: if type(graph1) == rdflib.ConjunctiveGraph: g1contexts", "rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts()) assert len(g2contexts) == 1 graph2 =", "web.XmlLexer() formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter)) except ImportError: logger.info(\"Install", "of the color, and # the foreground with 30 #", "class ColoredFormatter(logging.Formatter): def format(self, record): if record.levelname in COL: record.levelname", "set_colored_logger(verbosity_level): class ColoredFormatter(logging.Formatter): def format(self, record): if record.levelname in COL:", "if type(graph2) == rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts()) assert len(g2contexts) ==", "% str_bit) in_both, in_first, in_second = compare.graph_diff(iso1, iso2) def dump_nt_sorted(g):", "are isomorphic iso1 = compare.to_isomorphic(graph1) iso2 = compare.to_isomorphic(graph2) if graph1.identifier", "= dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second) import difflib diff = difflib.unified_diff(", "graph1 = g1contexts[0] if type(graph2) == rdflib.ConjunctiveGraph: g2contexts = list(graph2.contexts())", "web lexer = web.XmlLexer() formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter))", "g2contexts[0] # Return if both graphs are isomorphic iso1 =", "log_level = mapper[2] if log_level: logger.setLevel(log_level) return logger def my_graph_diff(graph1,", "sorted_first = dump_nt_sorted(in_first) sorted_second = dump_nt_sorted(in_second) import difflib diff =", "= ColoredFormatter(\"%(asctime)s %(name)s %(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\") handler = logging.StreamHandler()", "== rdflib.Graph: if type(graph1) == rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts()) assert", "rdflib.Graph: if type(graph1) == rdflib.ConjunctiveGraph: g1contexts = list(graph1.contexts()) assert len(g1contexts)", "rdflib import compare logger = logging.getLogger(\"ldtools\") RESET_SEQ = \"\\033[0m\" COLOR_SEQ", "= web.XmlLexer() formatter = terminal.TerminalFormatter() print(highlight(u'\\n'.join(diff), lexer, formatter)) except ImportError:", "logger.debug(u\"%s are isomorphic\" % str_bit) return print(u\"Differences between %s.\" %", "logger.addHandler(handler) logger2 = logging.getLogger(\"ldtools._add_property\") logger2.setLevel(logging.INFO) mapper = {1: logging.DEBUG, 2:", "%(funcName)s:%(lineno)d\" \" %(levelname)s: %(message)s\") handler = logging.StreamHandler() handler.setFormatter(formatter) logger =", "available\"\"\" # quick fix for wrong type if not type(graph1)", "= dump_nt_sorted(in_second) import difflib diff = difflib.unified_diff( sorted_first, sorted_second, u'Original',", "len(g2contexts) == 1 graph2 = g2contexts[0] # Return if both", "'INFO': MAGENTA, 'WARNING': YELLOW, 'CRITICAL': YELLOW, 'ERROR': RED} def set_colored_logger(verbosity_level):", "list(graph2.contexts()) assert len(g2contexts) == 1 graph2 = g2contexts[0] # Return", "iso2) def dump_nt_sorted(g): return sorted(g.serialize(format='nt').splitlines()) sorted_first = dump_nt_sorted(in_first) sorted_second =", "(graph1.identifier, graph2.identifier)) if iso1 == iso2: logger.debug(u\"%s are isomorphic\" %", "log_level: logger.setLevel(log_level) return logger def my_graph_diff(graph1, graph2): \"\"\"Compares graph2 to", "pygments available\"\"\" # quick fix for wrong type if not", "logger2.setLevel(logging.INFO) mapper = {1: logging.DEBUG, 2: logging.INFO, 3: logging.WARNING, 4:", "= unicode = str # Python 3 import logging import", "graph2.identifier: str_bit = u\"The 2 '%s' Graphs\" % graph1.identifier else:" ]
[ "Packet handlign callbacks DPROCFS = (1 << 4) # procfs", "handling DGENPKTV = (1 << 2) # Generic packet handling", "DIPNAT: 'IPNAT', DMANGLE: 'MANGLE', DPCAP: 'PCAP', DIGN: 'IGN', DFTP: 'FTP',", "DPROCFS = (1 << 4) # procfs DIPTBLS = (1", "DNONLOC: 'NONLOC', DDPF: 'DPF', DDPFV: 'DPFV', DIPNAT: 'IPNAT', DMANGLE: 'MANGLE',", "DIGN | DFTP: 'IGN-FTP', DMISC: 'MISC', } DLABELS_INV = {v.upper():", "output control DNFQUEUE = (1 << 0) # netfilterqueue DGENPKT", "12) # Packet redirect ignore conditions DFTP = (1 <<", "# Packet redirect ignore conditions DFTP = (1 << 13)", "DMANGLE: 'MANGLE', DPCAP: 'PCAP', DIGN: 'IGN', DFTP: 'FTP', DIGN |", "control DNFQUEUE = (1 << 0) # netfilterqueue DGENPKT =", "mask DFLAG = 0xf0000000 # Flag mask DEVERY = 0x0fffffff", "print levels for fine-grained debug trace output control DNFQUEUE =", "fine-grained debug trace output control DNFQUEUE = (1 << 0)", "= (1 << 3) # Packet handlign callbacks DPROCFS =", "Packet mangling DPCAP = (1 << 11) # Pcap write", "<< 12) # Packet redirect ignore conditions DFTP = (1", "debug trace output control DNFQUEUE = (1 << 0) #", "(1 << 8) # DPF (Dynamic Port Forwarding) Verbose DIPNAT", "7) # DPF (Dynamic Port Forwarding) DDPFV = (1 <<", "(1 << 2) # Generic packet handling with TCP analysis", "# procfs DIPTBLS = (1 << 5) # iptables DNONLOC", "analysis DCB = (1 << 3) # Packet handlign callbacks", "Forwarding) Verbose DIPNAT = (1 << 9) # IP redirection", "# DPF (Dynamic Port Forwarding) Verbose DIPNAT = (1 <<", "Miscellaneous DCOMP = 0x0fffffff # Component mask DFLAG = 0xf0000000", "'IGN-FTP', DMISC: 'MISC', } DLABELS_INV = {v.upper(): k for k,", "<< 4) # procfs DIPTBLS = (1 << 5) #", "DIGN = (1 << 12) # Packet redirect ignore conditions", "<< 6) # Nonlocal-destined datagrams DDPF = (1 << 7)", "(1 << 1) # Generic packet handling DGENPKTV = (1", "DMANGLE = (1 << 10) # Packet mangling DPCAP =", "handlign callbacks DPROCFS = (1 << 4) # procfs DIPTBLS", "# netfilterqueue DGENPKT = (1 << 1) # Generic packet", "<< 5) # iptables DNONLOC = (1 << 6) #", "# DPF (Dynamic Port Forwarding) DDPFV = (1 << 8)", "DGENPKTV = (1 << 2) # Generic packet handling with", "DPF (Dynamic Port Forwarding) Verbose DIPNAT = (1 << 9)", "Port Forwarding) Verbose DIPNAT = (1 << 9) # IP", "= (1 << 9) # IP redirection for nonlocal-destined datagrams", "# Pcap write logic DIGN = (1 << 12) #", "ignore conditions DFTP = (1 << 13) # FTP checks", "= { DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV', DCB: 'CB',", "'IPTABLES', DNONLOC: 'NONLOC', DDPF: 'DPF', DDPFV: 'DPFV', DIPNAT: 'IPNAT', DMANGLE:", "# Log everything, complete verbosity DLABELS = { DNFQUEUE: 'NFQUEUE',", "(1 << 27) # Miscellaneous DCOMP = 0x0fffffff # Component", "netfilterqueue DGENPKT = (1 << 1) # Generic packet handling", "verbosity DEVERY2 = 0x8fffffff # Log everything, complete verbosity DLABELS", "# Nonlocal-destined datagrams DDPF = (1 << 7) # DPF", "<< 9) # IP redirection for nonlocal-destined datagrams DMANGLE =", "DNFQUEUE = (1 << 0) # netfilterqueue DGENPKT = (1", "(Dynamic Port Forwarding) Verbose DIPNAT = (1 << 9) #", "'IGN', DFTP: 'FTP', DIGN | DFTP: 'IGN-FTP', DMISC: 'MISC', }", "redirection for nonlocal-destined datagrams DMANGLE = (1 << 10) #", "Log everything, low verbosity DEVERY2 = 0x8fffffff # Log everything,", "everything, low verbosity DEVERY2 = 0x8fffffff # Log everything, complete", "procfs DIPTBLS = (1 << 5) # iptables DNONLOC =", "'MISC', } DLABELS_INV = {v.upper(): k for k, v in", "0) # netfilterqueue DGENPKT = (1 << 1) # Generic", "datagrams DDPF = (1 << 7) # DPF (Dynamic Port", "<< 3) # Packet handlign callbacks DPROCFS = (1 <<", "Verbose DIPNAT = (1 << 9) # IP redirection for", "= 0xf0000000 # Flag mask DEVERY = 0x0fffffff # Log", "mask DEVERY = 0x0fffffff # Log everything, low verbosity DEVERY2", "2) # Generic packet handling with TCP analysis DCB =", "DLABELS = { DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV', DCB:", "= (1 << 1) # Generic packet handling DGENPKTV =", "levels for fine-grained debug trace output control DNFQUEUE = (1", "write logic DIGN = (1 << 12) # Packet redirect", "DCB = (1 << 3) # Packet handlign callbacks DPROCFS", "0x0fffffff # Component mask DFLAG = 0xf0000000 # Flag mask", "(1 << 3) # Packet handlign callbacks DPROCFS = (1", "= (1 << 2) # Generic packet handling with TCP", "callbacks DPROCFS = (1 << 4) # procfs DIPTBLS =", "4) # procfs DIPTBLS = (1 << 5) # iptables", "6) # Nonlocal-destined datagrams DDPF = (1 << 7) #", "<< 7) # DPF (Dynamic Port Forwarding) DDPFV = (1", "8) # DPF (Dynamic Port Forwarding) Verbose DIPNAT = (1", "11) # Pcap write logic DIGN = (1 << 12)", "'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC', DDPF: 'DPF', DDPFV: 'DPFV', DIPNAT:", "redirect ignore conditions DFTP = (1 << 13) # FTP", "9) # IP redirection for nonlocal-destined datagrams DMANGLE = (1", "(Dynamic Port Forwarding) DDPFV = (1 << 8) # DPF", "<< 13) # FTP checks DMISC = (1 << 27)", "low verbosity DEVERY2 = 0x8fffffff # Log everything, complete verbosity", "DFTP: 'FTP', DIGN | DFTP: 'IGN-FTP', DMISC: 'MISC', } DLABELS_INV", "# Packet handlign callbacks DPROCFS = (1 << 4) #", "(1 << 6) # Nonlocal-destined datagrams DDPF = (1 <<", "'GENPKT', DGENPKTV: 'GENPKTV', DCB: 'CB', DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC:", "'MANGLE', DPCAP: 'PCAP', DIGN: 'IGN', DFTP: 'FTP', DIGN | DFTP:", "handling with TCP analysis DCB = (1 << 3) #", "Packet redirect ignore conditions DFTP = (1 << 13) #", "DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC', DDPF: 'DPF', DDPFV: 'DPFV', DIPNAT: 'IPNAT',", "'IPNAT', DMANGLE: 'MANGLE', DPCAP: 'PCAP', DIGN: 'IGN', DFTP: 'FTP', DIGN", "# IP redirection for nonlocal-destined datagrams DMANGLE = (1 <<", "| DFTP: 'IGN-FTP', DMISC: 'MISC', } DLABELS_INV = {v.upper(): k", "# iptables DNONLOC = (1 << 6) # Nonlocal-destined datagrams", "FTP checks DMISC = (1 << 27) # Miscellaneous DCOMP", "13) # FTP checks DMISC = (1 << 27) #", "DPCAP = (1 << 11) # Pcap write logic DIGN", "everything, complete verbosity DLABELS = { DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT',", "DPF (Dynamic Port Forwarding) DDPFV = (1 << 8) #", "(1 << 0) # netfilterqueue DGENPKT = (1 << 1)", "# Component mask DFLAG = 0xf0000000 # Flag mask DEVERY", "# Debug print levels for fine-grained debug trace output control", "verbosity DLABELS = { DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV',", "Component mask DFLAG = 0xf0000000 # Flag mask DEVERY =", "= (1 << 12) # Packet redirect ignore conditions DFTP", "'PCAP', DIGN: 'IGN', DFTP: 'FTP', DIGN | DFTP: 'IGN-FTP', DMISC:", "'FTP', DIGN | DFTP: 'IGN-FTP', DMISC: 'MISC', } DLABELS_INV =", "(1 << 13) # FTP checks DMISC = (1 <<", "DIPNAT = (1 << 9) # IP redirection for nonlocal-destined", "<< 8) # DPF (Dynamic Port Forwarding) Verbose DIPNAT =", "DGENPKT = (1 << 1) # Generic packet handling DGENPKTV", "27) # Miscellaneous DCOMP = 0x0fffffff # Component mask DFLAG", "= 0x8fffffff # Log everything, complete verbosity DLABELS = {", "= (1 << 10) # Packet mangling DPCAP = (1", "complete verbosity DLABELS = { DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV:", "<< 0) # netfilterqueue DGENPKT = (1 << 1) #", "(1 << 9) # IP redirection for nonlocal-destined datagrams DMANGLE", "conditions DFTP = (1 << 13) # FTP checks DMISC", "= 0x0fffffff # Component mask DFLAG = 0xf0000000 # Flag", "(1 << 4) # procfs DIPTBLS = (1 << 5)", "for fine-grained debug trace output control DNFQUEUE = (1 <<", "iptables DNONLOC = (1 << 6) # Nonlocal-destined datagrams DDPF", "} DLABELS_INV = {v.upper(): k for k, v in DLABELS.items()}", "DIGN: 'IGN', DFTP: 'FTP', DIGN | DFTP: 'IGN-FTP', DMISC: 'MISC',", "DDPF = (1 << 7) # DPF (Dynamic Port Forwarding)", "mangling DPCAP = (1 << 11) # Pcap write logic", "= (1 << 5) # iptables DNONLOC = (1 <<", "(1 << 5) # iptables DNONLOC = (1 << 6)", "DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV', DCB: 'CB', DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES',", "<< 2) # Generic packet handling with TCP analysis DCB", "# Flag mask DEVERY = 0x0fffffff # Log everything, low", "(1 << 7) # DPF (Dynamic Port Forwarding) DDPFV =", "= (1 << 11) # Pcap write logic DIGN =", "= 0x0fffffff # Log everything, low verbosity DEVERY2 = 0x8fffffff", "DDPF: 'DPF', DDPFV: 'DPFV', DIPNAT: 'IPNAT', DMANGLE: 'MANGLE', DPCAP: 'PCAP',", "Forwarding) DDPFV = (1 << 8) # DPF (Dynamic Port", "= (1 << 27) # Miscellaneous DCOMP = 0x0fffffff #", "# FTP checks DMISC = (1 << 27) # Miscellaneous", "DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC', DDPF: 'DPF', DDPFV: 'DPFV',", "DGENPKTV: 'GENPKTV', DCB: 'CB', DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC',", "DFTP: 'IGN-FTP', DMISC: 'MISC', } DLABELS_INV = {v.upper(): k for", "Pcap write logic DIGN = (1 << 12) # Packet", "DFLAG = 0xf0000000 # Flag mask DEVERY = 0x0fffffff #", "= (1 << 7) # DPF (Dynamic Port Forwarding) DDPFV", "IP redirection for nonlocal-destined datagrams DMANGLE = (1 << 10)", "Debug print levels for fine-grained debug trace output control DNFQUEUE", "'NONLOC', DDPF: 'DPF', DDPFV: 'DPFV', DIPNAT: 'IPNAT', DMANGLE: 'MANGLE', DPCAP:", "for nonlocal-destined datagrams DMANGLE = (1 << 10) # Packet", "<< 1) # Generic packet handling DGENPKTV = (1 <<", "trace output control DNFQUEUE = (1 << 0) # netfilterqueue", "DMISC = (1 << 27) # Miscellaneous DCOMP = 0x0fffffff", "DCB: 'CB', DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC', DDPF: 'DPF',", "<< 11) # Pcap write logic DIGN = (1 <<", "= (1 << 4) # procfs DIPTBLS = (1 <<", "# Log everything, low verbosity DEVERY2 = 0x8fffffff # Log", "'DPF', DDPFV: 'DPFV', DIPNAT: 'IPNAT', DMANGLE: 'MANGLE', DPCAP: 'PCAP', DIGN:", "= (1 << 13) # FTP checks DMISC = (1", "Generic packet handling with TCP analysis DCB = (1 <<", "0xf0000000 # Flag mask DEVERY = 0x0fffffff # Log everything,", "DNONLOC = (1 << 6) # Nonlocal-destined datagrams DDPF =", "DIPTBLS = (1 << 5) # iptables DNONLOC = (1", "(1 << 10) # Packet mangling DPCAP = (1 <<", "= (1 << 0) # netfilterqueue DGENPKT = (1 <<", "packet handling with TCP analysis DCB = (1 << 3)", "'GENPKTV', DCB: 'CB', DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC', DDPF:", "DDPFV: 'DPFV', DIPNAT: 'IPNAT', DMANGLE: 'MANGLE', DPCAP: 'PCAP', DIGN: 'IGN',", "3) # Packet handlign callbacks DPROCFS = (1 << 4)", "# Miscellaneous DCOMP = 0x0fffffff # Component mask DFLAG =", "DEVERY = 0x0fffffff # Log everything, low verbosity DEVERY2 =", "# Generic packet handling with TCP analysis DCB = (1", "Flag mask DEVERY = 0x0fffffff # Log everything, low verbosity", "0x0fffffff # Log everything, low verbosity DEVERY2 = 0x8fffffff #", "0x8fffffff # Log everything, complete verbosity DLABELS = { DNFQUEUE:", "TCP analysis DCB = (1 << 3) # Packet handlign", "10) # Packet mangling DPCAP = (1 << 11) #", "DCOMP = 0x0fffffff # Component mask DFLAG = 0xf0000000 #", "(1 << 12) # Packet redirect ignore conditions DFTP =", "'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV', DCB: 'CB', DPROCFS: 'PROCFS', DIPTBLS:", "datagrams DMANGLE = (1 << 10) # Packet mangling DPCAP", "with TCP analysis DCB = (1 << 3) # Packet", "DFTP = (1 << 13) # FTP checks DMISC =", "'DPFV', DIPNAT: 'IPNAT', DMANGLE: 'MANGLE', DPCAP: 'PCAP', DIGN: 'IGN', DFTP:", "# Packet mangling DPCAP = (1 << 11) # Pcap", "= (1 << 8) # DPF (Dynamic Port Forwarding) Verbose", "1) # Generic packet handling DGENPKTV = (1 << 2)", "nonlocal-destined datagrams DMANGLE = (1 << 10) # Packet mangling", "Port Forwarding) DDPFV = (1 << 8) # DPF (Dynamic", "(1 << 11) # Pcap write logic DIGN = (1", "checks DMISC = (1 << 27) # Miscellaneous DCOMP =", "Generic packet handling DGENPKTV = (1 << 2) # Generic", "DMISC: 'MISC', } DLABELS_INV = {v.upper(): k for k, v", "packet handling DGENPKTV = (1 << 2) # Generic packet", "<< 10) # Packet mangling DPCAP = (1 << 11)", "DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV', DCB: 'CB', DPROCFS: 'PROCFS',", "DPCAP: 'PCAP', DIGN: 'IGN', DFTP: 'FTP', DIGN | DFTP: 'IGN-FTP',", "DDPFV = (1 << 8) # DPF (Dynamic Port Forwarding)", "Nonlocal-destined datagrams DDPF = (1 << 7) # DPF (Dynamic", "Log everything, complete verbosity DLABELS = { DNFQUEUE: 'NFQUEUE', DGENPKT:", "# Generic packet handling DGENPKTV = (1 << 2) #", "logic DIGN = (1 << 12) # Packet redirect ignore", "{ DNFQUEUE: 'NFQUEUE', DGENPKT: 'GENPKT', DGENPKTV: 'GENPKTV', DCB: 'CB', DPROCFS:", "<< 27) # Miscellaneous DCOMP = 0x0fffffff # Component mask", "DEVERY2 = 0x8fffffff # Log everything, complete verbosity DLABELS =", "= (1 << 6) # Nonlocal-destined datagrams DDPF = (1", "'CB', DPROCFS: 'PROCFS', DIPTBLS: 'IPTABLES', DNONLOC: 'NONLOC', DDPF: 'DPF', DDPFV:", "5) # iptables DNONLOC = (1 << 6) # Nonlocal-destined" ]
[ "training_state, _ = sess.run( [loss, final_state, train_op], feed_dict) if steps", "learning_rate = 0.0001 # build the model rnn_model = MultiRnn(", "= 'sum' # dir to write summary train_dir = 'ckpt'", "from matplotlib import pyplot as plt sum_dir = 'sum' #", "matplotlib import pyplot as plt sum_dir = 'sum' # dir", "format_str = ( '%s: step %d, loss = %.2f (%.1f", "tf.float32, [batch_size, num_steps, 2 * NEFF]) ref_data = tf.placeholder( tf.float32,", "batch_gen = BatchGenerator(data_dir, batch_size, num_steps, epochs) with tf.Session() as sess:", "loss = rnn_model.loss(inf_data, ref_data) saver = tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries()", "train_dir = 'ckpt' # dir to store the model data_dir", "generator for batch data for f_data, b_data, r_data, v_data in", "os import matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot", "set NEFF = 129 # effective FFT points batch_size =", "= time.time() steps += 1 in_data_np = np.concatenate((f_data, b_data), axis=2)", "256 output_size = 129 num_layer = 3 learning_rate = 0.0001", "None: feed_dict[init_state] = training_state # training the net loss_value, training_state,", "tf import numpy as np from input import BatchGenerator from", "# build the model rnn_model = MultiRnn( cell_type, state_size, output_size,", "= sess.run( [loss, final_state, train_op], feed_dict) if steps % 10000", "= 'NL_LSTM' state_size = 256 output_size = 129 num_layer =", "Script for training the model ''' import tensorflow as tf", "= time.time() - start_time sec_per_batch = float(duration) examples_per_sec = batch_size", "the net loss_value, training_state, _, summary_str, test_inf = sess.run( [loss,", "import matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot as", "(format_str % (datetime.now(), steps, loss_value, examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps)", "as plt sum_dir = 'sum' # dir to write summary", "tf.merge_all_summaries() train_op = rnn_model.train(loss) batch_gen = BatchGenerator(data_dir, batch_size, num_steps, epochs)", "num_steps) # input data and referene data placeholder in_data =", "input import BatchGenerator from model import MultiRnn import time from", "in_data_np = np.concatenate((f_data, b_data), axis=2) if steps % 100 ==", "model rnn_model = MultiRnn( cell_type, state_size, output_size, batch_size, num_layer, learning_rate,", "num_steps = 20 epochs = 2000 cell_type = 'NL_LSTM' state_size", "num_steps, 2 * NEFF]) ref_data = tf.placeholder( tf.float32, [batch_size, num_steps,", "mpl.use('Agg') from matplotlib import pyplot as plt sum_dir = 'sum'", "training the model ''' import tensorflow as tf import numpy", "= %.2f (%.1f examples/sec; %.3f ' 'sec/batch, epoch %d)') print", "# dir to store the model data_dir = 'train.pkl' #", "sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps) else: feed_dict = {in_data: in_data_np, ref_data:", "rnn_model.train(loss) batch_gen = BatchGenerator(data_dir, batch_size, num_steps, epochs) with tf.Session() as", "(datetime.now(), steps, loss_value, examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps) else: feed_dict", "store the model data_dir = 'train.pkl' # dir of the", "%d)') print (format_str % (datetime.now(), steps, loss_value, examples_per_sec, sec_per_batch, idx))", "r_data, v_data in epoch: start_time = time.time() steps += 1", "rnn_model.loss(inf_data, ref_data) saver = tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() train_op =", "= rnn_model.loss(inf_data, ref_data) saver = tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() train_op", "feed_dict[init_state] = training_state # training the net loss_value, training_state, _,", "as sess: summary_writer = tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps =", "0.0001 # build the model rnn_model = MultiRnn( cell_type, state_size,", "train_op = rnn_model.train(loss) batch_gen = BatchGenerator(data_dir, batch_size, num_steps, epochs) with", "training_state is not None: feed_dict[init_state] = training_state # training the", "make inference init_state, final_state, inf_data = rnn_model.inference(in_data) # compute loss", "in_data = tf.placeholder( tf.float32, [batch_size, num_steps, 2 * NEFF]) ref_data", "net loss_value, training_state, _, summary_str, test_inf = sess.run( [loss, final_state,", "= training_state loss_value, training_state, _ = sess.run( [loss, final_state, train_op],", "if training_state is not None: feed_dict[init_state] = training_state # training", "time from datetime import datetime import os import matplotlib as", "'sec/batch, epoch %d)') print (format_str % (datetime.now(), steps, loss_value, examples_per_sec,", "+= 1 in_data_np = np.concatenate((f_data, b_data), axis=2) if steps %", "from model import MultiRnn import time from datetime import datetime", "idx)) summary_writer.add_summary(summary_str, steps) else: feed_dict = {in_data: in_data_np, ref_data: r_data}", "duration format_str = ( '%s: step %d, loss = %.2f", "# dir to write summary train_dir = 'ckpt' # dir", "cell_type = 'NL_LSTM' state_size = 256 output_size = 129 num_layer", "state_size, output_size, batch_size, num_layer, learning_rate, num_steps) # input data and", "enumerate(batch_gen.gen_epochs()): training_state = None # generator for batch data for", "loss = %.2f (%.1f examples/sec; %.3f ' 'sec/batch, epoch %d)')", "data_dir = 'train.pkl' # dir of the data set NEFF", "'%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '", "# make inference init_state, final_state, inf_data = rnn_model.inference(in_data) # compute", "mpl mpl.use('Agg') from matplotlib import pyplot as plt sum_dir =", "in epoch: start_time = time.time() steps += 1 in_data_np =", "ref_data) saver = tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() train_op = rnn_model.train(loss)", "training_state # training the net loss_value, training_state, _, summary_str, test_inf", "generator for epoch data for idx, epoch in enumerate(batch_gen.gen_epochs()): training_state", "= ( '%s: step %d, loss = %.2f (%.1f examples/sec;", "2 * NEFF]) ref_data = tf.placeholder( tf.float32, [batch_size, num_steps, NEFF])", "steps, loss_value, examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps) else: feed_dict =", "inf_data = rnn_model.inference(in_data) # compute loss loss = rnn_model.loss(inf_data, ref_data)", "feed_dict) duration = time.time() - start_time sec_per_batch = float(duration) examples_per_sec", "= 256 output_size = 129 num_layer = 3 learning_rate =", "feed_dict) if steps % 10000 == 0: checkpoint_path = os.path.join(train_dir,", "and referene data placeholder in_data = tf.placeholder( tf.float32, [batch_size, num_steps,", "for idx, epoch in enumerate(batch_gen.gen_epochs()): training_state = None # generator", "np.concatenate((f_data, b_data), axis=2) if steps % 100 == 0: feed_dict", "{in_data: in_data_np, ref_data: r_data} if training_state is not None: feed_dict[init_state]", "== 0: feed_dict = {in_data: in_data_np, ref_data: r_data} if training_state", "batch_size, num_steps, epochs) with tf.Session() as sess: summary_writer = tf.train.SummaryWriter(", "for epoch data for idx, epoch in enumerate(batch_gen.gen_epochs()): training_state =", "summary_writer.add_summary(summary_str, steps) else: feed_dict = {in_data: in_data_np, ref_data: r_data} if", "from datetime import datetime import os import matplotlib as mpl", "batch_size, num_layer, learning_rate, num_steps) # input data and referene data", "float(duration) examples_per_sec = batch_size / duration format_str = ( '%s:", "129 num_layer = 3 learning_rate = 0.0001 # build the", "import BatchGenerator from model import MultiRnn import time from datetime", "in_data_np, ref_data: r_data} if training_state is not None: feed_dict[init_state] =", "1 in_data_np = np.concatenate((f_data, b_data), axis=2) if steps % 100", "training the net loss_value, training_state, _, summary_str, test_inf = sess.run(", "step %d, loss = %.2f (%.1f examples/sec; %.3f ' 'sec/batch,", "sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps = 0 # generator for epoch", "train_op, summary_op, inf_data], feed_dict) duration = time.time() - start_time sec_per_batch", "129 # effective FFT points batch_size = 128 num_steps =", "'train.pkl' # dir of the data set NEFF = 129", "= tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() train_op = rnn_model.train(loss) batch_gen =", "FFT points batch_size = 128 num_steps = 20 epochs =", "write summary train_dir = 'ckpt' # dir to store the", "rnn_model.inference(in_data) # compute loss loss = rnn_model.loss(inf_data, ref_data) saver =", "input data and referene data placeholder in_data = tf.placeholder( tf.float32,", "for batch data for f_data, b_data, r_data, v_data in epoch:", "v_data in epoch: start_time = time.time() steps += 1 in_data_np", "[loss, final_state, train_op, summary_op, inf_data], feed_dict) duration = time.time() -", "( '%s: step %d, loss = %.2f (%.1f examples/sec; %.3f", "import tensorflow as tf import numpy as np from input", "NEFF]) # make inference init_state, final_state, inf_data = rnn_model.inference(in_data) #", "batch_size = 128 num_steps = 20 epochs = 2000 cell_type", "_, summary_str, test_inf = sess.run( [loss, final_state, train_op, summary_op, inf_data],", "NEFF = 129 # effective FFT points batch_size = 128", "time.time() steps += 1 in_data_np = np.concatenate((f_data, b_data), axis=2) if", "0: feed_dict = {in_data: in_data_np, ref_data: r_data} if training_state is", "examples/sec; %.3f ' 'sec/batch, epoch %d)') print (format_str % (datetime.now(),", "epochs) with tf.Session() as sess: summary_writer = tf.train.SummaryWriter( sum_dir, sess.graph)", "tensorflow as tf import numpy as np from input import", "summary_op = tf.merge_all_summaries() train_op = rnn_model.train(loss) batch_gen = BatchGenerator(data_dir, batch_size,", "as np from input import BatchGenerator from model import MultiRnn", "= tf.placeholder( tf.float32, [batch_size, num_steps, 2 * NEFF]) ref_data =", "training_state is not None: feed_dict[init_state] = training_state loss_value, training_state, _", "learning_rate, num_steps) # input data and referene data placeholder in_data", "_ = sess.run( [loss, final_state, train_op], feed_dict) if steps %", "= 2000 cell_type = 'NL_LSTM' state_size = 256 output_size =", "/ duration format_str = ( '%s: step %d, loss =", "the data set NEFF = 129 # effective FFT points", "plt sum_dir = 'sum' # dir to write summary train_dir", "tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps = 0 # generator for", "referene data placeholder in_data = tf.placeholder( tf.float32, [batch_size, num_steps, 2", "to store the model data_dir = 'train.pkl' # dir of", "epoch: start_time = time.time() steps += 1 in_data_np = np.concatenate((f_data,", "sess.run( [loss, final_state, train_op, summary_op, inf_data], feed_dict) duration = time.time()", "BatchGenerator(data_dir, batch_size, num_steps, epochs) with tf.Session() as sess: summary_writer =", "if steps % 10000 == 0: checkpoint_path = os.path.join(train_dir, 'model.ckpt')", "= 'ckpt' # dir to store the model data_dir =", "matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot as plt", "start_time = time.time() steps += 1 in_data_np = np.concatenate((f_data, b_data),", "sess.graph) sess.run(tf.initialize_all_variables()) steps = 0 # generator for epoch data", "= tf.merge_all_summaries() train_op = rnn_model.train(loss) batch_gen = BatchGenerator(data_dir, batch_size, num_steps,", "= training_state # training the net loss_value, training_state, _, summary_str,", "time.time() - start_time sec_per_batch = float(duration) examples_per_sec = batch_size /", "%.3f ' 'sec/batch, epoch %d)') print (format_str % (datetime.now(), steps,", "loss_value, training_state, _, summary_str, test_inf = sess.run( [loss, final_state, train_op,", "= rnn_model.train(loss) batch_gen = BatchGenerator(data_dir, batch_size, num_steps, epochs) with tf.Session()", "summary train_dir = 'ckpt' # dir to store the model", "is not None: feed_dict[init_state] = training_state # training the net", "dir of the data set NEFF = 129 # effective", "num_steps, NEFF]) # make inference init_state, final_state, inf_data = rnn_model.inference(in_data)", "feed_dict = {in_data: in_data_np, ref_data: r_data} if training_state is not", "training_state = None # generator for batch data for f_data,", "'ckpt' # dir to store the model data_dir = 'train.pkl'", "build the model rnn_model = MultiRnn( cell_type, state_size, output_size, batch_size,", "= 'train.pkl' # dir of the data set NEFF =", "compute loss loss = rnn_model.loss(inf_data, ref_data) saver = tf.train.Saver(tf.all_variables()) summary_op", "the model data_dir = 'train.pkl' # dir of the data", "''' import tensorflow as tf import numpy as np from", "inf_data], feed_dict) duration = time.time() - start_time sec_per_batch = float(duration)", "test_inf = sess.run( [loss, final_state, train_op, summary_op, inf_data], feed_dict) duration", "[batch_size, num_steps, 2 * NEFF]) ref_data = tf.placeholder( tf.float32, [batch_size,", "data for f_data, b_data, r_data, v_data in epoch: start_time =", "# compute loss loss = rnn_model.loss(inf_data, ref_data) saver = tf.train.Saver(tf.all_variables())", "model data_dir = 'train.pkl' # dir of the data set", "rnn_model = MultiRnn( cell_type, state_size, output_size, batch_size, num_layer, learning_rate, num_steps)", "output_size, batch_size, num_layer, learning_rate, num_steps) # input data and referene", "not None: feed_dict[init_state] = training_state # training the net loss_value,", "import pyplot as plt sum_dir = 'sum' # dir to", "from input import BatchGenerator from model import MultiRnn import time", "num_layer, learning_rate, num_steps) # input data and referene data placeholder", "= 20 epochs = 2000 cell_type = 'NL_LSTM' state_size =", "= tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps = 0 # generator", "= tf.placeholder( tf.float32, [batch_size, num_steps, NEFF]) # make inference init_state,", "None # generator for batch data for f_data, b_data, r_data,", "% (datetime.now(), steps, loss_value, examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps) else:", "tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() train_op = rnn_model.train(loss) batch_gen = BatchGenerator(data_dir,", "points batch_size = 128 num_steps = 20 epochs = 2000", "in enumerate(batch_gen.gen_epochs()): training_state = None # generator for batch data", "else: feed_dict = {in_data: in_data_np, ref_data: r_data} if training_state is", "sec_per_batch = float(duration) examples_per_sec = batch_size / duration format_str =", "output_size = 129 num_layer = 3 learning_rate = 0.0001 #", "= {in_data: in_data_np, ref_data: r_data} if training_state is not None:", "final_state, train_op], feed_dict) if steps % 10000 == 0: checkpoint_path", "import datetime import os import matplotlib as mpl mpl.use('Agg') from", "the model ''' import tensorflow as tf import numpy as", "batch_size / duration format_str = ( '%s: step %d, loss", "to write summary train_dir = 'ckpt' # dir to store", "saver = tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() train_op = rnn_model.train(loss) batch_gen", "tf.float32, [batch_size, num_steps, NEFF]) # make inference init_state, final_state, inf_data", "import time from datetime import datetime import os import matplotlib", "examples_per_sec = batch_size / duration format_str = ( '%s: step", "# training the net loss_value, training_state, _, summary_str, test_inf =", "= None # generator for batch data for f_data, b_data,", "# effective FFT points batch_size = 128 num_steps = 20", "axis=2) if steps % 100 == 0: feed_dict = {in_data:", "model ''' import tensorflow as tf import numpy as np", "# generator for epoch data for idx, epoch in enumerate(batch_gen.gen_epochs()):", "loss loss = rnn_model.loss(inf_data, ref_data) saver = tf.train.Saver(tf.all_variables()) summary_op =", "np from input import BatchGenerator from model import MultiRnn import", "MultiRnn( cell_type, state_size, output_size, batch_size, num_layer, learning_rate, num_steps) # input", "%d, loss = %.2f (%.1f examples/sec; %.3f ' 'sec/batch, epoch", "steps) else: feed_dict = {in_data: in_data_np, ref_data: r_data} if training_state", "final_state, train_op, summary_op, inf_data], feed_dict) duration = time.time() - start_time", "r_data} if training_state is not None: feed_dict[init_state] = training_state loss_value,", "of the data set NEFF = 129 # effective FFT", "'NL_LSTM' state_size = 256 output_size = 129 num_layer = 3", "100 == 0: feed_dict = {in_data: in_data_np, ref_data: r_data} if", "dir to write summary train_dir = 'ckpt' # dir to", "sess.run(tf.initialize_all_variables()) steps = 0 # generator for epoch data for", "# dir of the data set NEFF = 129 #", "print (format_str % (datetime.now(), steps, loss_value, examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str,", "summary_op, inf_data], feed_dict) duration = time.time() - start_time sec_per_batch =", "for training the model ''' import tensorflow as tf import", "= 0.0001 # build the model rnn_model = MultiRnn( cell_type,", "import MultiRnn import time from datetime import datetime import os", "MultiRnn import time from datetime import datetime import os import", "cell_type, state_size, output_size, batch_size, num_layer, learning_rate, num_steps) # input data", "for f_data, b_data, r_data, v_data in epoch: start_time = time.time()", "import os import matplotlib as mpl mpl.use('Agg') from matplotlib import", "num_layer = 3 learning_rate = 0.0001 # build the model", "datetime import datetime import os import matplotlib as mpl mpl.use('Agg')", "''' Script for training the model ''' import tensorflow as", "% 10000 == 0: checkpoint_path = os.path.join(train_dir, 'model.ckpt') saver.save(sess, checkpoint_path,", "= MultiRnn( cell_type, state_size, output_size, batch_size, num_layer, learning_rate, num_steps) #", "(%.1f examples/sec; %.3f ' 'sec/batch, epoch %d)') print (format_str %", "% 100 == 0: feed_dict = {in_data: in_data_np, ref_data: r_data}", "start_time sec_per_batch = float(duration) examples_per_sec = batch_size / duration format_str", "state_size = 256 output_size = 129 num_layer = 3 learning_rate", "3 learning_rate = 0.0001 # build the model rnn_model =", "batch data for f_data, b_data, r_data, v_data in epoch: start_time", "dir to store the model data_dir = 'train.pkl' # dir", "= 129 num_layer = 3 learning_rate = 0.0001 # build", "as tf import numpy as np from input import BatchGenerator", "0 # generator for epoch data for idx, epoch in", "feed_dict[init_state] = training_state loss_value, training_state, _ = sess.run( [loss, final_state,", "[loss, final_state, train_op], feed_dict) if steps % 10000 == 0:", "steps % 100 == 0: feed_dict = {in_data: in_data_np, ref_data:", "epochs = 2000 cell_type = 'NL_LSTM' state_size = 256 output_size", "summary_writer = tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps = 0 #", "loss_value, examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps) else: feed_dict = {in_data:", "10000 == 0: checkpoint_path = os.path.join(train_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=steps)", "not None: feed_dict[init_state] = training_state loss_value, training_state, _ = sess.run(", "inference init_state, final_state, inf_data = rnn_model.inference(in_data) # compute loss loss", "data placeholder in_data = tf.placeholder( tf.float32, [batch_size, num_steps, 2 *", "pyplot as plt sum_dir = 'sum' # dir to write", "= float(duration) examples_per_sec = batch_size / duration format_str = (", "tf.placeholder( tf.float32, [batch_size, num_steps, 2 * NEFF]) ref_data = tf.placeholder(", "summary_str, test_inf = sess.run( [loss, final_state, train_op, summary_op, inf_data], feed_dict)", "' 'sec/batch, epoch %d)') print (format_str % (datetime.now(), steps, loss_value,", "r_data} if training_state is not None: feed_dict[init_state] = training_state #", "sess.run( [loss, final_state, train_op], feed_dict) if steps % 10000 ==", "= sess.run( [loss, final_state, train_op, summary_op, inf_data], feed_dict) duration =", "if training_state is not None: feed_dict[init_state] = training_state loss_value, training_state,", "train_op], feed_dict) if steps % 10000 == 0: checkpoint_path =", "'sum' # dir to write summary train_dir = 'ckpt' #", "epoch in enumerate(batch_gen.gen_epochs()): training_state = None # generator for batch", "20 epochs = 2000 cell_type = 'NL_LSTM' state_size = 256", "training_state loss_value, training_state, _ = sess.run( [loss, final_state, train_op], feed_dict)", "tf.placeholder( tf.float32, [batch_size, num_steps, NEFF]) # make inference init_state, final_state,", "b_data), axis=2) if steps % 100 == 0: feed_dict =", "datetime import os import matplotlib as mpl mpl.use('Agg') from matplotlib", "%.2f (%.1f examples/sec; %.3f ' 'sec/batch, epoch %d)') print (format_str", "= 0 # generator for epoch data for idx, epoch", "2000 cell_type = 'NL_LSTM' state_size = 256 output_size = 129", "num_steps, epochs) with tf.Session() as sess: summary_writer = tf.train.SummaryWriter( sum_dir,", "[batch_size, num_steps, NEFF]) # make inference init_state, final_state, inf_data =", "ref_data: r_data} if training_state is not None: feed_dict[init_state] = training_state", "data for idx, epoch in enumerate(batch_gen.gen_epochs()): training_state = None #", "data set NEFF = 129 # effective FFT points batch_size", "= 128 num_steps = 20 epochs = 2000 cell_type =", "<filename>multichannel_lstm/train.py ''' Script for training the model ''' import tensorflow", "BatchGenerator from model import MultiRnn import time from datetime import", "final_state, inf_data = rnn_model.inference(in_data) # compute loss loss = rnn_model.loss(inf_data,", "duration = time.time() - start_time sec_per_batch = float(duration) examples_per_sec =", "# input data and referene data placeholder in_data = tf.placeholder(", "sess: summary_writer = tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps = 0", "with tf.Session() as sess: summary_writer = tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables())", "import numpy as np from input import BatchGenerator from model", "steps % 10000 == 0: checkpoint_path = os.path.join(train_dir, 'model.ckpt') saver.save(sess,", "epoch data for idx, epoch in enumerate(batch_gen.gen_epochs()): training_state = None", "numpy as np from input import BatchGenerator from model import", "steps = 0 # generator for epoch data for idx,", "effective FFT points batch_size = 128 num_steps = 20 epochs", "128 num_steps = 20 epochs = 2000 cell_type = 'NL_LSTM'", "training_state, _, summary_str, test_inf = sess.run( [loss, final_state, train_op, summary_op,", "steps += 1 in_data_np = np.concatenate((f_data, b_data), axis=2) if steps", "f_data, b_data, r_data, v_data in epoch: start_time = time.time() steps", "= 129 # effective FFT points batch_size = 128 num_steps", "= rnn_model.inference(in_data) # compute loss loss = rnn_model.loss(inf_data, ref_data) saver", "if steps % 100 == 0: feed_dict = {in_data: in_data_np,", "data and referene data placeholder in_data = tf.placeholder( tf.float32, [batch_size,", "examples_per_sec, sec_per_batch, idx)) summary_writer.add_summary(summary_str, steps) else: feed_dict = {in_data: in_data_np,", "= BatchGenerator(data_dir, batch_size, num_steps, epochs) with tf.Session() as sess: summary_writer", "the model rnn_model = MultiRnn( cell_type, state_size, output_size, batch_size, num_layer,", "ref_data = tf.placeholder( tf.float32, [batch_size, num_steps, NEFF]) # make inference", "= np.concatenate((f_data, b_data), axis=2) if steps % 100 == 0:", "as mpl mpl.use('Agg') from matplotlib import pyplot as plt sum_dir", "tf.Session() as sess: summary_writer = tf.train.SummaryWriter( sum_dir, sess.graph) sess.run(tf.initialize_all_variables()) steps", "loss_value, training_state, _ = sess.run( [loss, final_state, train_op], feed_dict) if", "# generator for batch data for f_data, b_data, r_data, v_data", "* NEFF]) ref_data = tf.placeholder( tf.float32, [batch_size, num_steps, NEFF]) #", "- start_time sec_per_batch = float(duration) examples_per_sec = batch_size / duration", "None: feed_dict[init_state] = training_state loss_value, training_state, _ = sess.run( [loss,", "model import MultiRnn import time from datetime import datetime import", "idx, epoch in enumerate(batch_gen.gen_epochs()): training_state = None # generator for", "epoch %d)') print (format_str % (datetime.now(), steps, loss_value, examples_per_sec, sec_per_batch,", "= 3 learning_rate = 0.0001 # build the model rnn_model", "placeholder in_data = tf.placeholder( tf.float32, [batch_size, num_steps, 2 * NEFF])", "sum_dir = 'sum' # dir to write summary train_dir =", "= batch_size / duration format_str = ( '%s: step %d,", "is not None: feed_dict[init_state] = training_state loss_value, training_state, _ =", "NEFF]) ref_data = tf.placeholder( tf.float32, [batch_size, num_steps, NEFF]) # make", "b_data, r_data, v_data in epoch: start_time = time.time() steps +=", "init_state, final_state, inf_data = rnn_model.inference(in_data) # compute loss loss =" ]
[ "DagsterInstance.get() as instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else: click.echo(\"Daemon(s)", "statuses\", ) def debug_heartbeat_dump_command(): with DagsterInstance.get() as instance: for daemon_type", "to allow a daemon to go without heartbeating before failing", "go without heartbeating before failing the dagster-daemon process.\", ) def", "from dagster.core.instance import DagsterInstance from dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController,", "sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check for recent heartbeats from the daemon.\",", "liveness_check_command, \"wipe\": wipe_command, \"debug\": debug_group, } @click.group(commands=commands) @click.version_option(version=__version__) def group():", "@click.command( name=\"run\", help=\"Run any daemons configured on the DagsterInstance.\", )", "correctly and that \" \"you have created a dagster.yaml file", "\"the DAGSTER_HOME environment variable has been set correctly and that", "ExitStack import click import pendulum from dagster import __version__ from", "click import pendulum from dagster import __version__ from dagster.core.instance import", "instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller: controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED, use", "created a dagster.yaml file there.\" ) with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()", "heartbeats wiped\") @click.command( name=\"heartbeat\", help=\"Read and write a heartbeat\", )", "def group(): \"CLI tools for working with the dagster daemon", ") def wipe_command(): with DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats", "health_check_command, \"liveness-check\": liveness_check_command, \"wipe\": wipe_command, \"debug\": debug_group, } @click.group(commands=commands) @click.version_option(version=__version__)", "the DagsterInstance.\", ) def run_command(): with capture_interrupts(): with DagsterInstance.get() as", "instance: if instance.is_ephemeral: raise Exception( \"dagster-daemon can't run using an", "else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run any daemons configured on the", "tools for working with the dagster daemon process.\" return group", ") @click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in seconds) to", "else: click.echo(\"Daemon(s) not running\") sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe all heartbeats", "import threading import time import warnings from contextlib import ExitStack", "liveness-check instead\", ) def health_check_command(): warnings.warn(\"health-check is deprecated. Use liveness-check", "heartbeating before failing the dagster-daemon process.\", ) def liveness_check_command(): with", "commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} ) def debug_group(): \"Daemon debugging utils\"", "with DagsterInstance.get() as instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log all heartbeat", "<reponame>elsenorbw/dagster import os import sys import threading import time import", "DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run any daemons configured on the DagsterInstance.\",", "instance.is_ephemeral: raise Exception( \"dagster-daemon can't run using an in-memory instance.", "sys import threading import time import warnings from contextlib import", ") def run_command(): with capture_interrupts(): with DagsterInstance.get() as instance: if", "Make sure \" \"the DAGSTER_HOME environment variable has been set", "instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\") @click.command( name=\"heartbeat\", help=\"Read and write a", "if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run any daemons configured", "on the DagsterInstance.\", ) def run_command(): with capture_interrupts(): with DagsterInstance.get()", "\"you have created a dagster.yaml file there.\" ) with daemon_controller_from_instance(", "run_command(): with capture_interrupts(): with DagsterInstance.get() as instance: if instance.is_ephemeral: raise", "with DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\") @click.command( name=\"heartbeat\",", "DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\") @click.command( name=\"heartbeat\", help=\"Read", "daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} ) def debug_group(): \"Daemon", "with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller: controller.check_daemon_loop() @click.command( name=\"health-check\",", "running\") sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe all heartbeats from storage.\", )", "@click.group(commands=commands) @click.version_option(version=__version__) def group(): \"CLI tools for working with the", "all heartbeat statuses\", ) def debug_heartbeat_dump_command(): with DagsterInstance.get() as instance:", "dagster.core.instance import DagsterInstance from dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy,", "seconds) to allow a daemon to go without heartbeating before", "all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else: click.echo(\"Daemon(s) not running\") sys.exit(1) @click.command(", "write a heartbeat\", ) def debug_heartbeat_command(): with DagsterInstance.get() as instance:", "name=\"heartbeat-dump\", help=\"Log all heartbeat statuses\", ) def debug_heartbeat_dump_command(): with DagsterInstance.get()", "import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, )", "= os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance) if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS", "as instance: if instance.is_ephemeral: raise Exception( \"dagster-daemon can't run using", "\"liveness-check\": liveness_check_command, \"wipe\": wipe_command, \"debug\": debug_group, } @click.group(commands=commands) @click.version_option(version=__version__) def", ") as controller: controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED, use liveness-check instead\",", "import time import warnings from contextlib import ExitStack import click", "DagsterInstance.get() as instance: for daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group(", "time import warnings from contextlib import ExitStack import click import", "live\") else: click.echo(\"Daemon(s) not running\") sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe all", "have created a dagster.yaml file there.\" ) with daemon_controller_from_instance( instance,", "{ \"run\": run_command, \"health-check\": health_check_command, \"liveness-check\": liveness_check_command, \"wipe\": wipe_command, \"debug\":", "dagster daemon process.\" return group cli = create_dagster_daemon_cli() def main():", "click.echo(\"Daemon healthy\") else: click.echo(\"Daemon not healthy\") sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check", "_get_heartbeat_tolerance(): tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance) if tolerance", ") def liveness_check_command(): with DagsterInstance.get() as instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()):", "\"heartbeat-dump\": debug_heartbeat_dump_command} ) def debug_group(): \"Daemon debugging utils\" def create_dagster_daemon_cli():", "dagster-daemon process.\", ) def liveness_check_command(): with DagsterInstance.get() as instance: if", "set correctly and that \" \"you have created a dagster.yaml", "(in seconds) to allow a daemon to go without heartbeating", "if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else: click.echo(\"Daemon(s) not running\") sys.exit(1)", "help=\"Log all heartbeat statuses\", ) def debug_heartbeat_dump_command(): with DagsterInstance.get() as", "run_command, \"health-check\": health_check_command, \"liveness-check\": liveness_check_command, \"wipe\": wipe_command, \"debug\": debug_group, }", "help=\"Check for recent heartbeats from the daemon.\", ) @click.option( \"--heartbeat-tolerance\",", "return int(tolerance) if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run any", "instead.\") with DagsterInstance.get() as instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\")", "instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} ) def", "@click.version_option(version=__version__) def group(): \"CLI tools for working with the dagster", "\"Daemon debugging utils\" def create_dagster_daemon_cli(): commands = { \"run\": run_command,", "\"run\": run_command, \"health-check\": health_check_command, \"liveness-check\": liveness_check_command, \"wipe\": wipe_command, \"debug\": debug_group,", "for recent heartbeats from the daemon.\", ) @click.option( \"--heartbeat-tolerance\", required=False,", "daemon process.\" return group cli = create_dagster_daemon_cli() def main(): cli(obj={})", "click.echo(\"Daemon(s) not running\") sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe all heartbeats from", "\" \"you have created a dagster.yaml file there.\" ) with", "else: click.echo(\"Daemon not healthy\") sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check for recent", "@click.command( name=\"heartbeat\", help=\"Read and write a heartbeat\", ) def debug_heartbeat_command():", "DagsterInstance.get() as instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else: click.echo(\"Daemon", "with DagsterInstance.get() as instance: if instance.is_ephemeral: raise Exception( \"dagster-daemon can't", "name=\"run\", help=\"Run any daemons configured on the DagsterInstance.\", ) def", "controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED, use liveness-check instead\", ) def health_check_command():", "def liveness_check_command(): with DagsterInstance.get() as instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon", "__version__ from dagster.core.instance import DagsterInstance from dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS,", "debug_heartbeat_dump_command(): with DagsterInstance.get() as instance: for daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance,", "name=\"liveness-check\", help=\"Check for recent heartbeats from the daemon.\", ) @click.option(", "a dagster.yaml file there.\" ) with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() )", "an in-memory instance. Make sure \" \"the DAGSTER_HOME environment variable", "debug_daemon_heartbeats, get_daemon_status, ) from dagster.utils.interrupts import capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance():", "import sys import threading import time import warnings from contextlib", "deprecated. Use liveness-check instead.\") with DagsterInstance.get() as instance: if all_daemons_healthy(instance,", "with capture_interrupts(): with DagsterInstance.get() as instance: if instance.is_ephemeral: raise Exception(", "raise_interrupts_as def _get_heartbeat_tolerance(): tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance)", "threading import time import warnings from contextlib import ExitStack import", "help=\"How long (in seconds) to allow a daemon to go", "DagsterInstance from dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance,", "} @click.group(commands=commands) @click.version_option(version=__version__) def group(): \"CLI tools for working with", "debug_heartbeat_command(): with DagsterInstance.get() as instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log all", "\"CLI tools for working with the dagster daemon process.\" return", "name=\"health-check\", help=\"DEPRECATED, use liveness-check instead\", ) def health_check_command(): warnings.warn(\"health-check is", "( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, ) from", "in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} )", "process.\" return group cli = create_dagster_daemon_cli() def main(): cli(obj={}) #", "Exception( \"dagster-daemon can't run using an in-memory instance. Make sure", "from storage.\", ) def wipe_command(): with DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats()", "\"debug\": debug_group, } @click.group(commands=commands) @click.version_option(version=__version__) def group(): \"CLI tools for", ") from dagster.utils.interrupts import capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance(): tolerance =", "for working with the dagster daemon process.\" return group cli", "DAGSTER_HOME environment variable has been set correctly and that \"", "def health_check_command(): warnings.warn(\"health-check is deprecated. Use liveness-check instead.\") with DagsterInstance.get()", "from dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats,", "pendulum from dagster import __version__ from dagster.core.instance import DagsterInstance from", "def _get_heartbeat_tolerance(): tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance) if", "dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status,", "configured on the DagsterInstance.\", ) def run_command(): with capture_interrupts(): with", "using an in-memory instance. Make sure \" \"the DAGSTER_HOME environment", "environment variable has been set correctly and that \" \"you", "help=\"Run any daemons configured on the DagsterInstance.\", ) def run_command():", "all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, ) from dagster.utils.interrupts import capture_interrupts, raise_interrupts_as", "liveness-check instead.\") with DagsterInstance.get() as instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon", "without heartbeating before failing the dagster-daemon process.\", ) def liveness_check_command():", "@click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in seconds) to allow", "all heartbeats from storage.\", ) def wipe_command(): with DagsterInstance.get() as", "debug_heartbeat_dump_command} ) def debug_group(): \"Daemon debugging utils\" def create_dagster_daemon_cli(): commands", "before failing the dagster-daemon process.\", ) def liveness_check_command(): with DagsterInstance.get()", "as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\") @click.command( name=\"heartbeat\", help=\"Read and", "import pendulum from dagster import __version__ from dagster.core.instance import DagsterInstance", "is deprecated. Use liveness-check instead.\") with DagsterInstance.get() as instance: if", "tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance) if tolerance else", "has been set correctly and that \" \"you have created", "click.echo(\"Daemon not healthy\") sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check for recent heartbeats", "int(tolerance) if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run any daemons", "dagster import __version__ from dagster.core.instance import DagsterInstance from dagster.daemon.controller import", "\"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in seconds) to allow a", "instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else: click.echo(\"Daemon(s) not running\")", "instance. Make sure \" \"the DAGSTER_HOME environment variable has been", "debug_group, } @click.group(commands=commands) @click.version_option(version=__version__) def group(): \"CLI tools for working", "Use liveness-check instead.\") with DagsterInstance.get() as instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()):", "that \" \"you have created a dagster.yaml file there.\" )", "a daemon to go without heartbeating before failing the dagster-daemon", "\" \"the DAGSTER_HOME environment variable has been set correctly and", "storage.\", ) def wipe_command(): with DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon", "contextlib import ExitStack import click import pendulum from dagster import", "help=\"Read and write a heartbeat\", ) def debug_heartbeat_command(): with DagsterInstance.get()", "healthy\") else: click.echo(\"Daemon not healthy\") sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check for", "health_check_command(): warnings.warn(\"health-check is deprecated. Use liveness-check instead.\") with DagsterInstance.get() as", "instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else: click.echo(\"Daemon not healthy\")", "def create_dagster_daemon_cli(): commands = { \"run\": run_command, \"health-check\": health_check_command, \"liveness-check\":", "wipe_command(): with DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\") @click.command(", "from the daemon.\", ) @click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long", "can't run using an in-memory instance. Make sure \" \"the", "run using an in-memory instance. Make sure \" \"the DAGSTER_HOME", "heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller: controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED, use liveness-check", "name=\"wipe\", help=\"Wipe all heartbeats from storage.\", ) def wipe_command(): with", "tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run any daemons configured on", "heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else: click.echo(\"Daemon not healthy\") sys.exit(1) @click.command( name=\"liveness-check\",", "from contextlib import ExitStack import click import pendulum from dagster", "DagsterInstance.\", ) def run_command(): with capture_interrupts(): with DagsterInstance.get() as instance:", "and that \" \"you have created a dagster.yaml file there.\"", "controller: controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED, use liveness-check instead\", ) def", "a heartbeat\", ) def debug_heartbeat_command(): with DagsterInstance.get() as instance: debug_daemon_heartbeats(instance)", "instance: for daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command,", ") return int(tolerance) if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\", help=\"Run", "with DagsterInstance.get() as instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else:", "with DagsterInstance.get() as instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else:", ") def debug_heartbeat_dump_command(): with DagsterInstance.get() as instance: for daemon_type in", "heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else: click.echo(\"Daemon(s) not running\") sys.exit(1) @click.command( name=\"wipe\",", "debug_group(): \"Daemon debugging utils\" def create_dagster_daemon_cli(): commands = { \"run\":", "\"health-check\": health_check_command, \"liveness-check\": liveness_check_command, \"wipe\": wipe_command, \"debug\": debug_group, } @click.group(commands=commands)", "def debug_group(): \"Daemon debugging utils\" def create_dagster_daemon_cli(): commands = {", "file there.\" ) with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller:", "\"dagster-daemon can't run using an in-memory instance. Make sure \"", ") with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller: controller.check_daemon_loop() @click.command(", "the dagster daemon process.\" return group cli = create_dagster_daemon_cli() def", "wiped\") @click.command( name=\"heartbeat\", help=\"Read and write a heartbeat\", ) def", "daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller: controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED,", "as controller: controller.check_daemon_loop() @click.command( name=\"health-check\", help=\"DEPRECATED, use liveness-check instead\", )", "daemon.\", ) @click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in seconds)", "as instance: for daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\":", "healthy\") sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check for recent heartbeats from the", "get_daemon_status, ) from dagster.utils.interrupts import capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance(): tolerance", "any daemons configured on the DagsterInstance.\", ) def run_command(): with", "not healthy\") sys.exit(1) @click.command( name=\"liveness-check\", help=\"Check for recent heartbeats from", "daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, ) from dagster.utils.interrupts import capture_interrupts, raise_interrupts_as def", "long (in seconds) to allow a daemon to go without", "debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} ) def debug_group(): \"Daemon debugging utils\" def", "@click.command( name=\"wipe\", help=\"Wipe all heartbeats from storage.\", ) def wipe_command():", "working with the dagster daemon process.\" return group cli =", "variable has been set correctly and that \" \"you have", "the daemon.\", ) @click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in", "been set correctly and that \" \"you have created a", "help=\"Wipe all heartbeats from storage.\", ) def wipe_command(): with DagsterInstance.get()", "as instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\") else: click.echo(\"Daemon(s) not", "def wipe_command(): with DagsterInstance.get() as instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\")", "warnings from contextlib import ExitStack import click import pendulum from", "= { \"run\": run_command, \"health-check\": health_check_command, \"liveness-check\": liveness_check_command, \"wipe\": wipe_command,", "warnings.warn(\"health-check is deprecated. Use liveness-check instead.\") with DagsterInstance.get() as instance:", "import warnings from contextlib import ExitStack import click import pendulum", "\"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance) if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command( name=\"run\",", "import __version__ from dagster.core.instance import DagsterInstance from dagster.daemon.controller import (", "sure \" \"the DAGSTER_HOME environment variable has been set correctly", "to go without heartbeating before failing the dagster-daemon process.\", )", "sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe all heartbeats from storage.\", ) def", "def debug_heartbeat_command(): with DagsterInstance.get() as instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log", "all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else: click.echo(\"Daemon not healthy\") sys.exit(1) @click.command(", "utils\" def create_dagster_daemon_cli(): commands = { \"run\": run_command, \"health-check\": health_check_command,", "with the dagster daemon process.\" return group cli = create_dagster_daemon_cli()", "instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log all heartbeat statuses\", ) def", "failing the dagster-daemon process.\", ) def liveness_check_command(): with DagsterInstance.get() as", "recent heartbeats from the daemon.\", ) @click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS,", "the dagster-daemon process.\", ) def liveness_check_command(): with DagsterInstance.get() as instance:", "all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, ) from dagster.utils.interrupts import capture_interrupts,", "process.\", ) def liveness_check_command(): with DagsterInstance.get() as instance: if all_daemons_live(instance,", "debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log all heartbeat statuses\", ) def debug_heartbeat_dump_command():", "commands = { \"run\": run_command, \"health-check\": health_check_command, \"liveness-check\": liveness_check_command, \"wipe\":", "@click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} ) def debug_group(): \"Daemon debugging", "instance: instance.wipe_daemon_heartbeats() click.echo(\"Daemon heartbeats wiped\") @click.command( name=\"heartbeat\", help=\"Read and write", "capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance(): tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return", "heartbeats from the daemon.\", ) @click.option( \"--heartbeat-tolerance\", required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How", "dagster.utils.interrupts import capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance(): tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\",", "capture_interrupts(): with DagsterInstance.get() as instance: if instance.is_ephemeral: raise Exception( \"dagster-daemon", "@click.command( name=\"liveness-check\", help=\"Check for recent heartbeats from the daemon.\", )", "debugging utils\" def create_dagster_daemon_cli(): commands = { \"run\": run_command, \"health-check\":", "click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command} ) def debug_group():", "import click import pendulum from dagster import __version__ from dagster.core.instance", "import ExitStack import click import pendulum from dagster import __version__", "allow a daemon to go without heartbeating before failing the", "click.echo(\"Daemon heartbeats wiped\") @click.command( name=\"heartbeat\", help=\"Read and write a heartbeat\",", "there.\" ) with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as controller: controller.check_daemon_loop()", "in-memory instance. Make sure \" \"the DAGSTER_HOME environment variable has", "as instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log all heartbeat statuses\", )", ") def health_check_command(): warnings.warn(\"health-check is deprecated. Use liveness-check instead.\") with", "@click.command( name=\"heartbeat-dump\", help=\"Log all heartbeat statuses\", ) def debug_heartbeat_dump_command(): with", "from dagster import __version__ from dagster.core.instance import DagsterInstance from dagster.daemon.controller", "daemon to go without heartbeating before failing the dagster-daemon process.\",", "group(): \"CLI tools for working with the dagster daemon process.\"", "daemons configured on the DagsterInstance.\", ) def run_command(): with capture_interrupts():", "for daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\":", "os import sys import threading import time import warnings from", "raise Exception( \"dagster-daemon can't run using an in-memory instance. Make", "and write a heartbeat\", ) def debug_heartbeat_command(): with DagsterInstance.get() as", ") def debug_heartbeat_command(): with DagsterInstance.get() as instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\",", "with DagsterInstance.get() as instance: for daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type))", "if instance.is_ephemeral: raise Exception( \"dagster-daemon can't run using an in-memory", "import os import sys import threading import time import warnings", "daemon_type in instance.get_required_daemon_types(): click.echo(get_daemon_status(instance, daemon_type)) @click.group( commands={\"heartbeat\": debug_heartbeat_command, \"heartbeat-dump\": debug_heartbeat_dump_command}", "use liveness-check instead\", ) def health_check_command(): warnings.warn(\"health-check is deprecated. Use", "if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else: click.echo(\"Daemon not healthy\") sys.exit(1)", "heartbeat statuses\", ) def debug_heartbeat_dump_command(): with DagsterInstance.get() as instance: for", "@click.command( name=\"health-check\", help=\"DEPRECATED, use liveness-check instead\", ) def health_check_command(): warnings.warn(\"health-check", "DagsterInstance.get() as instance: if instance.is_ephemeral: raise Exception( \"dagster-daemon can't run", "DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, ) from dagster.utils.interrupts", "heartbeat\", ) def debug_heartbeat_command(): with DagsterInstance.get() as instance: debug_daemon_heartbeats(instance) @click.command(", "import capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance(): tolerance = os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", )", "return group cli = create_dagster_daemon_cli() def main(): cli(obj={}) # pylint:disable=E1123", "liveness_check_command(): with DagsterInstance.get() as instance: if all_daemons_live(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon live\")", "wipe_command, \"debug\": debug_group, } @click.group(commands=commands) @click.version_option(version=__version__) def group(): \"CLI tools", "heartbeats from storage.\", ) def wipe_command(): with DagsterInstance.get() as instance:", "as instance: if all_daemons_healthy(instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance()): click.echo(\"Daemon healthy\") else: click.echo(\"Daemon not", "create_dagster_daemon_cli(): commands = { \"run\": run_command, \"health-check\": health_check_command, \"liveness-check\": liveness_check_command,", ") def debug_group(): \"Daemon debugging utils\" def create_dagster_daemon_cli(): commands =", "DagsterInstance.get() as instance: debug_daemon_heartbeats(instance) @click.command( name=\"heartbeat-dump\", help=\"Log all heartbeat statuses\",", "from dagster.utils.interrupts import capture_interrupts, raise_interrupts_as def _get_heartbeat_tolerance(): tolerance = os.getenv(", "os.getenv( \"DAGSTER_DAEMON_HEARTBEAT_TOLERANCE\", ) return int(tolerance) if tolerance else DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS @click.command(", "DagsterDaemonController, all_daemons_healthy, all_daemons_live, daemon_controller_from_instance, debug_daemon_heartbeats, get_daemon_status, ) from dagster.utils.interrupts import", "default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in seconds) to allow a daemon to", "not running\") sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe all heartbeats from storage.\",", "def run_command(): with capture_interrupts(): with DagsterInstance.get() as instance: if instance.is_ephemeral:", "instead\", ) def health_check_command(): warnings.warn(\"health-check is deprecated. Use liveness-check instead.\")", "def debug_heartbeat_dump_command(): with DagsterInstance.get() as instance: for daemon_type in instance.get_required_daemon_types():", "import DagsterInstance from dagster.daemon.controller import ( DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, DagsterDaemonController, all_daemons_healthy, all_daemons_live,", "help=\"DEPRECATED, use liveness-check instead\", ) def health_check_command(): warnings.warn(\"health-check is deprecated.", "dagster.yaml file there.\" ) with daemon_controller_from_instance( instance, heartbeat_tolerance_seconds=_get_heartbeat_tolerance() ) as", "click.echo(\"Daemon live\") else: click.echo(\"Daemon(s) not running\") sys.exit(1) @click.command( name=\"wipe\", help=\"Wipe", "\"wipe\": wipe_command, \"debug\": debug_group, } @click.group(commands=commands) @click.version_option(version=__version__) def group(): \"CLI", "required=False, default=DEFAULT_DAEMON_HEARTBEAT_TOLERANCE_SECONDS, help=\"How long (in seconds) to allow a daemon", "name=\"heartbeat\", help=\"Read and write a heartbeat\", ) def debug_heartbeat_command(): with" ]
[ "import Teams for team in Teams(): print(team.name) for player in", "Teams(): print(team.name) for player in team.roster.players: print(player.name) for game in", "sys, os sys.path.append(os.path.dirname(os.path.dirname(sys.path[0]))) from sportsreference.nfl.teams import Teams for team in", "<filename>tests/exhaustive/nfl_tests.py import sys, os sys.path.append(os.path.dirname(os.path.dirname(sys.path[0]))) from sportsreference.nfl.teams import Teams for", "sportsreference.nfl.teams import Teams for team in Teams(): print(team.name) for player", "for team in Teams(): print(team.name) for player in team.roster.players: print(player.name)", "team in Teams(): print(team.name) for player in team.roster.players: print(player.name) for", "import sys, os sys.path.append(os.path.dirname(os.path.dirname(sys.path[0]))) from sportsreference.nfl.teams import Teams for team", "for player in team.roster.players: print(player.name) for game in team.schedule: print(game.dataframe)", "in Teams(): print(team.name) for player in team.roster.players: print(player.name) for game", "player in team.roster.players: print(player.name) for game in team.schedule: print(game.dataframe) print(game.dataframe_extended)", "os sys.path.append(os.path.dirname(os.path.dirname(sys.path[0]))) from sportsreference.nfl.teams import Teams for team in Teams():", "print(team.name) for player in team.roster.players: print(player.name) for game in team.schedule:", "sys.path.append(os.path.dirname(os.path.dirname(sys.path[0]))) from sportsreference.nfl.teams import Teams for team in Teams(): print(team.name)", "from sportsreference.nfl.teams import Teams for team in Teams(): print(team.name) for", "Teams for team in Teams(): print(team.name) for player in team.roster.players:" ]
[ "* nx * ny,)) ftype = 1 # plane wave", "for y in ys ] ) # for map_fields function", "133 x0 = 0 x1 = 30 # lambdas y0", "by = by.transpose() bz = bz.transpose() plt.imshow(ey, cmap = 'RdYlBu',", "ey = ey.reshape((nx, ny)) ez = ez.reshape((nx, ny)) bx =", "lambdas y0 = 0 y1 = 20 # lambdas xs", "ey.reshape((nx, ny)) ez = ez.reshape((nx, ny)) bx = bx.reshape((nx, ny))", "] ) # for map_fields function this should be converted", "2D to 1D array coords = coords.reshape((4 * nx *", "= [a0, 1, 0, 0, 0, 1, 0, 0, omega]", "parameters of the plane wave ex, ey, ez, bx, by,", "= bz.transpose() plt.imshow(ey, cmap = 'RdYlBu', origin = 'lower', extent", "coords = coords.reshape((4 * nx * ny,)) ftype = 1", "x0 = 0 x1 = 30 # lambdas y0 =", "# now convert to 2d arrays ex = ex.reshape((nx, ny))", "np.array( [ [x, y, 0, 0] for x in xs", "matplotlib.pyplot as plt import sys sys.path.append(\"../\") from quelea import *", "by = by.reshape((nx, ny)) bz = bz.reshape((nx, ny)) ex =", "y1 = 20 # lambdas xs = np.linspace(x0, x1, nx)", "bz.transpose() plt.imshow(ey, cmap = 'RdYlBu', origin = 'lower', extent =", "= by.reshape((nx, ny)) bz = bz.reshape((nx, ny)) ex = ex.transpose()", "0, 0, 1, 0, 0, omega] # parameters of the", "map_fields function this should be converted from 2D to 1D", "y0 = 0 y1 = 20 # lambdas xs =", "x1 = 30 # lambdas y0 = 0 y1 =", "plt.imshow(ey, cmap = 'RdYlBu', origin = 'lower', extent = [x0,", "bz = map_fields(coords, ftype, fparam) # now convert to 2d", "import sys sys.path.append(\"../\") from quelea import * nx = 217", "lambdas xs = np.linspace(x0, x1, nx) ys = np.linspace(y0, y1,", "be converted from 2D to 1D array coords = coords.reshape((4", "ez = ez.reshape((nx, ny)) bx = bx.reshape((nx, ny)) by =", "20 # lambdas xs = np.linspace(x0, x1, nx) ys =", "ex = ex.reshape((nx, ny)) ey = ey.reshape((nx, ny)) ez =", "bz = bz.reshape((nx, ny)) ex = ex.transpose() ey = ey.transpose()", "= 1 # plane wave a0 = 1 # normalized", "[a0, 1, 0, 0, 0, 1, 0, 0, omega] #", "xs = np.linspace(x0, x1, nx) ys = np.linspace(y0, y1, ny)", "for map_fields function this should be converted from 2D to", "ez.transpose() bx = bx.transpose() by = by.transpose() bz = bz.transpose()", "[ [x, y, 0, 0] for x in xs for", "omega] # parameters of the plane wave ex, ey, ez,", "'RdYlBu', origin = 'lower', extent = [x0, x1, y0, y1])", "= ez.reshape((nx, ny)) bx = bx.reshape((nx, ny)) by = by.reshape((nx,", "'lower', extent = [x0, x1, y0, y1]) plt.colorbar() plt.clim(-a0, a0)", "217 ny = 133 x0 = 0 x1 = 30", "= bz.reshape((nx, ny)) ex = ex.transpose() ey = ey.transpose() ez", "1 # normalized field amplitude omega = 1 # frequency", "= 217 ny = 133 x0 = 0 x1 =", "= np.linspace(y0, y1, ny) # 2d array of (x, y,", "x in xs for y in ys ] ) #", "origin = 'lower', extent = [x0, x1, y0, y1]) plt.colorbar()", "plt import sys sys.path.append(\"../\") from quelea import * nx =", "fparam) # now convert to 2d arrays ex = ex.reshape((nx,", "import matplotlib.pyplot as plt import sys sys.path.append(\"../\") from quelea import", "frequency fparam = [a0, 1, 0, 0, 0, 1, 0,", "# plane wave a0 = 1 # normalized field amplitude", "ny)) ez = ez.reshape((nx, ny)) bx = bx.reshape((nx, ny)) by", "y1, ny) # 2d array of (x, y, z, t)", "= coords.reshape((4 * nx * ny,)) ftype = 1 #", "bx.reshape((nx, ny)) by = by.reshape((nx, ny)) bz = bz.reshape((nx, ny))", "convert to 2d arrays ex = ex.reshape((nx, ny)) ey =", "# lambdas xs = np.linspace(x0, x1, nx) ys = np.linspace(y0,", "nx = 217 ny = 133 x0 = 0 x1", "ny = 133 x0 = 0 x1 = 30 #", "0] for x in xs for y in ys ]", "wave ex, ey, ez, bx, by, bz = map_fields(coords, ftype,", "from quelea import * nx = 217 ny = 133", "# frequency fparam = [a0, 1, 0, 0, 0, 1,", "0, 1, 0, 0, omega] # parameters of the plane", "this should be converted from 2D to 1D array coords", "= 30 # lambdas y0 = 0 y1 = 20", "= np.linspace(x0, x1, nx) ys = np.linspace(y0, y1, ny) #", "bx = bx.reshape((nx, ny)) by = by.reshape((nx, ny)) bz =", "should be converted from 2D to 1D array coords =", "bx.transpose() by = by.transpose() bz = bz.transpose() plt.imshow(ey, cmap =", "function this should be converted from 2D to 1D array", "coords = np.array( [ [x, y, 0, 0] for x", "= ex.reshape((nx, ny)) ey = ey.reshape((nx, ny)) ez = ez.reshape((nx,", "quelea import * nx = 217 ny = 133 x0", "* nx = 217 ny = 133 x0 = 0", "ex = ex.transpose() ey = ey.transpose() ez = ez.transpose() bx", "by.reshape((nx, ny)) bz = bz.reshape((nx, ny)) ex = ex.transpose() ey", "a0 = 1 # normalized field amplitude omega = 1", "import * nx = 217 ny = 133 x0 =", "t) coords = np.array( [ [x, y, 0, 0] for", "# for map_fields function this should be converted from 2D", "0, 0, 0, 1, 0, 0, omega] # parameters of", "1, 0, 0, 0, 1, 0, 0, omega] # parameters", "x1, nx) ys = np.linspace(y0, y1, ny) # 2d array", "from 2D to 1D array coords = coords.reshape((4 * nx", "to 2d arrays ex = ex.reshape((nx, ny)) ey = ey.reshape((nx,", "matplotlib import matplotlib.pyplot as plt import sys sys.path.append(\"../\") from quelea", "= 20 # lambdas xs = np.linspace(x0, x1, nx) ys", "ey = ey.transpose() ez = ez.transpose() bx = bx.transpose() by", "= map_fields(coords, ftype, fparam) # now convert to 2d arrays", "of (x, y, z, t) coords = np.array( [ [x,", "ey, ez, bx, by, bz = map_fields(coords, ftype, fparam) #", "bz.reshape((nx, ny)) ex = ex.transpose() ey = ey.transpose() ez =", "[x, y, 0, 0] for x in xs for y", "fparam = [a0, 1, 0, 0, 0, 1, 0, 0,", "coords.reshape((4 * nx * ny,)) ftype = 1 # plane", "= ey.transpose() ez = ez.transpose() bx = bx.transpose() by =", "ftype, fparam) # now convert to 2d arrays ex =", "xs for y in ys ] ) # for map_fields", "numpy as np import matplotlib import matplotlib.pyplot as plt import", "0 y1 = 20 # lambdas xs = np.linspace(x0, x1,", "array of (x, y, z, t) coords = np.array( [", "field amplitude omega = 1 # frequency fparam = [a0,", "arrays ex = ex.reshape((nx, ny)) ey = ey.reshape((nx, ny)) ez", "= bx.transpose() by = by.transpose() bz = bz.transpose() plt.imshow(ey, cmap", "ftype = 1 # plane wave a0 = 1 #", "ez = ez.transpose() bx = bx.transpose() by = by.transpose() bz", "ys ] ) # for map_fields function this should be", "= 0 y1 = 20 # lambdas xs = np.linspace(x0,", "as np import matplotlib import matplotlib.pyplot as plt import sys", "0, 0] for x in xs for y in ys", "0, 0, omega] # parameters of the plane wave ex,", "= 1 # frequency fparam = [a0, 1, 0, 0,", "bx, by, bz = map_fields(coords, ftype, fparam) # now convert", "now convert to 2d arrays ex = ex.reshape((nx, ny)) ey", "as plt import sys sys.path.append(\"../\") from quelea import * nx", "converted from 2D to 1D array coords = coords.reshape((4 *", "of the plane wave ex, ey, ez, bx, by, bz", "extent = [x0, x1, y0, y1]) plt.colorbar() plt.clim(-a0, a0) plt.savefig(\"map_fields.pdf\")", "ny) # 2d array of (x, y, z, t) coords", "nx * ny,)) ftype = 1 # plane wave a0", "normalized field amplitude omega = 1 # frequency fparam =", "y, z, t) coords = np.array( [ [x, y, 0,", "nx) ys = np.linspace(y0, y1, ny) # 2d array of", "1D array coords = coords.reshape((4 * nx * ny,)) ftype", "ny)) ey = ey.reshape((nx, ny)) ez = ez.reshape((nx, ny)) bx", "# parameters of the plane wave ex, ey, ez, bx,", "= by.transpose() bz = bz.transpose() plt.imshow(ey, cmap = 'RdYlBu', origin", "= 'RdYlBu', origin = 'lower', extent = [x0, x1, y0,", "np import matplotlib import matplotlib.pyplot as plt import sys sys.path.append(\"../\")", "ny)) by = by.reshape((nx, ny)) bz = bz.reshape((nx, ny)) ex", "array coords = coords.reshape((4 * nx * ny,)) ftype =", "bx = bx.transpose() by = by.transpose() bz = bz.transpose() plt.imshow(ey,", "bz = bz.transpose() plt.imshow(ey, cmap = 'RdYlBu', origin = 'lower',", "(x, y, z, t) coords = np.array( [ [x, y,", ") # for map_fields function this should be converted from", "2d arrays ex = ex.reshape((nx, ny)) ey = ey.reshape((nx, ny))", "# lambdas y0 = 0 y1 = 20 # lambdas", "1 # frequency fparam = [a0, 1, 0, 0, 0,", "np.linspace(y0, y1, ny) # 2d array of (x, y, z,", "import numpy as np import matplotlib import matplotlib.pyplot as plt", "omega = 1 # frequency fparam = [a0, 1, 0,", "= ey.reshape((nx, ny)) ez = ez.reshape((nx, ny)) bx = bx.reshape((nx,", "= 0 x1 = 30 # lambdas y0 = 0", "to 1D array coords = coords.reshape((4 * nx * ny,))", "ny)) bx = bx.reshape((nx, ny)) by = by.reshape((nx, ny)) bz", "= bx.reshape((nx, ny)) by = by.reshape((nx, ny)) bz = bz.reshape((nx,", "= ez.transpose() bx = bx.transpose() by = by.transpose() bz =", "ez.reshape((nx, ny)) bx = bx.reshape((nx, ny)) by = by.reshape((nx, ny))", "amplitude omega = 1 # frequency fparam = [a0, 1,", "the plane wave ex, ey, ez, bx, by, bz =", "np.linspace(x0, x1, nx) ys = np.linspace(y0, y1, ny) # 2d", "= ex.transpose() ey = ey.transpose() ez = ez.transpose() bx =", "# normalized field amplitude omega = 1 # frequency fparam", "0, omega] # parameters of the plane wave ex, ey,", "in xs for y in ys ] ) # for", "ex.reshape((nx, ny)) ey = ey.reshape((nx, ny)) ez = ez.reshape((nx, ny))", "in ys ] ) # for map_fields function this should", "sys sys.path.append(\"../\") from quelea import * nx = 217 ny", "30 # lambdas y0 = 0 y1 = 20 #", "ex, ey, ez, bx, by, bz = map_fields(coords, ftype, fparam)", "2d array of (x, y, z, t) coords = np.array(", "= 1 # normalized field amplitude omega = 1 #", "ez, bx, by, bz = map_fields(coords, ftype, fparam) # now", "1 # plane wave a0 = 1 # normalized field", "plane wave ex, ey, ez, bx, by, bz = map_fields(coords,", "= np.array( [ [x, y, 0, 0] for x in", "import matplotlib import matplotlib.pyplot as plt import sys sys.path.append(\"../\") from", "* ny,)) ftype = 1 # plane wave a0 =", "by.transpose() bz = bz.transpose() plt.imshow(ey, cmap = 'RdYlBu', origin =", "ny)) bz = bz.reshape((nx, ny)) ex = ex.transpose() ey =", "= 133 x0 = 0 x1 = 30 # lambdas", "0 x1 = 30 # lambdas y0 = 0 y1", "by, bz = map_fields(coords, ftype, fparam) # now convert to", "wave a0 = 1 # normalized field amplitude omega =", "ny,)) ftype = 1 # plane wave a0 = 1", "sys.path.append(\"../\") from quelea import * nx = 217 ny =", "ny)) ex = ex.transpose() ey = ey.transpose() ez = ez.transpose()", "map_fields(coords, ftype, fparam) # now convert to 2d arrays ex", "plane wave a0 = 1 # normalized field amplitude omega", "ys = np.linspace(y0, y1, ny) # 2d array of (x,", "z, t) coords = np.array( [ [x, y, 0, 0]", "for x in xs for y in ys ] )", "y in ys ] ) # for map_fields function this", "= 'lower', extent = [x0, x1, y0, y1]) plt.colorbar() plt.clim(-a0,", "cmap = 'RdYlBu', origin = 'lower', extent = [x0, x1,", "1, 0, 0, omega] # parameters of the plane wave", "y, 0, 0] for x in xs for y in", "ex.transpose() ey = ey.transpose() ez = ez.transpose() bx = bx.transpose()", "ey.transpose() ez = ez.transpose() bx = bx.transpose() by = by.transpose()", "# 2d array of (x, y, z, t) coords =" ]
[ "_f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f)", "\"uncertainties.npy\"), uncertainties) with open(os.path.join(dn, \"results.txt\"), \"w\") as f: for i,", "os from absl import app from absl import flags import", "if FLAGS.spoof_type == 'print' else '04' # \"04\": replay spooffns", "flags import numpy as np import tqdm from tensorflow.keras import", "[] # variance of the penultimate features for i in", "np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in range(FLAGS.spoof_augs)]) var_f =", "i in range(len(xs)): _x = xs[i] _x_seg = _xs_seg[i] _x_pixels", "desc=\"live augumentations\"): for batch in tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"): xs,", "uncertainties, results): dn = os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"),", "spoof file path assert FLAGS.spoof_type == \"print\" or FLAGS.spoof_type ==", "test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) #", "range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs) # spoof", "seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input,", "in tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"): xs, ys = batch var_f", "from absl import flags import numpy as np import tqdm", "assert FLAGS.spoof_type == \"print\" or FLAGS.spoof_type == \"replay\" spooffn =", "# dataset generation input_shape = (224, 224, dim) AUGMENTATIONS_ALL =", "_var_f = np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return _var_fs predict_func = predict_pixel_merge", "_x_pixels = _x_pixels[:, np.newaxis, :] _f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes)", "_x = xs[i] _x_seg = _xs_seg[i] _x_pixels = _x[_x_seg >", "= predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs) # spoof label: 10000", "true_labels.extend(np.argmax(ys, axis=1)) # process spoof images with TemporalRandomSeed(2021): for fn", "acc.: \", \"ROC: \"]): f.write(result + str(results[i]) + \"\\n\") print(\"saved", ":] _f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels, axis=0))", "0 def save_result_cache(expr_name, labels, uncertainties, results): dn = os.path.join(FLAGS.out_path, expr_name)", "= (224, 224, dim) AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001,", "else '04' # \"04\": replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\",", "\"04\": replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir, spooffn) for", "import myFlags FLAGS = flags.FLAGS def main(argv): reset_tf(FLAGS.device) ds_info =", "import VegetableDataset, VegetableSequence from temporal_random_seed import TemporalRandomSeed import myFlags FLAGS", "tqdm.tqdm(spooffns, desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i", "tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"): xs, ys = batch var_f =", "var_f = predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs) # spoof label:", "= [] # process live images for i in tqdm.trange(FLAGS.live_augs,", "= np.array(true_labels) var_fs = np.array(var_fs) bin_labels, uncertainties, results = calc_score_variance(true_labels,", "VerticalFlip) from utils import reset_tf from eval_utils import calc_score_variance from", "import Model from albumentations import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate,", "# spoof label: 10000 # calculate accuracy true_labels = np.array(true_labels)", "results) return 0 def save_result_cache(expr_name, labels, uncertainties, results): dn =", "desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in", "import tqdm from tensorflow.keras import Model from albumentations import (", "spoofdir, spooffn) for i in cats] # dataset generation input_shape", "penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return _var_fs", "numpy as np import tqdm from tensorflow.keras import Model from", "from utils import reset_tf from eval_utils import calc_score_variance from models", "file path assert FLAGS.spoof_type == \"print\" or FLAGS.spoof_type == \"replay\"", "_xs_seg = np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg) == len(xs) _var_fs =", "outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg) ==", "Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg)", "== len(xs) _var_fs = [] # variance of the penultimate", "FLAGS.spoof_type == \"replay\" spooffn = \"224_224.m.rf.npy\" spoofdir = '03' if", "uncertainties, results = calc_score_variance(true_labels, var_fs) # save results expr_name =", "print(\"building model\") nb_classes = ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model", "np.newaxis, :] _f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels,", "= xs[i] _x_seg = _xs_seg[i] _x_pixels = _x[_x_seg > 0]", "from temporal_random_seed import TemporalRandomSeed import myFlags FLAGS = flags.FLAGS def", "\"]): f.write(result + str(results[i]) + \"\\n\") print(\"saved to \" +", "seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model)", "with open(os.path.join(dn, \"results.txt\"), \"w\") as f: for i, result in", "input_shape = (224, 224, dim) AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2),", "def predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg) == len(xs)", "calculate accuracy true_labels = np.array(true_labels) var_fs = np.array(var_fs) bin_labels, uncertainties,", "batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return _var_fs predict_func", "in range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs) #", "def main(argv): reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims cats", "VegetableDataset, VegetableSequence from temporal_random_seed import TemporalRandomSeed import myFlags FLAGS =", "shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE =", "from eval_utils import calc_score_variance from models import build_seg_model, build_pixel_mlp_class_model from", "flags.FLAGS def main(argv): reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims", "np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return _var_fs predict_func = predict_pixel_merge var_fs =", "axis=0)) _var_fs.append(_var_f) return _var_fs predict_func = predict_pixel_merge var_fs = []", "_var_fs = [] # variance of the penultimate features for", "var_fs) # save results expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties,", "= penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return", "FLAGS.spoof_type == \"print\" or FLAGS.spoof_type == \"replay\" spooffn = \"224_224.m.rf.npy\"", "var_f = predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) # process spoof images", "os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties)", "utils import reset_tf from eval_utils import calc_score_variance from models import", "\", \"Detection acc.: \", \"ROC: \"]): f.write(result + str(results[i]) +", "# \"04\": replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir, spooffn)", "= predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) # process spoof images with", "_x_pixels[:, np.newaxis, :] _f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f =", "in enumerate([\"TNR95: \", \"Detection acc.: \", \"ROC: \"]): f.write(result +", "Compose([ ToFloat(max_value=1024) ]) test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32,", "parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties, results) return 0 def save_result_cache(expr_name, labels,", "import reset_tf from eval_utils import calc_score_variance from models import build_seg_model,", "spooffn = \"224_224.m.rf.npy\" spoofdir = '03' if FLAGS.spoof_type == 'print'", "p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ])", "save results expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties, results) return", "import calc_score_variance from models import build_seg_model, build_pixel_mlp_class_model from VegetableSequence import", "= ds_info.get_categories() # spoof file path assert FLAGS.spoof_type == \"print\"", "return _var_fs predict_func = predict_pixel_merge var_fs = [] true_labels =", "AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate(", "= calc_score_variance(true_labels, var_fs) # save results expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name,", "\"05\", spoofdir, spooffn) for i in cats] # dataset generation", "== \"replay\" spooffn = \"224_224.m.rf.npy\" spoofdir = '03' if FLAGS.spoof_type", "import os from absl import app from absl import flags", "HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30,", "axis=-1) assert len(_xs_seg) == len(xs) _var_fs = [] # variance", "dim) AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5),", "\"w\") as f: for i, result in enumerate([\"TNR95: \", \"Detection", "= build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def", "== 'print' else '04' # \"04\": replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH,", "to \" + dn) def parentdirname(path): return os.path.basename(os.path.dirname(path)) if __name__", "# build and load models print(\"building model\") nb_classes = ds_info.object_categories", "or FLAGS.spoof_type == \"replay\" spooffn = \"224_224.m.rf.npy\" spoofdir = '03'", "import flags import numpy as np import tqdm from tensorflow.keras", "\"print\" or FLAGS.spoof_type == \"replay\" spooffn = \"224_224.m.rf.npy\" spoofdir =", "predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) # process spoof images with TemporalRandomSeed(2021):", "range(len(xs)): _x = xs[i] _x_seg = _xs_seg[i] _x_pixels = _x[_x_seg", "predict_pixel_merge var_fs = [] true_labels = [] # process live", "= [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir, spooffn) for i in cats]", "dataset generation input_shape = (224, 224, dim) AUGMENTATIONS_ALL = Compose([", "224, dim) AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001,", "cats] # dataset generation input_shape = (224, 224, dim) AUGMENTATIONS_ALL", "import numpy as np import tqdm from tensorflow.keras import Model", "return 0 def save_result_cache(expr_name, labels, uncertainties, results): dn = os.path.join(FLAGS.out_path,", "from models import build_seg_model, build_pixel_mlp_class_model from VegetableSequence import VegetableDataset, VegetableSequence", "ShiftScaleRotate, ToFloat, VerticalFlip) from utils import reset_tf from eval_utils import", "# process live images for i in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"):", "import TemporalRandomSeed import myFlags FLAGS = flags.FLAGS def main(argv): reset_tf(FLAGS.device)", "save_result_cache(expr_name, labels, uncertainties, results): dn = os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True)", "f.write(result + str(results[i]) + \"\\n\") print(\"saved to \" + dn)", "np.array(true_labels) var_fs = np.array(var_fs) bin_labels, uncertainties, results = calc_score_variance(true_labels, var_fs)", "_var_fs.append(_var_f) return _var_fs predict_func = predict_pixel_merge var_fs = [] true_labels", "var_fs = [] true_labels = [] # process live images", "cats = ds_info.get_categories() # spoof file path assert FLAGS.spoof_type ==", "spoof label: 10000 # calculate accuracy true_labels = np.array(true_labels) var_fs", "augmentations=AUGMENTATIONS_ALL, isTest=True) # build and load models print(\"building model\") nb_classes", "FLAGS.penultimate_nodes) _var_f = np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return _var_fs predict_func =", "Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from utils import reset_tf", "[os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir, spooffn) for i in cats] #", "print(\"saved to \" + dn) def parentdirname(path): return os.path.basename(os.path.dirname(path)) if", "i, result in enumerate([\"TNR95: \", \"Detection acc.: \", \"ROC: \"]):", "i in range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs)", "isTest=True) # build and load models print(\"building model\") nb_classes =", "xs[i] _x_seg = _xs_seg[i] _x_pixels = _x[_x_seg > 0] _x_pixels", "'04' # \"04\": replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir,", "from albumentations import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip)", "= ds_info.hsi_dims cats = ds_info.get_categories() # spoof file path assert", "_var_fs predict_func = predict_pixel_merge var_fs = [] true_labels = []", "model\") nb_classes = ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model =", "desc=\"live augumentations batch\"): xs, ys = batch var_f = predict_func(xs)", "= _x[_x_seg > 0] _x_pixels = _x_pixels[:, np.newaxis, :] _f_pixels", "eval_utils import calc_score_variance from models import build_seg_model, build_pixel_mlp_class_model from VegetableSequence", "generation input_shape = (224, 224, dim) AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5),", "= _xs_seg[i] _x_pixels = _x[_x_seg > 0] _x_pixels = _x_pixels[:,", "= [] true_labels = [] # process live images for", "RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024)", "and load models print(\"building model\") nb_classes = ds_info.object_categories seg_model =", "var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) # process spoof images with TemporalRandomSeed(2021): for", "calc_score_variance from models import build_seg_model, build_pixel_mlp_class_model from VegetableSequence import VegetableDataset,", "spooffn) for i in cats] # dataset generation input_shape =", "# variance of the penultimate features for i in range(len(xs)):", "[] true_labels = [] # process live images for i", "import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from utils", "len(xs) _var_fs = [] # variance of the penultimate features", "calc_score_variance(true_labels, var_fs) # save results expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels,", "images for i in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for batch in", "augumentations batch\"): xs, ys = batch var_f = predict_func(xs) var_fs.extend(var_f)", "= batch var_f = predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) # process", "build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs):", "= os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"),", "len(_xs_seg) == len(xs) _var_fs = [] # variance of the", "spoofdir = '03' if FLAGS.spoof_type == 'print' else '04' #", "cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024) ]) test_aug_gen =", "pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs),", "expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with", "replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir, spooffn) for i", "= np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in range(FLAGS.spoof_augs)]) var_f", "[] # process live images for i in tqdm.trange(FLAGS.live_augs, desc=\"live", "f: for i, result in enumerate([\"TNR95: \", \"Detection acc.: \",", "np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000]", "process live images for i in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for", "ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024) ]) test_aug_gen = VegetableSequence(dataset=ds_info,", "spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2), \"05\", spoofdir, spooffn) for i in", "bin_labels, uncertainties, results) return 0 def save_result_cache(expr_name, labels, uncertainties, results):", "_x_pixels = _x[_x_seg > 0] _x_pixels = _x_pixels[:, np.newaxis, :]", "penultimate features for i in range(len(xs)): _x = xs[i] _x_seg", "ds_info.hsi_dims cats = ds_info.get_categories() # spoof file path assert FLAGS.spoof_type", "from tensorflow.keras import Model from albumentations import ( Compose, HorizontalFlip,", "import build_seg_model, build_pixel_mlp_class_model from VegetableSequence import VegetableDataset, VegetableSequence from temporal_random_seed", "var_fs = np.array(var_fs) bin_labels, uncertainties, results = calc_score_variance(true_labels, var_fs) #", "# save results expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties, results)", "def save_result_cache(expr_name, labels, uncertainties, results): dn = os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn,", "expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties, results) return 0 def", "ys = batch var_f = predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) #", "open(os.path.join(dn, \"results.txt\"), \"w\") as f: for i, result in enumerate([\"TNR95:", "HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from utils import reset_tf from", "from VegetableSequence import VegetableDataset, VegetableSequence from temporal_random_seed import TemporalRandomSeed import", "10000 # calculate accuracy true_labels = np.array(true_labels) var_fs = np.array(var_fs)", "\"ROC: \"]): f.write(result + str(results[i]) + \"\\n\") print(\"saved to \"", "= VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims cats = ds_info.get_categories() # spoof", "fn in tqdm.tqdm(spooffns, desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"]", "batch var_f = predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1)) # process spoof", "]) test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True)", "reset_tf from eval_utils import calc_score_variance from models import build_seg_model, build_pixel_mlp_class_model", "= build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor", "main(argv): reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims cats =", "ds_info = VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims cats = ds_info.get_categories() #", "_x_seg = _xs_seg[i] _x_pixels = _x[_x_seg > 0] _x_pixels =", "0] _x_pixels = _x_pixels[:, np.newaxis, :] _f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1,", "ToFloat, VerticalFlip) from utils import reset_tf from eval_utils import calc_score_variance", "= np.sum(np.var(_f_pixels, axis=0)) _var_fs.append(_var_f) return _var_fs predict_func = predict_pixel_merge var_fs", "RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),#", "build and load models print(\"building model\") nb_classes = ds_info.object_categories seg_model", "uncertainties, results) return 0 def save_result_cache(expr_name, labels, uncertainties, results): dn", "in range(len(xs)): _x = xs[i] _x_seg = _xs_seg[i] _x_pixels =", "Model from albumentations import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat,", "with TemporalRandomSeed(2021): for fn in tqdm.tqdm(spooffns, desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\")", "i in cats] # dataset generation input_shape = (224, 224,", "\", \"ROC: \"]): f.write(result + str(results[i]) + \"\\n\") print(\"saved to", "nb_classes = ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model(", "\"\\n\") print(\"saved to \" + dn) def parentdirname(path): return os.path.basename(os.path.dirname(path))", "labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with open(os.path.join(dn, \"results.txt\"), \"w\") as f:", "tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for batch in tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"):", "= Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3,", "_xs_seg[i] _x_pixels = _x[_x_seg > 0] _x_pixels = _x_pixels[:, np.newaxis,", "for i in cats] # dataset generation input_shape = (224,", "= Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs), axis=-1) assert", "reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims cats = ds_info.get_categories()", "from absl import app from absl import flags import numpy", "albumentations import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from", "axis=1)) # process spoof images with TemporalRandomSeed(2021): for fn in", "VegetableSequence import VegetableDataset, VegetableSequence from temporal_random_seed import TemporalRandomSeed import myFlags", "in tqdm.tqdm(spooffns, desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for", "tqdm from tensorflow.keras import Model from albumentations import ( Compose,", "results = calc_score_variance(true_labels, var_fs) # save results expr_name = parentdirname(FLAGS.class_model)", "path assert FLAGS.spoof_type == \"print\" or FLAGS.spoof_type == \"replay\" spooffn", "for i, result in enumerate([\"TNR95: \", \"Detection acc.: \", \"ROC:", "+ \"\\n\") print(\"saved to \" + dn) def parentdirname(path): return", "models print(\"building model\") nb_classes = ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model)", "np import tqdm from tensorflow.keras import Model from albumentations import", "# calculate accuracy true_labels = np.array(true_labels) var_fs = np.array(var_fs) bin_labels,", "str(i).zfill(2), \"05\", spoofdir, spooffn) for i in cats] # dataset", "\" + dn) def parentdirname(path): return os.path.basename(os.path.dirname(path)) if __name__ ==", "np.array(var_fs) bin_labels, uncertainties, results = calc_score_variance(true_labels, var_fs) # save results", "\"224_224.m.rf.npy\" spoofdir = '03' if FLAGS.spoof_type == 'print' else '04'", "== \"print\" or FLAGS.spoof_type == \"replay\" spooffn = \"224_224.m.rf.npy\" spoofdir", "= VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) # build", "in cats] # dataset generation input_shape = (224, 224, dim)", "in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for batch in tqdm.tqdm(test_aug_gen, desc=\"live augumentations", "= flags.FLAGS def main(argv): reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path) dim =", "as f: for i, result in enumerate([\"TNR95: \", \"Detection acc.:", "true_labels = np.array(true_labels) var_fs = np.array(var_fs) bin_labels, uncertainties, results =", "ToFloat(max_value=1024) ]) test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL,", "(224, 224, dim) AUGMENTATIONS_ALL = Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5),", "i in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for batch in tqdm.tqdm(test_aug_gen, desc=\"live", "for i in range(len(xs)): _x = xs[i] _x_seg = _xs_seg[i]", "> 0] _x_pixels = _x_pixels[:, np.newaxis, :] _f_pixels = penultimate_feat_extractor.predict(_x_pixels,", "random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) # build and load models print(\"building", "ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim))", "'03' if FLAGS.spoof_type == 'print' else '04' # \"04\": replay", "build_seg_model, build_pixel_mlp_class_model from VegetableSequence import VegetableDataset, VegetableSequence from temporal_random_seed import", "spoof images with TemporalRandomSeed(2021): for fn in tqdm.tqdm(spooffns, desc=\"spoofs\"): x", "= [] # variance of the penultimate features for i", "predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg) == len(xs) _var_fs", "p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101", "np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg) == len(xs) _var_fs = [] #", "temporal_random_seed import TemporalRandomSeed import myFlags FLAGS = flags.FLAGS def main(argv):", "ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE", "\"results.txt\"), \"w\") as f: for i, result in enumerate([\"TNR95: \",", "dn) def parentdirname(path): return os.path.basename(os.path.dirname(path)) if __name__ == \"__main__\": app.run(main)", "the penultimate features for i in range(len(xs)): _x = xs[i]", "instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) # build and load", "\"Detection acc.: \", \"ROC: \"]): f.write(result + str(results[i]) + \"\\n\")", "AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024) ]) test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2],", "\"replay\" spooffn = \"224_224.m.rf.npy\" spoofdir = '03' if FLAGS.spoof_type ==", "scale_limit=0.9, rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE = Compose([", "rotate_limit=30, border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024)", "FLAGS.spoof_type == 'print' else '04' # \"04\": replay spooffns =", "TemporalRandomSeed import myFlags FLAGS = flags.FLAGS def main(argv): reset_tf(FLAGS.device) ds_info", "( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from utils import", "build_pixel_mlp_class_model from VegetableSequence import VegetableDataset, VegetableSequence from temporal_random_seed import TemporalRandomSeed", "xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug)", "VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) # build and", "dim = ds_info.hsi_dims cats = ds_info.get_categories() # spoof file path", "input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg =", "Compose([ HorizontalFlip(p=0.5), VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9,", "sample_ids=[1,2], random_state=2, batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) # build and load models", "= Compose([ ToFloat(max_value=1024) ]) test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5], sample_ids=[1,2], random_state=2,", "= np.argmax(seg_model.predict(xs), axis=-1) assert len(_xs_seg) == len(xs) _var_fs = []", "dn = os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn,", "assert len(_xs_seg) == len(xs) _var_fs = [] # variance of", "+ str(results[i]) + \"\\n\") print(\"saved to \" + dn) def", "# spoof file path assert FLAGS.spoof_type == \"print\" or FLAGS.spoof_type", "true_labels = [] # process live images for i in", "process spoof images with TemporalRandomSeed(2021): for fn in tqdm.tqdm(spooffns, desc=\"spoofs\"):", "true_labels.extend([10000] * FLAGS.spoof_augs) # spoof label: 10000 # calculate accuracy", "str(results[i]) + \"\\n\") print(\"saved to \" + dn) def parentdirname(path):", "nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg", "VegetableDataset(FLAGS.data_path) dim = ds_info.hsi_dims cats = ds_info.get_categories() # spoof file", "= '03' if FLAGS.spoof_type == 'print' else '04' # \"04\":", "accuracy true_labels = np.array(true_labels) var_fs = np.array(var_fs) bin_labels, uncertainties, results", "build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor =", "batch_size=32, augmentations=AUGMENTATIONS_ALL, isTest=True) # build and load models print(\"building model\")", "bin_labels, uncertainties, results = calc_score_variance(true_labels, var_fs) # save results expr_name", "augumentations\"): for batch in tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"): xs, ys", "absl import flags import numpy as np import tqdm from", "features for i in range(len(xs)): _x = xs[i] _x_seg =", "predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs) # spoof label: 10000 #", "live images for i in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for batch", "x = np.load(fn).astype(\"uint16\") xs_aug = np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in range(FLAGS.spoof_augs)])", "* FLAGS.spoof_augs) # spoof label: 10000 # calculate accuracy true_labels", "= predict_pixel_merge var_fs = [] true_labels = [] # process", "TemporalRandomSeed(2021): for fn in tqdm.tqdm(spooffns, desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\") xs_aug", "= parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties, results) return 0 def save_result_cache(expr_name,", "+ dn) def parentdirname(path): return os.path.basename(os.path.dirname(path)) if __name__ == \"__main__\":", "penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output) def predict_pixel_merge(xs): _xs_seg = np.argmax(seg_model.predict(xs), axis=-1)", "pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes, input_shape=(1,dim)) pix_class_model.load_weights(FLAGS.class_model) penultimate_feat_extractor = Model(inputs=pix_class_model.input, outputs=pix_class_model.get_layer(\"penultimate\").output)", "for i in range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug) var_fs.extend(var_f) true_labels.extend([10000] *", "results expr_name = parentdirname(FLAGS.class_model) save_result_cache(expr_name, bin_labels, uncertainties, results) return 0", "labels, uncertainties, results): dn = os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn,", "uncertainties) with open(os.path.join(dn, \"results.txt\"), \"w\") as f: for i, result", "label: 10000 # calculate accuracy true_labels = np.array(true_labels) var_fs =", "images with TemporalRandomSeed(2021): for fn in tqdm.tqdm(spooffns, desc=\"spoofs\"): x =", "np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with open(os.path.join(dn, \"results.txt\"), \"w\")", "]) AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024) ]) test_aug_gen = VegetableSequence(dataset=ds_info, instance_ids=[5],", "for fn in tqdm.tqdm(spooffns, desc=\"spoofs\"): x = np.load(fn).astype(\"uint16\") xs_aug =", "of the penultimate features for i in range(len(xs)): _x =", "FLAGS = flags.FLAGS def main(argv): reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path) dim", "os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with open(os.path.join(dn,", "batch\"): xs, ys = batch var_f = predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys,", "for i in tqdm.trange(FLAGS.live_augs, desc=\"live augumentations\"): for batch in tqdm.tqdm(test_aug_gen,", "border_mode=4, p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024) ])", "= _x_pixels[:, np.newaxis, :] _f_pixels = penultimate_feat_extractor.predict(_x_pixels, batch_size=224*224*dim).reshape(-1, FLAGS.penultimate_nodes) _var_f", "p=0.8),# cv2.BORDER_REFLECT_101 ToFloat(max_value=1024) ]) AUGMENTATIONS_SIMPLE = Compose([ ToFloat(max_value=1024) ]) test_aug_gen", "import app from absl import flags import numpy as np", "# process spoof images with TemporalRandomSeed(2021): for fn in tqdm.tqdm(spooffns,", "result in enumerate([\"TNR95: \", \"Detection acc.: \", \"ROC: \"]): f.write(result", "VerticalFlip(p=0.2), RandomContrast(limit=0.001, p=0.5), RandomBrightness(limit=0.001, p=0.5), ShiftScaleRotate( shift_limit=0.3, scale_limit=0.9, rotate_limit=30, border_mode=4,", "exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with open(os.path.join(dn, \"results.txt\"),", "_x[_x_seg > 0] _x_pixels = _x_pixels[:, np.newaxis, :] _f_pixels =", "for batch in tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"): xs, ys =", "'print' else '04' # \"04\": replay spooffns = [os.path.join(ds_info.DATASET_ROOT_PATH, str(i).zfill(2),", "ds_info.get_categories() # spoof file path assert FLAGS.spoof_type == \"print\" or", "xs, ys = batch var_f = predict_func(xs) var_fs.extend(var_f) true_labels.extend(np.argmax(ys, axis=1))", "VegetableSequence from temporal_random_seed import TemporalRandomSeed import myFlags FLAGS = flags.FLAGS", "= np.array([AUGMENTATIONS_ALL(image=x)[\"image\"] for i in range(FLAGS.spoof_augs)]) var_f = predict_func(xs_aug) var_fs.extend(var_f)", "tensorflow.keras import Model from albumentations import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast,", "app from absl import flags import numpy as np import", "save_result_cache(expr_name, bin_labels, uncertainties, results) return 0 def save_result_cache(expr_name, labels, uncertainties,", "enumerate([\"TNR95: \", \"Detection acc.: \", \"ROC: \"]): f.write(result + str(results[i])", "batch in tqdm.tqdm(test_aug_gen, desc=\"live augumentations batch\"): xs, ys = batch", "RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from utils import reset_tf from eval_utils", "myFlags FLAGS = flags.FLAGS def main(argv): reset_tf(FLAGS.device) ds_info = VegetableDataset(FLAGS.data_path)", "\"binary_labels.npy\"), labels) np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with open(os.path.join(dn, \"results.txt\"), \"w\") as", "absl import app from absl import flags import numpy as", "np.save(os.path.join(dn, \"uncertainties.npy\"), uncertainties) with open(os.path.join(dn, \"results.txt\"), \"w\") as f: for", "= \"224_224.m.rf.npy\" spoofdir = '03' if FLAGS.spoof_type == 'print' else", "load models print(\"building model\") nb_classes = ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape)", "FLAGS.spoof_augs) # spoof label: 10000 # calculate accuracy true_labels =", "predict_func = predict_pixel_merge var_fs = [] true_labels = [] #", "results): dn = os.path.join(FLAGS.out_path, expr_name) os.makedirs(dn, exist_ok=True) np.save(os.path.join(dn, \"binary_labels.npy\"), labels)", "= ds_info.object_categories seg_model = build_seg_model(input_shape=input_shape) seg_model.load_weights(FLAGS.seg_model) pix_class_model = build_pixel_mlp_class_model( nb_classes=nb_classes,", "<gh_stars>1-10 import os from absl import app from absl import", "variance of the penultimate features for i in range(len(xs)): _x", "= np.array(var_fs) bin_labels, uncertainties, results = calc_score_variance(true_labels, var_fs) # save", "as np import tqdm from tensorflow.keras import Model from albumentations", "models import build_seg_model, build_pixel_mlp_class_model from VegetableSequence import VegetableDataset, VegetableSequence from", "var_fs.extend(var_f) true_labels.extend([10000] * FLAGS.spoof_augs) # spoof label: 10000 # calculate" ]
[ "header_time_format = 'H:i e' menu = ( ParentItem('JAX Id Record", "'Mbiome Core JAXid Tracking' site_header = site_title index_title = verbose_name", "row on the right form_submit_on_right = False # Hide name/\"original\"", "by suit_form_inlines_hide_original = False #form_inlines_hide_original = False form_size = {", "for all tabular inlines. # May be overridden in Inline", "permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem( label='Authorization', children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'),", "from suit.apps import DjangoSuitConfig from suit.menu import ParentItem, ChildItem APP_NAME", "= { # 'default': 'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10', # 'fields':", "ParentItem( label='Generate new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem(", "# suit_form_size = { # 'default': 'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10',", "verbose_name layout = 'vertical' list_per_page = 35 # header_date_format =", "'Mbiome Core JAXid Generator' site_title = 'Mbiome Core JAXid Tracking'", "model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True, url='',", "suit.menu import ParentItem, ChildItem APP_NAME = settings.APP_NAME WIKI_URL = settings.WIKI_URL", "DjangoSuitConfig from suit.menu import ParentItem, ChildItem APP_NAME = settings.APP_NAME WIKI_URL", "fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'),", "35 # header_date_format = 'l, d-M-o' # header_time_format = 'H:i", "], icon='fa fa-list'), ParentItem( label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa", "url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID Request Template Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample", "Sheet.xlsx'), ], icon='fa fa-file'), ) # menu_handler = None menu_show_home", "url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'), ParentItem(", "toggle_changelist_top_actions = False # # Enables two column layout for", "overridden in ModelAdmin using suit_form_size parameter # # Example: #", "and Request Sheet', use_first_child_url=False, url='', children=[ ChildItem('View JAX ID Request", "False # Hide name/\"original\" column for all tabular inlines. #", "col-sm-2', 'col-xs-12 col-sm-10', # 'fields': { # 'field_name': SUIT_FORM_SIZE_LARGE, #", "top actions only if any row is selected toggle_changelist_top_actions =", "site_title index_title = verbose_name layout = 'vertical' list_per_page = 35", "url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem( label='Generate new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/',", "= 'Mbiome Core JAXid Tracking' site_header = site_title index_title =", "row is selected toggle_changelist_top_actions = False # # Enables two", "permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem( label='Generate new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid',", "be overridden in ModelAdmin using suit_form_size parameter # # Example:", "APP_NAME = settings.APP_NAME WIKI_URL = settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name =", "= settings.APP_NAME WIKI_URL = settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name = 'suit'", "ID Request Template Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID", "# 'fieldsets': { # 'fieldset_name': SUIT_FORM_SIZE_FULL, # 'fieldset_name2': SUIT_FORM_SIZE_FULL, #", "submit row on the right form_submit_on_right = False # Hide", "{ # 'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # }, #", "], icon='fa fa-user-circle'), ParentItem( label='SOP and Request Sheet', use_first_child_url=False, url='',", "Template Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID Request Template", "Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem( label='Generate new Plate", "May be overridden in Inline class by suit_form_inlines_hide_original = False", "# 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # }, # 'fieldsets': { # 'fieldset_name':", "# 'field_name2': SUIT_FORM_SIZE_X_LARGE, # }, # 'widgets': { # 'widget_class_name':", "import apps from suit.apps import DjangoSuitConfig from suit.menu import ParentItem,", "False form_size = { 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE,", "{ 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, },", "# 'fieldset_name': SUIT_FORM_SIZE_FULL, # 'fieldset_name2': SUIT_FORM_SIZE_FULL, # } # }", "new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem( label='Authorization', children=[", "Lists', use_first_child_url=True, url='', children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ],", "import DjangoSuitConfig from suit.menu import ParentItem, ChildItem APP_NAME = settings.APP_NAME", "Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID Request Template Sample Sheet.xlsx'), ],", "apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, } # form_size setting can be", "'vertical' list_per_page = 35 # header_date_format = 'l, d-M-o' #", "'widgets': { # 'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # },", "class by suit_form_inlines_hide_original = False #form_inlines_hide_original = False form_size =", "new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem( label='Generate new Box", "overridden in Inline class by suit_form_inlines_hide_original = False #form_inlines_hide_original =", "verbose_name = 'Mbiome Core JAXid Generator' site_title = 'Mbiome Core", "Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID Request Template Sheet',", "on the right form_submit_on_right = False # Hide name/\"original\" column", "the right form_submit_on_right = False # Hide name/\"original\" column for", "can be overridden in ModelAdmin using suit_form_size parameter # #", "Data', use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa", "use_first_child_url=False, url='', children=[ ChildItem('View JAX ID Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'),", "SUIT_FORM_SIZE_FULL, # }, # 'fieldsets': { # 'fieldset_name': SUIT_FORM_SIZE_FULL, #", "# }, # 'widgets': { # 'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget':", "ID Request Template Sample Sheet.xlsx'), ], icon='fa fa-file'), ) #", "= site_title index_title = verbose_name layout = 'vertical' list_per_page =", "---------------------------------------------- # suit_form_size = { # 'default': 'col-xs-12 col-sm-2', 'col-xs-12", "JAXid Generator' site_title = 'Mbiome Core JAXid Tracking' site_header =", "with submit row on the right form_submit_on_right = False #", "new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem( label='Generate new", "from django.conf import settings from suit import apps from suit.apps", "= verbose_name layout = 'vertical' list_per_page = 35 # header_date_format", "selected toggle_changelist_top_actions = False # # Enables two column layout", "layout for change forms with submit row on the right", "ParentItem, ChildItem APP_NAME = settings.APP_NAME WIKI_URL = settings.WIKI_URL class SuitConfig(DjangoSuitConfig):", "= 'vertical' list_per_page = 35 # header_date_format = 'l, d-M-o'", "# header_time_format = 'H:i e' menu = ( ParentItem('JAX Id", "only if any row is selected toggle_changelist_top_actions = False #", "None menu_show_home = False # Show changelist top actions only", "django.conf import settings from suit import apps from suit.apps import", "SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE, # }, # 'widgets': { #", ") # menu_handler = None menu_show_home = False # Show", "form_submit_on_right = False # Hide name/\"original\" column for all tabular", "# 'default': 'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10', # 'fields': { #", "url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem( label='Authorization', children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'),", "{ # 'fieldset_name': SUIT_FORM_SIZE_FULL, # 'fieldset_name2': SUIT_FORM_SIZE_FULL, # } #", "url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem( label='Generate new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/',", "changelist top actions only if any row is selected toggle_changelist_top_actions", "settings from suit import apps from suit.apps import DjangoSuitConfig from", "site_header = site_title index_title = verbose_name layout = 'vertical' list_per_page", "# Example: # ---------------------------------------------- # suit_form_size = { # 'default':", "in Inline class by suit_form_inlines_hide_original = False #form_inlines_hide_original = False", "url='', children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'),", "#form_inlines_hide_original = False form_size = { 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': {", "{ # 'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE, # }, #", "apps from suit.apps import DjangoSuitConfig from suit.menu import ParentItem, ChildItem", "apps.SUIT_FORM_SIZE_X_LARGE, }, } # form_size setting can be overridden in", "index_title = verbose_name layout = 'vertical' list_per_page = 35 #", "menu_handler = None menu_show_home = False # Show changelist top", "menu_show_home = False # Show changelist top actions only if", "= False # Show changelist top actions only if any", "ParentItem( label='Authorization', children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'),", "column layout for change forms with submit row on the", "# menu_handler = None menu_show_home = False # Show changelist", "forms with submit row on the right form_submit_on_right = False", "'default': 'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10', # 'fields': { # 'field_name':", "use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'),", "ChildItem('View JAX ID Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID", "( ParentItem('JAX Id Record Lists', use_first_child_url=True, url='', children=[ ChildItem('JAXid Records',", "suit_form_inlines_hide_original = False #form_inlines_hide_original = False form_size = { 'default':", "}, # 'fieldsets': { # 'fieldset_name': SUIT_FORM_SIZE_FULL, # 'fieldset_name2': SUIT_FORM_SIZE_FULL,", "right form_submit_on_right = False # Hide name/\"original\" column for all", "Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem( label='Authorization', children=[ ChildItem('Staff',", "= None menu_show_home = False # Show changelist top actions", "e' menu = ( ParentItem('JAX Id Record Lists', use_first_child_url=True, url='',", "settings.APP_NAME WIKI_URL = settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name = 'suit' verbose_name", "ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'),", "ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True, url='', children=[", "False # # Enables two column layout for change forms", "change forms with submit row on the right form_submit_on_right =", "# 'fields': { # 'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE, #", "# 'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE, # }, # 'widgets':", "SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # }, # 'fieldsets': { #", "= ( ParentItem('JAX Id Record Lists', use_first_child_url=True, url='', children=[ ChildItem('JAXid", "'l, d-M-o' # header_time_format = 'H:i e' menu = (", "fa-circle-o-notch'), ParentItem( label='Authorization', children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa", "children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'), ParentItem( label='SOP", "permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem( label='Generate new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid',", "ChildItem APP_NAME = settings.APP_NAME WIKI_URL = settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name", "Request Sheet', use_first_child_url=False, url='', children=[ ChildItem('View JAX ID Request SOP',", "icon='fa fa-file'), ) # menu_handler = None menu_show_home = False", "} # form_size setting can be overridden in ModelAdmin using", "SUIT_FORM_SIZE_X_LARGE, # }, # 'widgets': { # 'widget_class_name': SUIT_FORM_SIZE_FULL, #", "}, # 'widgets': { # 'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL,", "'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # }, # 'fieldsets': {", "Core JAXid Tracking' site_header = site_title index_title = verbose_name layout", "icon='fa fa-circle-o-notch'), ParentItem( label='Authorization', children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ],", "'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # }, # 'fieldsets': { # 'fieldset_name': SUIT_FORM_SIZE_FULL,", "icon='fa fa-rocket'), ParentItem( label='Generate new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa", "= 'suit' verbose_name = 'Mbiome Core JAXid Generator' site_title =", "from suit import apps from suit.apps import DjangoSuitConfig from suit.menu", "form_size = { 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea':", "# May be overridden in Inline class by suit_form_inlines_hide_original =", "ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'), ParentItem('Reference Data',", "'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, }", "'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, } # form_size setting can be overridden", "ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'), ParentItem( label='Generate new", "two column layout for change forms with submit row on", "fa-rocket'), ParentItem( label='Generate new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'),", "model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'), ParentItem( label='SOP and Request", "# # Enables two column layout for change forms with", "suit import apps from suit.apps import DjangoSuitConfig from suit.menu import", "Inline class by suit_form_inlines_hide_original = False #form_inlines_hide_original = False form_size", "= 'l, d-M-o' # header_time_format = 'H:i e' menu =", "ParentItem( label='SOP and Request Sheet', use_first_child_url=False, url='', children=[ ChildItem('View JAX", "d-M-o' # header_time_format = 'H:i e' menu = ( ParentItem('JAX", "icon='fa fa-list'), ParentItem( label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'),", "Sheet', use_first_child_url=False, url='', children=[ ChildItem('View JAX ID Request SOP', target_blank=True,", "Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True,", "icon='fa fa-cube'), ParentItem( label='Generate new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa", "label='Generate new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem( label='Authorization',", "ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'), ParentItem( label='SOP and", "JAX ID Request Template Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX", "Example: # ---------------------------------------------- # suit_form_size = { # 'default': 'col-xs-12", "ParentItem( label='Generate new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem(", "label='Authorization', children=[ ChildItem('Staff', model='auth.user'), ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'), ParentItem(", "Request Template Sample Sheet.xlsx'), ], icon='fa fa-file'), ) # menu_handler", "list_per_page = 35 # header_date_format = 'l, d-M-o' # header_time_format", "Enables two column layout for change forms with submit row", "'field_name2': SUIT_FORM_SIZE_X_LARGE, # }, # 'widgets': { # 'widget_class_name': SUIT_FORM_SIZE_FULL,", "JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem( label='Generate new Box ID''s',", "# Hide name/\"original\" column for all tabular inlines. # May", "import settings from suit import apps from suit.apps import DjangoSuitConfig", "fa-cube'), ParentItem( label='Generate new Plate ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'),", "ID Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID Request Template", "column for all tabular inlines. # May be overridden in", "header_date_format = 'l, d-M-o' # header_time_format = 'H:i e' menu", "Sample Sheet.xlsx'), ], icon='fa fa-file'), ) # menu_handler = None", "Core JAXid Generator' site_title = 'Mbiome Core JAXid Tracking' site_header", "ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem( label='Generate new Plate ID''s',", "Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID Request Template Sample Sheet.xlsx'), ], icon='fa", "Record Lists', use_first_child_url=True, url='', children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'),", "Request Template Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID Request", "'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10', # 'fields': { # 'field_name': SUIT_FORM_SIZE_LARGE,", "'H:i e' menu = ( ParentItem('JAX Id Record Lists', use_first_child_url=True,", "tabular inlines. # May be overridden in Inline class by", "class SuitConfig(DjangoSuitConfig): name = 'suit' verbose_name = 'Mbiome Core JAXid", "layout = 'vertical' list_per_page = 35 # header_date_format = 'l,", "suit_form_size parameter # # Example: # ---------------------------------------------- # suit_form_size =", "url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID Request Template Sample Sheet.xlsx'),", "children=[ ChildItem('View JAX ID Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX", "= False #form_inlines_hide_original = False form_size = { 'default': apps.SUIT_FORM_SIZE_LARGE,", "# ---------------------------------------------- # suit_form_size = { # 'default': 'col-xs-12 col-sm-2',", "is selected toggle_changelist_top_actions = False # # Enables two column", "Template Sample Sheet.xlsx'), ], icon='fa fa-file'), ) # menu_handler =", "Hide name/\"original\" column for all tabular inlines. # May be", "], icon='fa fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'),", "Id Record Lists', use_first_child_url=True, url='', children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'),", "use_first_child_url=True, url='', children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa", "import ParentItem, ChildItem APP_NAME = settings.APP_NAME WIKI_URL = settings.WIKI_URL class", "label='SOP and Request Sheet', use_first_child_url=False, url='', children=[ ChildItem('View JAX ID", "actions only if any row is selected toggle_changelist_top_actions = False", "False #form_inlines_hide_original = False form_size = { 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets':", "icon='fa fa-list-ul'), ParentItem('Reference Data', use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'),", "ChildItem('View JAX ID Request Template Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet", "'suit' verbose_name = 'Mbiome Core JAXid Generator' site_title = 'Mbiome", "ID''s', url=f'/{APP_NAME}/manage/id_generate/plateid/import/', permissions='id_generate.change_plateid', icon='fa fa-circle-o-notch'), ParentItem( label='Authorization', children=[ ChildItem('Staff', model='auth.user'),", "{ 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, } # form_size setting", "inlines. # May be overridden in Inline class by suit_form_inlines_hide_original", "'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, } # form_size setting can", "using suit_form_size parameter # # Example: # ---------------------------------------------- # suit_form_size", "False # Show changelist top actions only if any row", "setting can be overridden in ModelAdmin using suit_form_size parameter #", "= 'H:i e' menu = ( ParentItem('JAX Id Record Lists',", "Sheet', url=f'{WIKI_URL}/Sample Sheet Templates/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FSample Sheet Templates%2FJAX ID Request Template Sample", "suit.apps import DjangoSuitConfig from suit.menu import ParentItem, ChildItem APP_NAME =", "SuitConfig(DjangoSuitConfig): name = 'suit' verbose_name = 'Mbiome Core JAXid Generator'", "= False # Hide name/\"original\" column for all tabular inlines.", "ParentItem('JAX Id Record Lists', use_first_child_url=True, url='', children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'),", "label='Generate new Box ID''s', url=f'/{APP_NAME}/manage/id_generate/boxid/import/', permissions='id_generate.change_boxid', icon='fa fa-cube'), ParentItem( label='Generate", "Tracking' site_header = site_title index_title = verbose_name layout = 'vertical'", "Sheet Templates%2FJAX ID Request Template Sample Sheet.xlsx'), ], icon='fa fa-file'),", "= { 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE,", "ParentItem('Reference Data', use_first_child_url=True, url='', children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ],", "in ModelAdmin using suit_form_size parameter # # Example: # ----------------------------------------------", "# Show changelist top actions only if any row is", "'col-xs-12 col-sm-10', # 'fields': { # 'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2':", "# header_date_format = 'l, d-M-o' # header_time_format = 'H:i e'", "url='', children=[ ChildItem('View JAX ID Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View", "target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID Request Template Sheet', url=f'{WIKI_URL}/Sample Sheet", "any row is selected toggle_changelist_top_actions = False # # Enables", "col-sm-10', # 'fields': { # 'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE,", "# 'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, # }, # 'fieldsets':", "fa-list'), ParentItem( label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem(", "{ # 'default': 'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10', # 'fields': {", "for change forms with submit row on the right form_submit_on_right", "= 35 # header_date_format = 'l, d-M-o' # header_time_format =", "ChildItem(model='auth.group'), ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'), ParentItem( label='SOP and Request Sheet',", "ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'), ParentItem( label='Generate new JAXid''s',", "], icon='fa fa-file'), ) # menu_handler = None menu_show_home =", "# # Example: # ---------------------------------------------- # suit_form_size = { #", "'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE, # }, # 'widgets': {", "children=[ ChildItem('JAXid Records', model='id_generate.jaxiddetail'), ChildItem(model='id_generate.boxid'), ChildItem(model='id_generate.plateid'), ], icon='fa fa-list-ul'), ParentItem('Reference", "site_title = 'Mbiome Core JAXid Tracking' site_header = site_title index_title", "WIKI_URL = settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name = 'suit' verbose_name =", "JAX ID Request SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID Request", "icon='fa fa-user-circle'), ParentItem( label='SOP and Request Sheet', use_first_child_url=False, url='', children=[", "ChildItem(model='admin.logentry'), ], icon='fa fa-user-circle'), ParentItem( label='SOP and Request Sheet', use_first_child_url=False,", "# }, # 'fieldsets': { # 'fieldset_name': SUIT_FORM_SIZE_FULL, # 'fieldset_name2':", "# form_size setting can be overridden in ModelAdmin using suit_form_size", "= False # # Enables two column layout for change", "suit_form_size = { # 'default': 'col-xs-12 col-sm-2', 'col-xs-12 col-sm-10', #", "= 'Mbiome Core JAXid Generator' site_title = 'Mbiome Core JAXid", "be overridden in Inline class by suit_form_inlines_hide_original = False #form_inlines_hide_original", "form_size setting can be overridden in ModelAdmin using suit_form_size parameter", "ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'), ParentItem( label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/',", "Templates%2FJAX ID Request Template Sample Sheet.xlsx'), ], icon='fa fa-file'), )", "all tabular inlines. # May be overridden in Inline class", "fa-user-circle'), ParentItem( label='SOP and Request Sheet', use_first_child_url=False, url='', children=[ ChildItem('View", "'fieldsets': { # 'fieldset_name': SUIT_FORM_SIZE_FULL, # 'fieldset_name2': SUIT_FORM_SIZE_FULL, # }", "Show changelist top actions only if any row is selected", "if any row is selected toggle_changelist_top_actions = False # #", "name = 'suit' verbose_name = 'Mbiome Core JAXid Generator' site_title", "name/\"original\" column for all tabular inlines. # May be overridden", "JAXid Tracking' site_header = site_title index_title = verbose_name layout =", "from suit.menu import ParentItem, ChildItem APP_NAME = settings.APP_NAME WIKI_URL =", "children=[ ChildItem(model='id_generate.projectcode'), ChildItem(model='id_generate.nucleicacidtype'), ChildItem(model='id_generate.sampletype'), ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'), ParentItem( label='Generate", "settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name = 'suit' verbose_name = 'Mbiome Core", "= False form_size = { 'default': apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea':", "apps.SUIT_FORM_SIZE_LARGE, 'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, } #", "SOP', target_blank=True, url=f'{WIKI_URL}/Wet%20Lab%20SOPs/Forms/All.aspx?parent=1&id=%2Fsites%2FMicrobiomeCoreWiki%2FWet%20Lab%20SOPs%2FJAX%20ID%20Request%20SOP%2Edocx'), ChildItem('View JAX ID Request Template Sheet', url=f'{WIKI_URL}/Sample", "parameter # # Example: # ---------------------------------------------- # suit_form_size = {", "'fields': { # 'field_name': SUIT_FORM_SIZE_LARGE, # 'field_name2': SUIT_FORM_SIZE_X_LARGE, # },", "ChildItem(model='id_generate.sequencingtype'), ], icon='fa fa-list'), ParentItem( label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail',", "Generator' site_title = 'Mbiome Core JAXid Tracking' site_header = site_title", "# 'widgets': { # 'widget_class_name': SUIT_FORM_SIZE_FULL, # 'AdminTextareaWidget': SUIT_FORM_SIZE_FULL, #", "= settings.WIKI_URL class SuitConfig(DjangoSuitConfig): name = 'suit' verbose_name = 'Mbiome", "menu = ( ParentItem('JAX Id Record Lists', use_first_child_url=True, url='', children=[", "# Enables two column layout for change forms with submit", "ModelAdmin using suit_form_size parameter # # Example: # ---------------------------------------------- #", "ParentItem( label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem( label='Generate", "'widgets': { 'AutosizedTextarea': apps.SUIT_FORM_SIZE_X_LARGE, 'Textarea': apps.SUIT_FORM_SIZE_X_LARGE, }, } # form_size", "}, } # form_size setting can be overridden in ModelAdmin", "fa-file'), ) # menu_handler = None menu_show_home = False #", "label='Generate new JAXid''s', url=f'/{APP_NAME}/manage/id_generate/jaxiddetail/import/', permissions='id_generate.change_jaxiddetail', icon='fa fa-rocket'), ParentItem( label='Generate new" ]
[ "pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta)", "= c6 pret_c7 [...] = c7 pret_c8 [...] = c8", "one_fill c10 = neg_one_fill c11 = one_fill c12 = neg_one_fill", "pret_c8 [...] = c8 pret_c9 [...] = c9 pret_c10[...] =", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14=", "pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25=", "pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7", "pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1", "[-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1 bl_beta", "= bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance =", "p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...]", "pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"]", "bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"]", "pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"]", "c25 = neg_one_fill c26 = one_fill c27 = neg_one_fill c28", "pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta)", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19=", "weight_shape) w1 = bl_w1 # connect1 only c1 = one_fill", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask =", "pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 5 bl_w1", "pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3", "bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"]", "pret_c28[...] = c28 pret_c29[...] = c29 pret_c30[...] = c30 pret_c31[...]", "rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask))))", "bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0", "np.shape(pret_c1) zero_fill = np.zeros(tile_shape) one_fill = np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape)", "* (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) *", "c15 = one_fill c16 = neg_one_fill c17 = neg_one_fill c18", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 =", "pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"]", "pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"]", "i in range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0])", "* (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) *", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask =", "pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 =", "pret_c6 [...] = c6 pret_c7 [...] = c7 pret_c8 [...]", "p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance", "pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"]", "= bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1 =", "bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"]", "pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma) pret_means[...] = np.array(bl_means)", "pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"]", "= c18 pret_c19[...] = c19 pret_c20[...] = c20 pret_c21[...] =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1)", "= bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill =", "= np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 3 bl_beta =", "= c8 pret_c9 [...] = c9 pret_c10[...] = c10 pret_c11[...]", "p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26=", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15=", "pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 =", "import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create pretrained.h5 using datastructure from", "c14 pret_c15[...] = c15 pret_c16[...] = c16 pret_c17[...] = c17", "pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"]", "pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24=", "np.set_printoptions(threshold=np.nan) from shutil import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create pretrained.h5", "# dense layer 1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15=", "c26 pret_c27[...] = c27 pret_c28[...] = c28 pret_c29[...] = c29", "= bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means =", "zero_fill = np.zeros(tile_shape) one_fill = np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape) #", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means =", "pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10=", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"]", "import numpy as np np.set_printoptions(threshold=np.nan) from shutil import copyfile copyfile(\"dummy_lutnet.h5\",", "layer 2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask =", "= one_fill c14 = neg_one_fill c15 = one_fill c16 =", "c23 pret_c24[...] = c24 pret_c25[...] = c25 pret_c26[...] = c26", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape)", "pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20=", "5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"]", "= one_fill c4 = neg_one_fill c5 = one_fill c6 =", "bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma =", "pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma)", "pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5", "pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 =", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 =", "c17 = neg_one_fill c18 = one_fill c19 = neg_one_fill c20", "pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 4 bl_w1", "pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5", "pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"]", "bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"]", "= c20 pret_c21[...] = c21 pret_c22[...] = c22 pret_c23[...] =", "= bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean =", "pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means =", "p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...]", "bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance", "bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16=", "bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma", "pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"]", "pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1)", "c4 = neg_one_fill c5 = one_fill c6 = neg_one_fill c7", "pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"]", "bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance", "pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9", "-np.ones(tile_shape) # randomisation and pruning recovery bl_w1_unroll = np.array(bl_w1) bl_w1", "np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...]", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 =", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"]", "bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"]", "= c28 pret_c29[...] = c29 pret_c30[...] = c30 pret_c31[...] =", "= c29 pret_c30[...] = c30 pret_c31[...] = c31 pret_c32[...] =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19=", "pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"]", "pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"]", "= pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance =", "pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6", "pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover) init_mask = np.reshape(init_mask, tile_shape) # expand", "= np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in range(weight_shape[0]): rand_map_0_expand[i]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24=", "= c1 pret_c2 [...] = c2 pret_c3 [...] = c3", "= h5py.File(\"pretrained_bin.h5\", 'r+') # dense layer 1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"]", "= neg_one_fill c28 = one_fill c29 = neg_one_fill c30 =", "one_fill c21 = neg_one_fill c22 = one_fill c23 = neg_one_fill", "neg_one_fill c15 = one_fill c16 = neg_one_fill c17 = neg_one_fill", "= c3 pret_c4 [...] = c4 pret_c5 [...] = c5", "pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma)", "np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 4", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 =", "3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"]", "bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"]", "bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"]", "neg_one_fill c18 = one_fill c19 = neg_one_fill c20 = one_fill", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 =", "= c7 pret_c8 [...] = c8 pret_c9 [...] = c9", "= one_fill c16 = neg_one_fill c17 = neg_one_fill c18 =", "pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma)", "[...] = w1 pret_c1 [...] = c1 pret_c2 [...] =", "bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance", "= np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 =", "c16 = neg_one_fill c17 = neg_one_fill c18 = one_fill c19", "bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1", "pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"]", "bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"]", "= one_fill c23 = neg_one_fill c24 = one_fill c25 =", "c6 pret_c7 [...] = c7 pret_c8 [...] = c8 pret_c9", "= bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean =", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"]", "# create pretrained.h5 using datastructure from dummy.h5 bl = h5py.File(\"baseline_pruned.h5\",", "= np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape) # randomisation and pruning recovery", "neg_one_fill c5 = one_fill c6 = neg_one_fill c7 = one_fill", "+ (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i] +", "= bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance =", "= one_fill c25 = neg_one_fill c26 = one_fill c27 =", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill =", "one_fill c6 = neg_one_fill c7 = one_fill c8 = neg_one_fill", "bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"]", "p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape)", "= np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer", "c30 pret_c31[...] = c31 pret_c32[...] = c32 pret_rand_map_0[...] = np.reshape(rand_map_0,", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30=", "np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask", "= bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 =", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 =", "bl_w1 = np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0])", "(tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1))", "= c13 pret_c14[...] = c14 pret_c15[...] = c15 pret_c16[...] =", "bn 4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean =", "one_fill c27 = neg_one_fill c28 = one_fill c29 = neg_one_fill", "= bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma =", "pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27=", "pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean)", "np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2)", "one_fill c31 = neg_one_fill c32 = one_fill pret_w1 [...] =", "= bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance =", "p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...]", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask =", "pret_c13[...] = c13 pret_c14[...] = c14 pret_c15[...] = c15 pret_c16[...]", "bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"]", "pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"]", "# expand randomisation map across tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29=", "[-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 3", "pret_c14[...] = c14 pret_c15[...] = c15 pret_c16[...] = c16 pret_c17[...]", "bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2", "1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"]", "p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance", "= np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float)", "p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...]", "one_fill pret_w1 [...] = w1 pret_c1 [...] = c1 pret_c2", "= np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma)", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27=", "pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...]", "pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"]", "c5 = one_fill c6 = neg_one_fill c7 = one_fill c8", "c30 = one_fill c31 = neg_one_fill c32 = one_fill pret_w1", "pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9", "= np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 2 bl_beta =", "c22 pret_c23[...] = c23 pret_c24[...] = c24 pret_c25[...] = c25", "pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1) p_gamma[...] = np.array(bl_gamma)", "bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 =", "shutil import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create pretrained.h5 using datastructure", "= neg_one_fill c5 = one_fill c6 = neg_one_fill c7 =", "bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 =", "p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...]", "bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1", "h5py.File(\"dummy.h5\", 'r') pretrained = h5py.File(\"pretrained_bin.h5\", 'r+') # dense layer 1", "[...] = c2 pret_c3 [...] = c3 pret_c4 [...] =", "only c1 = one_fill c2 = neg_one_fill c3 = one_fill", "bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"]", "= c9 pret_c10[...] = c10 pret_c11[...] = c11 pret_c12[...] =", "layer 3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask =", "* (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0,", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19=", "pret_c7 [...] = c7 pret_c8 [...] = c8 pret_c9 [...]", "neg_one_fill c26 = one_fill c27 = neg_one_fill c28 = one_fill", "[...] = c5 pret_c6 [...] = c6 pret_c7 [...] =", "pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill", "pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 =", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 =", "c16 pret_c17[...] = c17 pret_c18[...] = c18 pret_c19[...] = c19", "one_fill c8 = neg_one_fill c9 = one_fill c10 = neg_one_fill", "print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0", "pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11=", "= bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 =", "rand_map_1_expand[i] = rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i]", "rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma", "bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1", "pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"]", "(tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 =", "pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)]", "pret_c24[...] = c24 pret_c25[...] = c25 pret_c26[...] = c26 pret_c27[...]", "neg_one_fill c28 = one_fill c29 = neg_one_fill c30 = one_fill", "copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create pretrained.h5 using datastructure from dummy.h5", "bn 3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean =", "c13 pret_c14[...] = c14 pret_c15[...] = c15 pret_c16[...] = c16", "tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]])", "bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean", "p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...]", "pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4", "pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"]", "dense layer 1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma", "pret_c30[...] = c30 pret_c31[...] = c31 pret_c32[...] = c32 pret_rand_map_0[...]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1)", "'r') pretrained = h5py.File(\"pretrained_bin.h5\", 'r+') # dense layer 1 bl_w1", "p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2", "= pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance =", "pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"]", "bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta", "2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"]", "= np.array(bl_moving_variance) # bn 4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma =", "pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma", "rand_map_0_expand[i] = rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i]", "pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"]", "= np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn", "p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance", "= c21 pret_c22[...] = c22 pret_c23[...] = c23 pret_c24[...] =", "pret_means[...] = np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float)", "pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6", "for i in range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) *", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 =", "pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1", "pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6", "pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"]", "[...] = c7 pret_c8 [...] = c8 pret_c9 [...] =", "c15 pret_c16[...] = c16 pret_c17[...] = c17 pret_c18[...] = c18", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"]", "pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"]", "neg_one_fill c9 = one_fill c10 = neg_one_fill c11 = one_fill", "# dense layer 2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"]", "= np.array(bl_gamma) pret_means[...] = np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand =", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14=", "bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape)", "np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask", "pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"]", "= np.array(bl_w1) p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask))))", "# bn 5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean", "pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22=", "pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape =", "p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 4 bl_beta", "= neg_one_fill c3 = one_fill c4 = neg_one_fill c5 =", "bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape) w1 = bl_w1 # connect1", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 =", "pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"]", "np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 5", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"]", "p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1) p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...]", "c11 pret_c12[...] = c12 pret_c13[...] = c13 pret_c14[...] = c14", "pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8", "c9 pret_c10[...] = c10 pret_c11[...] = c11 pret_c12[...] = c12", "using datastructure from dummy.h5 bl = h5py.File(\"baseline_pruned.h5\", 'r') #dummy =", "= pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1) p_gamma[...] =", "c8 pret_c9 [...] = c9 pret_c10[...] = c10 pret_c11[...] =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1)", "pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"]", "= np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i] +", "bl = h5py.File(\"baseline_pruned.h5\", 'r') #dummy = h5py.File(\"dummy.h5\", 'r') pretrained =", "= rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] =", "= rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)),", "pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"]", "pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6", "pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma", "pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean)", "bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta", "bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1)", "pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12=", "tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0])", "pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"]", "c21 pret_c22[...] = c22 pret_c23[...] = c23 pret_c24[...] = c24", "pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"]", "copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create pretrained.h5 using datastructure from dummy.h5 bl", "pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill", "pret_c12[...] = c12 pret_c13[...] = c13 pret_c14[...] = c14 pret_c15[...]", "= one_fill c19 = neg_one_fill c20 = one_fill c21 =", "= bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"]", "tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0])", "pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape", "= pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] =", "pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"]", "np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"]", "w1 = bl_w1 # connect1 only c1 = one_fill c2", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14=", "= bl_w1 # connect1 only c1 = one_fill c2 =", "pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"]", "np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"]", "= one_fill c6 = neg_one_fill c7 = one_fill c8 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"]", "pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1", "[...] = c6 pret_c7 [...] = c7 pret_c8 [...] =", "pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"]", "c1 pret_c2 [...] = c2 pret_c3 [...] = c3 pret_c4", "create pretrained.h5 using datastructure from dummy.h5 bl = h5py.File(\"baseline_pruned.h5\", 'r')", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1", "pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 =", "pret_c5 [...] = c5 pret_c6 [...] = c6 pret_c7 [...]", "pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"]", "= bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta =", "= pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] =", "pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta)", "p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"]", "bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"]", "= neg_one_fill c9 = one_fill c10 = neg_one_fill c11 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30=", "bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma", "pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask", "expand randomisation map across tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand =", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape)", "= neg_one_fill c7 = one_fill c8 = neg_one_fill c9 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"]", "= neg_one_fill c24 = one_fill c25 = neg_one_fill c26 =", "pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0", "= np.array(bl_w1) bl_w1 = np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1", "pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"]", "= c27 pret_c28[...] = c28 pret_c29[...] = c29 pret_c30[...] =", "= np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 4 bl_beta =", "np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"]", "np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"]", "pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma", "= np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask", "bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"]", "rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0])", "= c14 pret_c15[...] = c15 pret_c16[...] = c16 pret_c17[...] =", "= c23 pret_c24[...] = c24 pret_c25[...] = c25 pret_c26[...] =", "np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 =", "pret_c10[...] = c10 pret_c11[...] = c11 pret_c12[...] = c12 pret_c13[...]", "= rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] =", "(-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...]", "pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"]", "= np.logical_or(pruning_mask, pruning_mask_recover) init_mask = np.reshape(init_mask, tile_shape) # expand randomisation", "= pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] =", "bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"]", "from dummy.h5 bl = h5py.File(\"baseline_pruned.h5\", 'r') #dummy = h5py.File(\"dummy.h5\", 'r')", "pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15=", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"]", "= bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 =", "pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0", "= neg_one_fill c18 = one_fill c19 = neg_one_fill c20 =", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means =", "pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"]", "np.array(bl_moving_variance) # bn 3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"]", "pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"]", "np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1))", "pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"]", "c21 = neg_one_fill c22 = one_fill c23 = neg_one_fill c24", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11=", "pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 =", "pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"]", "= neg_one_fill c30 = one_fill c31 = neg_one_fill c32 =", "pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"]", "pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28=", "pret_c2 [...] = c2 pret_c3 [...] = c3 pret_c4 [...]", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12=", "bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"]", "bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma", "pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1", "bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1", "c5 pret_c6 [...] = c6 pret_c7 [...] = c7 pret_c8", "np.array(bl_w1) bl_w1 = np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"]", "connect1 only c1 = one_fill c2 = neg_one_fill c3 =", "+ (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0", "pret_c29[...] = c29 pret_c30[...] = c30 pret_c31[...] = c31 pret_c32[...]", "pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2", "= rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 3 bl_w1 =", "= c10 pret_c11[...] = c11 pret_c12[...] = c12 pret_c13[...] =", "pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"]", "pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31=", "= np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma) pret_means[...] = np.array(bl_means) pret_pruning_mask[...]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20=", "randomisation and pruning recovery bl_w1_unroll = np.array(bl_w1) bl_w1 = np.array(bl_w1)", "= pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] =", "= c17 pret_c18[...] = c18 pret_c19[...] = c19 pret_c20[...] =", "= bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma =", "pret_c16[...] = c16 pret_c17[...] = c17 pret_c18[...] = c18 pret_c19[...]", "= np.array(bl_moving_variance) # bn 5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma =", "= neg_one_fill c22 = one_fill c23 = neg_one_fill c24 =", "[...] = c9 pret_c10[...] = c10 pret_c11[...] = c11 pret_c12[...]", "neg_one_fill c20 = one_fill c21 = neg_one_fill c22 = one_fill", "c25 pret_c26[...] = c26 pret_c27[...] = c27 pret_c28[...] = c28", "pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3", "= bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 =", "p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance", "bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"]", "= bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma =", "= neg_one_fill c11 = one_fill c12 = neg_one_fill c13 =", "np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand =", "1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23=", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30=", "(tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1))", "= pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] =", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape =", "bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"]", "# bn 4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24=", "[-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 4", "pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2", "pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1) p_gamma[...]", "c24 pret_c25[...] = c25 pret_c26[...] = c26 pret_c27[...] = c27", "pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3", "bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2", "p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27=", "pret_w1[...] = np.array(bl_w1) p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)),", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape =", "np.reshape(init_mask, tile_shape) # expand randomisation map across tiles rand_map_0_expand =", "pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma)", "np.array(bl_moving_variance) # bn 4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"]", "pret_c26[...] = c26 pret_c27[...] = c27 pret_c28[...] = c28 pret_c29[...]", "bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"]", "np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in range(weight_shape[0]): rand_map_0_expand[i] =", "= np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense", "pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 =", "pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"]", "pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"]", "pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"]", "pret_c3 [...] = c3 pret_c4 [...] = c4 pret_c5 [...]", "np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1", "pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean)", "= c30 pret_c31[...] = c31 pret_c32[...] = c32 pret_rand_map_0[...] =", "c18 pret_c19[...] = c19 pret_c20[...] = c20 pret_c21[...] = c21", "pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8", "pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13=", "np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"]", "p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 2 bl_beta", "np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25=", "np.array(bl_moving_variance) # bn 2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"]", "# bn 3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean", "init_mask = np.reshape(init_mask, tile_shape) # expand randomisation map across tiles", "pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22=", "datastructure from dummy.h5 bl = h5py.File(\"baseline_pruned.h5\", 'r') #dummy = h5py.File(\"dummy.h5\",", "= np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn", "np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover) init_mask", "c12 pret_c13[...] = c13 pret_c14[...] = c14 pret_c15[...] = c15", "rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand,", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26=", "neg_one_fill c30 = one_fill c31 = neg_one_fill c32 = one_fill", "[-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] =", "bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma", "pret_c4 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7", "bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"]", "p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 3 bl_beta", "randomisation map across tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]])", "pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4", "np.array(bl_moving_variance) # bn 5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"]", "bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"]", "pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill", "4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"]", "pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"]", "neg_one_fill c11 = one_fill c12 = neg_one_fill c13 = one_fill", "c14 = neg_one_fill c15 = one_fill c16 = neg_one_fill c17", "pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"]", "= bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma =", "c27 pret_c28[...] = c28 pret_c29[...] = c29 pret_c30[...] = c30", "pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"]", "pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10=", "pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"]", "+ tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape) w1", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"]", "bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2", "pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"]", "= pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31=", "bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means", "np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask =", "pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2", "h5py.File(\"pretrained_bin.h5\", 'r+') # dense layer 1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 =", "+ tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) +", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21=", "bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25=", "= pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] =", "bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta", "p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) #", "numpy as np np.set_printoptions(threshold=np.nan) from shutil import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\")", "= np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1)", "c29 pret_c30[...] = c30 pret_c31[...] = c31 pret_c32[...] = c32", "= bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 =", "p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...]", "p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 =", "one_fill c23 = neg_one_fill c24 = one_fill c25 = neg_one_fill", "bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma", "np np.set_printoptions(threshold=np.nan) from shutil import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create", "[...] = c3 pret_c4 [...] = c4 pret_c5 [...] =", "pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13=", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask =", "= pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 =", "bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"]", "pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2", "pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17=", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"]", "bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1)))", "= pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 =", "pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"]", "rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in range(weight_shape[0]):", "= pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28=", "c7 pret_c8 [...] = c8 pret_c9 [...] = c9 pret_c10[...]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32=", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28=", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22=", "# dense layer 4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"]", "pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"] pret_c8", "rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i]", "bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"]", "= one_fill c29 = neg_one_fill c30 = one_fill c31 =", "= one_fill c31 = neg_one_fill c32 = one_fill pret_w1 [...]", "one_fill c19 = neg_one_fill c20 = one_fill c21 = neg_one_fill", "pret_c19[...] = c19 pret_c20[...] = c20 pret_c21[...] = c21 pret_c22[...]", "pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1) p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask)", "= one_fill c2 = neg_one_fill c3 = one_fill c4 =", "bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"]", "pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4", "bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19=", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12=", "pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta)", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"]", "np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 3", "= bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma =", "pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"]", "p_moving_variance[...] = np.array(bl_moving_variance) # bn 4 bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma", "p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2", "= bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_7:0\"]", "pret_c23[...] = c23 pret_c24[...] = c24 pret_c25[...] = c25 pret_c26[...]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"]", "bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0", "bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"]", "(rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape)", "= np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover", "= c32 pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float)", "# randomisation and pruning recovery bl_w1_unroll = np.array(bl_w1) bl_w1 =", "= np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float)", "= pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] =", "pret_c18[...] = c18 pret_c19[...] = c19 pret_c20[...] = c20 pret_c21[...]", "= bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25=", "rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i]", "= c22 pret_c23[...] = c23 pret_c24[...] = c24 pret_c25[...] =", "p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...]", "pret_c8 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"]", "pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"]", "= h5py.File(\"dummy.h5\", 'r') pretrained = h5py.File(\"pretrained_bin.h5\", 'r+') # dense layer", "pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"]", "pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"]", "recovery bl_w1_unroll = np.array(bl_w1) bl_w1 = np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0])", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16=", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21=", "pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 2 bl_w1", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 =", "3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"]", "pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"]", "[-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 5", "c32 = one_fill pret_w1 [...] = w1 pret_c1 [...] =", "pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"]", "= c16 pret_c17[...] = c17 pret_c18[...] = c18 pret_c19[...] =", "= one_fill c10 = neg_one_fill c11 = one_fill c12 =", "np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover =", "pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3", "bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma", "'r+') # dense layer 1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23=", "c31 = neg_one_fill c32 = one_fill pret_w1 [...] = w1", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1", "np.array(bl_w1) p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) #", "[...] = c1 pret_c2 [...] = c2 pret_c3 [...] =", "pret_c20[...] = c20 pret_c21[...] = c21 pret_c22[...] = c22 pret_c23[...]", "one_fill c4 = neg_one_fill c5 = one_fill c6 = neg_one_fill", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"]", "bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"]", "5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"]", "# bn 1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean", "= bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape) w1 = bl_w1 #", "pret_c31[...] = c31 pret_c32[...] = c32 pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float)", "# dense layer 5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"]", "as np np.set_printoptions(threshold=np.nan) from shutil import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") #", "zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma", "pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape =", "= c12 pret_c13[...] = c13 pret_c14[...] = c14 pret_c15[...] =", "rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i]", "c11 = one_fill c12 = neg_one_fill c13 = one_fill c14", "= np.array(bl_moving_variance) # bn 3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma =", "import h5py import numpy as np np.set_printoptions(threshold=np.nan) from shutil import", "pret_c1 [...] = c1 pret_c2 [...] = c2 pret_c3 [...]", "= pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] =", "dummy.h5 bl = h5py.File(\"baseline_pruned.h5\", 'r') #dummy = h5py.File(\"dummy.h5\", 'r') pretrained", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15=", "print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23=", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1", "neg_one_fill c32 = one_fill pret_w1 [...] = w1 pret_c1 [...]", "pret_c15[...] = c15 pret_c16[...] = c16 pret_c17[...] = c17 pret_c18[...]", "bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"]", "pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma)", "h5py.File(\"baseline_pruned.h5\", 'r') #dummy = h5py.File(\"dummy.h5\", 'r') pretrained = h5py.File(\"pretrained_bin.h5\", 'r+')", "range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0])", "c23 = neg_one_fill c24 = one_fill c25 = neg_one_fill c26", "4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"]", "bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"]", "pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10=", "c9 = one_fill c10 = neg_one_fill c11 = one_fill c12", "# bn 2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean", "layer 1 bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma =", "init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask,", "rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"]", "one_fill c16 = neg_one_fill c17 = neg_one_fill c18 = one_fill", "bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma =", "bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1", "= np.array(bl_moving_variance) # bn 2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma =", "bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma", "pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"]", "pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill", "pret_c25[...] = c25 pret_c26[...] = c26 pret_c27[...] = c27 pret_c28[...]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill =", "p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2", "pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"]", "(-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma) pret_means[...] =", "pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"]", "pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"]", "pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] =", "= w1 pret_c1 [...] = c1 pret_c2 [...] = c2", "pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand", "c1 = one_fill c2 = neg_one_fill c3 = one_fill c4", "c10 = neg_one_fill c11 = one_fill c12 = neg_one_fill c13", "dense layer 4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask", "np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance)", "p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...]", "pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"]", "np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover) init_mask = np.reshape(init_mask, tile_shape)", "= np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0])", "= np.reshape(init_mask, tile_shape) # expand randomisation map across tiles rand_map_0_expand", "pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7", "(-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma) pret_means[...] = np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask)", "np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape) one_fill = np.ones(tile_shape)", "pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"]", "np.array(bl_gamma) pret_means[...] = np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand,", "np.reshape(bl_w1_rand_0, weight_shape) w1 = bl_w1 # connect1 only c1 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29=", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape =", "np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask =", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma =", "pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"]", "pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"]", "tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape) w1 =", "= one_fill pret_w1 [...] = w1 pret_c1 [...] = c1", "np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...]", "= bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"]", "pret_c11[...] = c11 pret_c12[...] = c12 pret_c13[...] = c13 pret_c14[...]", "p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2", "np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape) # randomisation and pruning recovery bl_w1_unroll", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 =", "bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean", "pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape", "rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1)", "one_fill c14 = neg_one_fill c15 = one_fill c16 = neg_one_fill", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31=", "pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask", "bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"]", "np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 2", "pruning recovery bl_w1_unroll = np.array(bl_w1) bl_w1 = np.array(bl_w1) rand_map_0 =", "= np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 2 bl_w1 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23=", "pret_c32= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 =", "np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"]", "bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2", "pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means", "p_moving_variance[...] = np.array(bl_moving_variance) # bn 5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma", "np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2", "bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means", "= neg_one_fill c17 = neg_one_fill c18 = one_fill c19 =", "= neg_one_fill c26 = one_fill c27 = neg_one_fill c28 =", "= np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 5 bl_beta =", "(rand_map_0_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_1_expand[i] = rand_map_1_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0])", "bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"]", "w1 pret_c1 [...] = c1 pret_c2 [...] = c2 pret_c3", "= bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean =", "= np.zeros(tile_shape) one_fill = np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape) # randomisation", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32=", "np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] =", "rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26=", "= np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] p_gamma =", "= np.reshape(bl_w1_rand_0, weight_shape) w1 = bl_w1 # connect1 only c1", "c6 = neg_one_fill c7 = one_fill c8 = neg_one_fill c9", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1)", "pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14=", "= pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] pret_w1[...] = np.array(bl_w1) p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...] =", "= np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] =", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"]", "neg_one_fill c22 = one_fill c23 = neg_one_fill c24 = one_fill", "neg_one_fill c7 = one_fill c8 = neg_one_fill c9 = one_fill", "= one_fill c12 = neg_one_fill c13 = one_fill c14 =", "pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover) init_mask =", "pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"]", "layer 5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask =", "weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape) one_fill", "(rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0])", "= pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance =", "np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool) init_mask = np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask,", "c26 = one_fill c27 = neg_one_fill c28 = one_fill c29", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 =", "c17 pret_c18[...] = c18 pret_c19[...] = c19 pret_c20[...] = c20", "p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...]", "print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31=", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 =", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 =", "bl_w1 # connect1 only c1 = one_fill c2 = neg_one_fill", "c10 pret_c11[...] = c11 pret_c12[...] = c12 pret_c13[...] = c13", "np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma) pret_means[...] = np.array(bl_means) pret_pruning_mask[...] =", "= neg_one_fill c20 = one_fill c21 = neg_one_fill c22 =", "= rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"]", "pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean)", "pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_31:0\"] pret_c32=", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 =", "pretrained[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"]", "pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 =", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"]", "pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta)", "rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask =", "= pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] =", "pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"]", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_20:0\"] pret_c21=", "pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"]", "= c19 pret_c20[...] = c20 pret_c21[...] = c21 pret_c22[...] =", "pretrained = h5py.File(\"pretrained_bin.h5\", 'r+') # dense layer 1 bl_w1 =", "[-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] =", "p_gamma[...] = np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense", "c12 = neg_one_fill c13 = one_fill c14 = neg_one_fill c15", "pret_c32[...] = c32 pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1,", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma =", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 =", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 =", "[...] = c4 pret_c5 [...] = c5 pret_c6 [...] =", "= bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1)", "p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...]", "pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand", "one_fill c2 = neg_one_fill c3 = one_fill c4 = neg_one_fill", "pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"]", "c32 pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...]", "= pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] =", "+ (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_1_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i] +", "rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0) rand_map_1 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 =", "pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"]", "= bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means =", "= bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 =", "print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0", "bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"]", "pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12=", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"]", "p_moving_variance[...] = np.array(bl_moving_variance) # bn 3 bl_beta = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] bl_gamma", "= np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2,", "pret_c4 [...] = c4 pret_c5 [...] = c5 pret_c6 [...]", "from shutil import copyfile copyfile(\"dummy_lutnet.h5\", \"pretrained_bin.h5\") # create pretrained.h5 using", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_23:0\"] pret_c24=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18=", "c29 = neg_one_fill c30 = one_fill c31 = neg_one_fill c32", "c2 pret_c3 [...] = c3 pret_c4 [...] = c4 pret_c5", "pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] =", "= rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand", "neg_one_fill c3 = one_fill c4 = neg_one_fill c5 = one_fill", "c13 = one_fill c14 = neg_one_fill c15 = one_fill c16", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape =", "one_fill c29 = neg_one_fill c30 = one_fill c31 = neg_one_fill", "pret_c27[...] = c27 pret_c28[...] = c28 pret_c29[...] = c29 pret_c30[...]", "bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1)", "c28 = one_fill c29 = neg_one_fill c30 = one_fill c31", "= pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance =", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"]", "rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"]", "bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"]", "= c15 pret_c16[...] = c16 pret_c17[...] = c17 pret_c18[...] =", "= bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma =", "np.array(bl_gamma) pret_pruning_mask[...] = np.array(bl_pruning_mask) print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 2", "pret_c17[...] = c17 pret_c18[...] = c18 pret_c19[...] = c19 pret_c20[...]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18=", "print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma =", "rand_map_2_expand = np.reshape(rand_map_2_expand, [-1,1]).astype(float) pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) #", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28=", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18=", "c28 pret_c29[...] = c29 pret_c30[...] = c30 pret_c31[...] = c31", "= c5 pret_c6 [...] = c6 pret_c7 [...] = c7", "h5py import numpy as np np.set_printoptions(threshold=np.nan) from shutil import copyfile", "p_gamma[...] = np.array(bl_gamma) pret_means[...] = np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_1:0\"]", "pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean)", "pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] p_gamma", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"]", "np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 =", "pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] pret_means", "pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"]", "= np.shape(pret_c1) zero_fill = np.zeros(tile_shape) one_fill = np.ones(tile_shape) neg_one_fill =", "np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30=", "pret_c21[...] = c21 pret_c22[...] = c22 pret_c23[...] = c23 pret_c24[...]", "pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 =", "= pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] =", "= bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask =", "= c25 pret_c26[...] = c26 pret_c27[...] = c27 pret_c28[...] =", "c8 = neg_one_fill c9 = one_fill c10 = neg_one_fill c11", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11=", "dense layer 5 bl_w1 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask", "c27 = neg_one_fill c28 = one_fill c29 = neg_one_fill c30", "+ tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) rand_map_2_expand[i] = rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) +", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1", "c3 = one_fill c4 = neg_one_fill c5 = one_fill c6", "pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand", "pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill =", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_19:0\"] pret_c20=", "[...] = c8 pret_c9 [...] = c9 pret_c10[...] = c10", "= c24 pret_c25[...] = c25 pret_c26[...] = c26 pret_c27[...] =", "bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma", "pret_c12= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"]", "= pretrained[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 =", "np.zeros(tile_shape) one_fill = np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape) # randomisation and", "rand_map_0_expand rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand =", "pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4", "= bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta =", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 =", "pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"]", "c24 = one_fill c25 = neg_one_fill c26 = one_fill c27", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"]", "pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_11:0\"]", "= pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance =", "= one_fill c21 = neg_one_fill c22 = one_fill c23 =", "pret_c9 [...] = c9 pret_c10[...] = c10 pret_c11[...] = c11", "= bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 =", "bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"]", "pret_c22= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"]", "= bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 =", "rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"]", "one_fill c25 = neg_one_fill c26 = one_fill c27 = neg_one_fill", "np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float) p_gamma[...] = np.array(bl_gamma) pret_means[...]", "= neg_one_fill c15 = one_fill c16 = neg_one_fill c17 =", "p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...]", "np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand = np.tile(rand_map_2,[weight_shape[0]/tile_shape[0]]) for i in", "pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"]", "= h5py.File(\"baseline_pruned.h5\", 'r') #dummy = h5py.File(\"dummy.h5\", 'r') pretrained = h5py.File(\"pretrained_bin.h5\",", "pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 3 bl_w1", "= bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] bl_gamma =", "bn 2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean =", "c20 pret_c21[...] = c21 pret_c22[...] = c22 pret_c23[...] = c23", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_8:0\"]", "= one_fill c8 = neg_one_fill c9 = one_fill c10 =", "'r') #dummy = h5py.File(\"dummy.h5\", 'r') pretrained = h5py.File(\"pretrained_bin.h5\", 'r+') #", "neg_one_fill c17 = neg_one_fill c18 = one_fill c19 = neg_one_fill", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_7:0\"]", "pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape", "= bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 =", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_3:0\"] pret_c4 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_5:0\"] pret_c6 =", "p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 5 bl_beta", "map across tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand", "np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] = np.reshape(rand_map_1, (-1,1)).astype(float) pret_rand_map_2[...] = np.reshape(rand_map_2, (-1,1)).astype(float)", "= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape =", "bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21=", "= pretrained[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_2:0\"] pret_c3 =", "rand_map_2_expand[i] = rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_28:0\"] pret_c29=", "tile_shape) # expand randomisation map across tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]])", "pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"]", "bl[\"model_weights\"][\"residual_sign_3\"][\"residual_sign_3\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_2:0\"]", "= bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means =", "in range(weight_shape[0]): rand_map_0_expand[i] = rand_map_0_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_0_expand[i]/tile_shape[0]) +", "bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] pret_pruning_mask", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17=", "pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_21:0\"] pret_c22= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_23:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_c1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"]", "pret_c25= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"]", "= bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean =", "p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] = np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) pretrained.close()", "= np.logical_not(pruning_mask[rand_map_0]) pruning_mask_recover = np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover)", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape =", "init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover) init_mask = np.reshape(init_mask, tile_shape) #", "= c11 pret_c12[...] = c12 pret_c13[...] = c13 pret_c14[...] =", "layer 4 bl_w1 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask =", "one_fill c12 = neg_one_fill c13 = one_fill c14 = neg_one_fill", "= c4 pret_c5 [...] = c5 pret_c6 [...] = c6", "pret_c22[...] = c22 pret_c23[...] = c23 pret_c24[...] = c24 pret_c25[...]", "= rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 5 bl_w1 =", "bl[\"model_weights\"][\"residual_sign_4\"][\"residual_sign_4\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_2:0\"]", "= c2 pret_c3 [...] = c3 pret_c4 [...] = c4", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_2:0\"] weight_shape = np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill =", "pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means = pretrained[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20=", "= c31 pret_c32[...] = c32 pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...]", "c31 pret_c32[...] = c32 pret_rand_map_0[...] = np.reshape(rand_map_0, (-1,1)).astype(float) pret_rand_map_1[...] =", "pret_c12= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_16:0\"]", "bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance", "np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"]", "pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"]", "np.array(bl_moving_mean) p_moving_variance[...] = np.array(bl_moving_variance) # bn 2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"]", "p_moving_variance[...] = np.array(bl_moving_variance) # bn 2 bl_beta = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"beta:0\"] bl_gamma", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29=", "bn 1 bl_beta = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean =", "bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"]", "bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_1\"][\"residual_sign_1\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"]", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"]", "rand_map_1_expand = np.reshape(rand_map_1_expand, [-1,1]).astype(float) pret_rand_map_exp_1[...] = rand_map_1_expand rand_map_2_expand = np.reshape(rand_map_2_expand,", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_22:0\"] pret_c23= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_23:0\"] pret_c24= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_24:0\"] pret_c25= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_26:0\"] pret_c27=", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable:0\"]", "bl_w1_unroll = np.array(bl_w1) bl_w1 = np.array(bl_w1) rand_map_0 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_0)", "= pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] p_moving_mean = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta[...] =", "c4 pret_c5 [...] = c5 pret_c6 [...] = c6 pret_c7", "np.logical_or(pruning_mask, pruning_mask_recover) init_mask = np.reshape(init_mask, tile_shape) # expand randomisation map", "c19 = neg_one_fill c20 = one_fill c21 = neg_one_fill c22", "bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape) w1 = bl_w1 # connect1 only", "bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable:0\"]", "pret_w1 [...] = w1 pret_c1 [...] = c1 pret_c2 [...]", "pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0 =", "pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"pruning_mask:0\"] p_gamma = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] pret_means", "= neg_one_fill c13 = one_fill c14 = neg_one_fill c15 =", "bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_1:0\"] pret_rand_map_2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_2:0\"] pret_pruning_mask = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"]", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_3:0\"] pret_c4 =", "pret_c27= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_31:0\"]", "pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17=", "bl_w1_rand_0 = bl_w1_unroll[rand_map_0_expand] bl_w1_rand_0 = np.reshape(bl_w1_rand_0, weight_shape) w1 = bl_w1", "c3 pret_c4 [...] = c4 pret_c5 [...] = c5 pret_c6", "one_fill = np.ones(tile_shape) neg_one_fill = -np.ones(tile_shape) # randomisation and pruning", "= bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"] bl_means =", "pret_rand_map_exp_2[...] = rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # bn 1 bl_beta =", "bl_gamma = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_1\"][\"batch_normalization_1\"][\"moving_variance:0\"] p_beta", "pret_c25= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_25:0\"] pret_c26= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_26:0\"] pret_c27= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_27:0\"] pret_c28= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_28:0\"] pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"]", "pret_c9 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_12:0\"] pret_c13=", "pret_c30= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_33:0\"] pret_rand_map_exp_0", "bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable:0\"]", "bl_w1 = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_8:0\"] pret_c9 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_10:0\"] pret_c11=", "= pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] p_moving_variance = pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] =", "= bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"moving_variance:0\"] p_beta = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] p_gamma = pretrained[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] p_moving_mean =", "pret_c16= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_16:0\"] pret_c17= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_20:0\"]", "pret_c29= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_29:0\"] pret_c30= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_30:0\"] pret_c31= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_31:0\"] pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 =", "= rand_map_2_expand print(np.sum(np.array(bl_pruning_mask)), np.prod(np.shape(np.array(bl_pruning_mask)))) # dense layer 4 bl_w1 =", "dense layer 2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask", "= rand_map_2_expand[i] + (tile_shape[0]*(weight_shape[0]/tile_shape[0]-1)) * (rand_map_2_expand[i]/tile_shape[0]) + tile_shape[0]*(i%weight_shape[0]/tile_shape[0]) bl_w1_rand_0 =", "= pretrained[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_variance:0\"] p_beta[...] = np.array(bl_beta) p_gamma[...] = np.array(bl_gamma) p_moving_mean[...] =", "= np.arange(tile_shape[0]) np.random.shuffle(rand_map_1) rand_map_2 = np.arange(tile_shape[0]) np.random.shuffle(rand_map_2) pruning_mask = np.array(bl_pruning_mask).astype(bool)", "pruning_mask_recover) init_mask = np.reshape(init_mask, tile_shape) # expand randomisation map across", "= np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...] = rand_map_0_expand rand_map_1_expand", "= np.shape(bl_w1) tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape) one_fill =", "= np.logical_and(pruning_mask, init_mask)[np.argsort(rand_map_0)] pruning_mask = np.logical_or(pruning_mask, pruning_mask_recover) init_mask = np.reshape(init_mask,", "c2 = neg_one_fill c3 = one_fill c4 = neg_one_fill c5", "c18 = one_fill c19 = neg_one_fill c20 = one_fill c21", "pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"] pret_c14= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_14:0\"] pret_c15= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_15:0\"] pret_c16= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_16:0\"] pret_c17=", "= pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 = pretrained[\"model_weights\"][\"binary_dense_4\"][\"binary_dense_4\"][\"rand_map_exp_1:0\"] pret_rand_map_exp_2 =", "= bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"] bl_gamma =", "#dummy = h5py.File(\"dummy.h5\", 'r') pretrained = h5py.File(\"pretrained_bin.h5\", 'r+') # dense", "= bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_1:0\"] pret_rand_map_2 =", "bl_beta = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_4\"][\"batch_normalization_4\"][\"moving_mean:0\"] bl_moving_variance", "# dense layer 3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"]", "= -np.ones(tile_shape) # randomisation and pruning recovery bl_w1_unroll = np.array(bl_w1)", "bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"pruning_mask:0\"] bl_gamma = bl[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable:0\"] zero_fill = np.zeros(np.shape(np.array(bl_w1))) pret_w1 = pretrained[\"model_weights\"][\"binary_dense_1\"][\"binary_dense_1\"][\"Variable_1:0\"]", "2 bl_w1 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_0:0\"] bl_pruning_mask = bl[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"pruning_mask:0\"]", "across tiles rand_map_0_expand = np.tile(rand_map_0,[weight_shape[0]/tile_shape[0]]) rand_map_1_expand = np.tile(rand_map_1,[weight_shape[0]/tile_shape[0]]) rand_map_2_expand =", "c22 = one_fill c23 = neg_one_fill c24 = one_fill c25", "pret_c32= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 =", "c19 pret_c20[...] = c20 pret_c21[...] = c21 pret_c22[...] = c22", "c20 = one_fill c21 = neg_one_fill c22 = one_fill c23", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_21:0\"] pret_c22=", "c7 = one_fill c8 = neg_one_fill c9 = one_fill c10", "= bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable:0\"] bl_means = bl[\"model_weights\"][\"residual_sign_2\"][\"residual_sign_2\"][\"means:0\"] pret_rand_map_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] pret_rand_map_1 =", "bn 5 bl_beta = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"beta:0\"] bl_gamma = bl[\"model_weights\"][\"batch_normalization_5\"][\"batch_normalization_5\"][\"gamma:0\"] bl_moving_mean =", "= c26 pret_c27[...] = c27 pret_c28[...] = c28 pret_c29[...] =", "= np.array(bl_means) pret_pruning_mask[...] = np.array(bl_pruning_mask) rand_map_0_expand = np.reshape(rand_map_0_expand, [-1,1]).astype(float) pret_rand_map_exp_0[...]", "pret_c17= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_17:0\"] pret_c18= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_18:0\"] pret_c19= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_19:0\"] pret_c20= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_20:0\"] pret_c21= pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_21:0\"]", "dense layer 3 bl_w1 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] bl_rand_map_0 = bl[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_0:0\"] bl_pruning_mask", "= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_1:0\"] pret_c2 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_2:0\"] pret_c3 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_3:0\"] pret_c4 =", "and pruning recovery bl_w1_unroll = np.array(bl_w1) bl_w1 = np.array(bl_w1) rand_map_0", "neg_one_fill c24 = one_fill c25 = neg_one_fill c26 = one_fill", "pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_4:0\"] pret_c5 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_5:0\"] pret_c6 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_7:0\"]", "pret_c6 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_6:0\"] pret_c7 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_7:0\"] pret_c8 = pretrained[\"model_weights\"][\"binary_dense_5\"][\"binary_dense_5\"][\"Variable_8:0\"] pret_c9", "\"pretrained_bin.h5\") # create pretrained.h5 using datastructure from dummy.h5 bl =", "tile_shape = np.shape(pret_c1) zero_fill = np.zeros(tile_shape) one_fill = np.ones(tile_shape) neg_one_fill", "= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_9:0\"] pret_c10= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_10:0\"] pret_c11= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_11:0\"] pret_c12= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_12:0\"] pret_c13= pretrained[\"model_weights\"][\"binary_dense_2\"][\"binary_dense_2\"][\"Variable_13:0\"]", "neg_one_fill c13 = one_fill c14 = neg_one_fill c15 = one_fill", "= neg_one_fill c32 = one_fill pret_w1 [...] = w1 pret_c1", "= bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_2\"][\"batch_normalization_2\"][\"moving_variance:0\"] p_beta =", "= one_fill c27 = neg_one_fill c28 = one_fill c29 =", "pret_c32= pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_32:0\"] pret_w1 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"Variable_33:0\"] pret_rand_map_exp_0 = pretrained[\"model_weights\"][\"binary_dense_3\"][\"binary_dense_3\"][\"rand_map_exp_0:0\"] pret_rand_map_exp_1 =", "neg_one_fill = -np.ones(tile_shape) # randomisation and pruning recovery bl_w1_unroll =", "# connect1 only c1 = one_fill c2 = neg_one_fill c3", "= bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"gamma:0\"] bl_moving_mean = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_mean:0\"] bl_moving_variance = bl[\"model_weights\"][\"batch_normalization_3\"][\"batch_normalization_3\"][\"moving_variance:0\"] p_beta =", "pretrained.h5 using datastructure from dummy.h5 bl = h5py.File(\"baseline_pruned.h5\", 'r') #dummy" ]
[ "return list(self._labels) def write(self, outfile, tokens): \"\"\"Writes ARFF data to", "%s\\n\\n' % time.ctime()) # Relation name s += '@RELATION rel\\n\\n'", "or STRING. \"\"\" self._labels = labels self._features = features def", "def header_section(self): \"\"\"Returns an ARFF header as a string.\"\"\" #", "% time.ctime()) # Relation name s += '@RELATION rel\\n\\n' #", "[(tok, None) for tok in tokens] # Data section s", "test data file. test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) #", "= tempfile.mkdtemp() try: # Write the training data file. train_filename", "if classifier in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier in", "and ftype is an ARFF type string such as NUMERIC", "numeric and string (note: not nominal) types. \"\"\" # Find", "of classes.\"\"\" return list(self._labels) def write(self, outfile, tokens): \"\"\"Writes ARFF", "input into Weka. Features and classes can be specified manually", "'-t', train_filename] cmd += list(options) if quiet: stdout = subprocess.PIPE", "'actual', 'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1] for line in lines[1:]", "DictionaryProbDist(probs) def parse_weka_output(self, lines): # Strip unwanted text from stdout", "the WEKAHOME environment variable. ' 'For more information about Weka,", "'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod", "by NLTK\\n' + '%% %s\\n\\n' % time.ctime()) # Relation name", "featuresets) # Call weka to classify the data. cmd =", "self._formatter.write(test_filename, featuresets) # Call weka to classify the data. cmd", "return ARFF_Formatter(labels, features) def header_section(self): \"\"\"Returns an ARFF header as", "ftype) if features.get(fname, ftype) != ftype: raise ValueError('Inconsistent type for", "import java, config_java from nltk.classify.api import ClassifierI _weka_classpath = None", "\"\"\" def __init__(self, labels, features): \"\"\" :param labels: A list", "= ftype features = sorted(features.items()) return ARFF_Formatter(labels, features) def header_section(self):", "% stderr) # Parse weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for", "Determine the types of all features. features = {} for", "see LICENSE.TXT \"\"\" Classifiers that make use of the external", "' 'of weka may not be supported.\\n' ' Header: %s'", "Label attribute specification s += '@ATTRIBUTE %-30r {%s}\\n' % ('-label-',", "f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter: \"\"\" Converts", "raise ValueError('Unsupported value type %r' % ftype) if features.get(fname, ftype)", "license information, see LICENSE.TXT \"\"\" Classifiers that make use of", "enumerate(lines): if line.strip().startswith(\"inst#\"): lines = lines[i:] break if lines[0].split() ==", "+ '%% %s\\n\\n' % time.ctime()) # Relation name s +=", "# Parse weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f in", "whether the given tokens are labeled or not. If None,", "list of classifiers (some may be abstract?): # ADTree, AODE,", "be determined from data using ``from_train``. \"\"\" def __init__(self, labels,", "'ripper': 'weka.classifiers.rules.JRip', } @classmethod def train(cls, model_filename, featuresets, classifier='naivebayes', options=[],", "the tokens will be assumed to be labeled if the", "Prism, RandomForest, # RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor, # RuleNode,", "A list of feature specifications, where each feature specification is", "'write'): outfile = open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod def from_train(tokens):", "finally: zf.close() class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename): self._formatter =", "def __init__(self, formatter, model_filename): self._formatter = formatter self._model = model_filename", "isinstance(tokens[0], (tuple, list)) if not labeled: tokens = [(tok, None)", "If unlabeled, # then use 'None' if labeled is None:", "% self._fmt_arff_val(tok.get(fname)) s += '%s\\n' % self._fmt_arff_val(label) return s def", "+= '@ATTRIBUTE %-30r {%s}\\n' % ('-label-', ','.join(self._labels)) return s def", "'Illegal options: -distribution' in stderr: raise ValueError('The installed version of", "IB1, IBk, Id3, J48, # JRip, KStar, LBR, LeastMedSq, LinearRegression,", "labels that can be generated. :param features: A list of", "version: print(('[Found Weka: %s (version %s)]' % (_weka_classpath, version))) else:", "Copyright (C) 2001-2015 NLTK Project # Author: <NAME> <<EMAIL>> #", "Strip unwanted text from stdout for i,line in enumerate(lines): if", "RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor, # RuleNode, SimpleLinearRegression, SimpleLogistic, #", "+= '%s,' % self._fmt_arff_val(tok.get(fname)) s += '%s\\n' % self._fmt_arff_val(label) return", "# ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule, # DecisionStump, DecisionTable, HyperPipes,", "raise LookupError('Unable to find weka.jar! Use config_weka() ' 'or set", "SMOreg, UserClassifier, VFI, # VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS = {", "NUMERIC or STRING. \"\"\" self._labels = labels self._features = features", "be assumed to be labeled if the first token's value", "'@RELATION rel\\n\\n' # Input attribute specifications for fname, ftype in", "f)) os.rmdir(temp_dir) class ARFF_Formatter: \"\"\" Converts featuresets and labeled featuresets", "tokens) # Determine the types of all features. features =", "for tok, label in tokens: for (fname, fval) in tok.items():", "NLTK Project # Author: <NAME> <<EMAIL>> # URL: <http://nltk.org/> #", "for the given data. :param tokens: a list of featuresets", "time import tempfile import os import subprocess import re import", "stderr: raise ValueError('The installed version of weka does ' 'not", "each feature specification is a tuple (fname, ftype); and ftype", "can't tell the type. else: raise ValueError('Unsupported value type %r'", "ValueError('Inconsistent type for %s' % fname) features[fname] = ftype features", "% ('-label-', ','.join(self._labels)) return s def data_section(self, tokens, labeled=None): \"\"\"", "cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass =", "type. else: raise ValueError('Unsupported value type %r' % ftype) if", "import subprocess import re import zipfile from sys import stdin", "LICENSE.TXT \"\"\" Classifiers that make use of the external 'Weka'", "nltk.internals import java, config_java from nltk.classify.api import ClassifierI _weka_classpath =", "J48, # JRip, KStar, LBR, LeastMedSq, LinearRegression, LMT, Logistic, #", "classifier %s' % classifier) # Train the weka model. cmd", "data.\"\"\" return self.header_section() + self.data_section(tokens) def labels(self): \"\"\"Returns the list", "Weka Classsifiers # # Copyright (C) 2001-2015 NLTK Project #", "may be determined from data using ``from_train``. \"\"\" def __init__(self,", "rel\\n\\n' # Input attribute specifications for fname, ftype in self._features:", "classifier. return WekaClassifier(formatter, model_filename) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir,", "'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath) if version:", "'Weka' package. \"\"\" from __future__ import print_function import time import", "# [xx] full list of classifiers (some may be abstract?):", "print(('[Found Weka: %s (version %s)]' % (_weka_classpath, version))) else: print('[Found", "if classpath is not None: _weka_classpath = classpath if _weka_classpath", "Train the weka model. cmd = [javaclass, '-d', model_filename, '-t',", "for fname, ftype in self._features: s += '%s,' % self._fmt_arff_val(tok.get(fname))", "+ '% Generated automatically by NLTK\\n' + '%% %s\\n\\n' %", "of ARFF output for the given data.\"\"\" return self.header_section() +", "version))) else: print('[Found Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath", "output format -- your version ' 'of weka may not", "[self.parse_weka_distribution(line.split()[-1]) for line in lines[1:] if line.strip()] # is this", "Ridor, # RuleNode, SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer, SMO, SMOreg, UserClassifier,", "formatter.write(train_filename, featuresets) if classifier in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif", "nltk.classify.util import names_demo, binary_names_demo_features def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model', featuresets, 'C4.5')", "# RuleNode, SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI,", "for (fname, fval) in tok.items(): if issubclass(type(fval), bool): ftype =", "the list of classes.\"\"\" return list(self._labels) def write(self, outfile, tokens):", "# URL: <http://nltk.org/> # For license information, see LICENSE.TXT \"\"\"", "nominal) types. \"\"\" # Find the set of all attested", "__future__ import print_function import time import tempfile import os import", "Returns the ARFF data section for the given data. :param", "classpath=_weka_classpath, stdout=stdout) # Return the new classifier. return WekaClassifier(formatter, model_filename)", "-- your version ' 'of weka may not be supported.\\n'", "('% Weka ARFF file\\n' + '% Generated automatically by NLTK\\n'", "and isinstance(tokens[0], (tuple, list)) if not labeled: tokens = [(tok,", "def __init__(self, labels, features): \"\"\" :param labels: A list of", "model_filename) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class", "','.join(self._labels)) return s def data_section(self, tokens, labeled=None): \"\"\" Returns the", "in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter: \"\"\" Converts featuresets", "WekaClassifier(formatter, model_filename) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir)", "Features and classes can be specified manually in the constructor,", "# VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5':", "% self._fmt_arff_val(label) return s def _fmt_arff_val(self, fval): if fval is", "be specified manually in the constructor, or may be determined", "set of all attested labels. labels = set(label for (tok,", "'@ATTRIBUTE %-30r %s\\n' % (fname, ftype) # Label attribute specification", "output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f))", "%s' % classifier) # Train the weka model. cmd =", "from stdout for i,line in enumerate(lines): if line.strip().startswith(\"inst#\"): lines =", "[xx] full list of classifiers (some may be abstract?): #", "feature specification is a tuple (fname, ftype); and ftype is", "the test data file. test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets)", "cmd = [javaclass, '-d', model_filename, '-t', train_filename] cmd += list(options)", "os.environ['WEKAHOME']) for path in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath =", "the new classifier. return WekaClassifier(formatter, model_filename) finally: for f in", "specifications, where each feature specification is a tuple (fname, ftype);", "searchpath = _weka_search if 'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for", "class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename): self._formatter = formatter self._model", "def parse_weka_output(self, lines): # Strip unwanted text from stdout for", "RuleNode, SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI, #", "s): probs = [float(v) for v in re.split('[*,]+', s) if", "cmd += list(options) if quiet: stdout = subprocess.PIPE else: stdout", "list(options) if quiet: stdout = subprocess.PIPE else: stdout = None", "labels self._features = features def format(self, tokens): \"\"\"Returns a string", "Winnow, ZeroR _CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression':", "label) in tokens: for fname, ftype in self._features: s +=", "Toolkit: Interface to Weka Classsifiers # # Copyright (C) 2001-2015", "_weka_classpath = classpath if _weka_classpath is None: searchpath = _weka_search", "import names_demo, binary_names_demo_features def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model', featuresets, 'C4.5') classifier", "classpath is not None: _weka_classpath = classpath if _weka_classpath is", "'%r' % fval else: return '%r' % fval if __name__", "= model_filename def prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0', '-distribution'])", "zipfile.ZipFile(jar) except SystemExit as KeyboardInterrupt: raise except: return None try:", "write(self, outfile, tokens): \"\"\"Writes ARFF data to a file for", "tokens: for (fname, fval) in tok.items(): if issubclass(type(fval), bool): ftype", "def prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0', '-distribution']) def classify_many(self,", "line in lines[:10]: print(line) raise ValueError('Unhandled output format -- your", "data_section(self, tokens, labeled=None): \"\"\" Returns the ARFF data section for", "s += '@RELATION rel\\n\\n' # Input attribute specifications for fname,", "'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path in searchpath: if", "'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1] for line in lines[1:] if", "ftype = 'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype = 'STRING' elif", "None finally: zf.close() class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename): self._formatter", "class ARFF_Formatter: \"\"\" Converts featuresets and labeled featuresets to ARFF-formatted", "an ARFF type string such as NUMERIC or STRING. \"\"\"", "# Check if the tokens are labeled or unlabeled. If", "file for the given data.\"\"\" if not hasattr(outfile, 'write'): outfile", "if _weka_classpath is None: raise LookupError('Unable to find weka.jar! Use", "representation of ARFF output for the given data.\"\"\" return self.header_section()", "= [javaclass, '-d', model_filename, '-t', train_filename] cmd += list(options) if", "% fname) features[fname] = ftype features = sorted(features.items()) return ARFF_Formatter(labels,", "None try: try: return zf.read('weka/core/version.txt') except KeyError: return None finally:", "tuple (fname, ftype); and ftype is an ARFF type string", "dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def parse_weka_output(self, lines): # Strip unwanted", "probability distribution ' 'output.') else: raise ValueError('Weka failed to generate", "ARFF type string such as NUMERIC or STRING. \"\"\" self._labels", "[01]\\.[0-9]* \\?\\s*$', lines[0]): return [line.split()[1] for line in lines if", "= os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) # Call weka to classify", "and labeled featuresets to ARFF-formatted strings, appropriate for input into", "ARFF header as a string.\"\"\" # Header comment. s =", "zf = zipfile.ZipFile(jar) except SystemExit as KeyboardInterrupt: raise except: return", "in tokens: for fname, ftype in self._features: s += '%s,'", "'%s,' % self._fmt_arff_val(tok.get(fname)) s += '%s\\n' % self._fmt_arff_val(label) return s", "feature types determined from the given data. Handles boolean, numeric", "cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename] + options (stdout,", "and feature types determined from the given data. Handles boolean,", "tempfile.mkdtemp() try: # Write the test data file. test_filename =", "else: raise ValueError('Weka failed to generate output:\\n%s' % stderr) #", "return '?' elif isinstance(fval, (bool, compat.integer_types)): return '%s' % fval", "!= ftype: raise ValueError('Inconsistent type for %s' % fname) features[fname]", "Id3, J48, # JRip, KStar, LBR, LeastMedSq, LinearRegression, LMT, Logistic,", "name s += '@RELATION rel\\n\\n' # Input attribute specifications for", "'of weka may not be supported.\\n' ' Header: %s' %", "Check if the tokens are labeled or unlabeled. If unlabeled,", "'%s' % fval elif isinstance(fval, float): return '%r' % fval", "% (_weka_classpath, version))) else: print('[Found Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath)", "def labels(self): \"\"\"Returns the list of classes.\"\"\" return list(self._labels) def", "= labels self._features = features def format(self, tokens): \"\"\"Returns a", "tokens = [(tok, None) for tok in tokens] # Data", "ARFF data to a file for the given data.\"\"\" if", "tokens, labeled=None): \"\"\" Returns the ARFF data section for the", "ftype in self._features: s += '%s,' % self._fmt_arff_val(tok.get(fname)) s +=", "bool)): ftype = 'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype = 'STRING'", "Input attribute specifications for fname, ftype in self._features: s +=", "stdin from nltk import compat from nltk.probability import DictionaryProbDist from", "\"\"\"Returns the list of classes.\"\"\" return list(self._labels) def write(self, outfile,", "ARFF data section for the given data. :param tokens: a", "test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) # Call weka to", "ValueError('The installed version of weka does ' 'not support probability", "failed to generate output:\\n%s' % stderr) # Parse weka's output.", "is None: raise LookupError('Unable to find weka.jar! Use config_weka() '", "Language Toolkit: Interface to Weka Classsifiers # # Copyright (C)", "featuresets, options): # Make sure we can find java &", "classifier) # Train the weka model. cmd = [javaclass, '-d',", "does ' 'not support probability distribution ' 'output.') else: raise", "features): \"\"\" :param labels: A list of all class labels", "@staticmethod def from_train(tokens): \"\"\" Constructs an ARFF_Formatter instance with class", "from __future__ import print_function import time import tempfile import os", "<<EMAIL>> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT", "for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter: \"\"\"", "print('[Found Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is None:", "and string (note: not nominal) types. \"\"\" # Find the", "i,line in enumerate(lines): if line.strip().startswith(\"inst#\"): lines = lines[i:] break if", "header as a string.\"\"\" # Header comment. s = ('%", "'prediction']: return [line.split()[2].split(':')[1] for line in lines[1:] if line.strip()] elif", "return None finally: zf.close() class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename):", "list of feature specifications, where each feature specification is a", "NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression, PART, #", "labels: A list of all class labels that can be", "Make sure we can find java & weka. config_weka() temp_dir", "None: labeled = tokens and isinstance(tokens[0], (tuple, list)) if not", "weka model. cmd = [javaclass, '-d', model_filename, '-t', train_filename] cmd", "if stderr and not stdout: if 'Illegal options: -distribution' in", "java & weka. config_weka() temp_dir = tempfile.mkdtemp() try: # Write", "# Relation name s += '@RELATION rel\\n\\n' # Input attribute", "find java & weka. config_weka() # Build an ARFF formatter.", "about Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf", "def classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0']) def _classify_many(self, featuresets,", "else: for line in lines[:10]: print(line) raise ValueError('Unhandled output format", "# Train the weka model. cmd = [javaclass, '-d', model_filename,", "is an ARFF type string such as NUMERIC or STRING.", "return [line.split()[2].split(':')[1] for line in lines[1:] if line.strip()] elif lines[0].split()", "break if lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'prediction']: return", "for the given data.\"\"\" if not hasattr(outfile, 'write'): outfile =", "featuresets which are tuples (featureset, label). :param labeled: Indicates whether", "file. test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) # Call weka", "features: A list of feature specifications, where each feature specification", "type string such as NUMERIC or STRING. \"\"\" self._labels =", "'-T', test_filename] + options (stdout, stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE,", "outfile = open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod def from_train(tokens): \"\"\"", "as NUMERIC or STRING. \"\"\" self._labels = labels self._features =", "the given tokens are labeled or not. If None, then", "ClassifierI _weka_classpath = None _weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka',", "attested labels. labels = set(label for (tok, label) in tokens)", "finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter:", "of all class labels that can be generated. :param features:", "binary_names_demo_features def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model', featuresets, 'C4.5') classifier = names_demo(make_classifier,", "\"\"\"Returns an ARFF header as a string.\"\"\" # Header comment.", "features) def header_section(self): \"\"\"Returns an ARFF header as a string.\"\"\"", "given data.\"\"\" return self.header_section() + self.data_section(tokens) def labels(self): \"\"\"Returns the", "config_weka() # Build an ARFF formatter. formatter = ARFF_Formatter.from_train(featuresets) temp_dir", "more information about Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar):", "os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs = [float(v)", "os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter: \"\"\" Converts featuresets and labeled", ":param labeled: Indicates whether the given tokens are labeled or", "a tuple (fname, ftype); and ftype is an ARFF type", "for line in lines[1:] if line.strip()] elif lines[0].split() == ['inst#',", "tok in tokens] # Data section s = '\\n@DATA\\n' for", "raise ValueError('Unhandled output format -- your version ' 'of weka", "HyperPipes, IB1, IBk, Id3, J48, # JRip, KStar, LBR, LeastMedSq,", "if v.strip()] probs = dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def parse_weka_output(self,", "model_filename, featuresets, classifier='naivebayes', options=[], quiet=True): # Make sure we can", "= cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass = classifier else:", "__init__(self, labels, features): \"\"\" :param labels: A list of all", "we can find java & weka. config_weka() temp_dir = tempfile.mkdtemp()", "featuresets): return self._classify_many(featuresets, ['-p', '0', '-distribution']) def classify_many(self, featuresets): return", "return None try: try: return zf.read('weka/core/version.txt') except KeyError: return None", "specification s += '@ATTRIBUTE %-30r {%s}\\n' % ('-label-', ','.join(self._labels)) return", "= tokens and isinstance(tokens[0], (tuple, list)) if not labeled: tokens", "= [(tok, None) for tok in tokens] # Data section", "classes.\"\"\" return list(self._labels) def write(self, outfile, tokens): \"\"\"Writes ARFF data", "} @classmethod def train(cls, model_filename, featuresets, classifier='naivebayes', options=[], quiet=True): #", "import re import zipfile from sys import stdin from nltk", "'or set the WEKAHOME environment variable. ' 'For more information", "set the WEKAHOME environment variable. ' 'For more information about", "raise except: return None try: try: return zf.read('weka/core/version.txt') except KeyError:", "_check_weka_version(jar): try: zf = zipfile.ZipFile(jar) except SystemExit as KeyboardInterrupt: raise", "ARFF-formatted strings, appropriate for input into Weka. Features and classes", "import DictionaryProbDist from nltk.internals import java, config_java from nltk.classify.api import", "os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath) if", "in self._features: s += '%s,' % self._fmt_arff_val(tok.get(fname)) s += '%s\\n'", "are labeled or unlabeled. If unlabeled, # then use 'None'", "an ARFF_Formatter instance with class labels and feature types determined", "tokens: for fname, ftype in self._features: s += '%s,' %", "fname, ftype in self._features: s += '%s,' % self._fmt_arff_val(tok.get(fname)) s", "['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath #", "'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod def from_train(tokens): \"\"\" Constructs an ARFF_Formatter", "line.strip()] else: for line in lines[:10]: print(line) raise ValueError('Unhandled output", "LBR, LeastMedSq, LinearRegression, LMT, Logistic, # LogisticBase, M5Base, MultilayerPerceptron, #", "tokens): \"\"\"Writes ARFF data to a file for the given", "ftype = 'STRING' elif fval is None: continue # can't", "'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf = zipfile.ZipFile(jar) except SystemExit as", "line in lines if line.strip()] else: for line in lines[:10]:", "in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path in searchpath: if os.path.exists(os.path.join(path,", "Weka: %s (version %s)]' % (_weka_classpath, version))) else: print('[Found Weka:", "be abstract?): # ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule, # DecisionStump,", "Handles boolean, numeric and string (note: not nominal) types. \"\"\"", "type for %s' % fname) features[fname] = ftype features =", "tokens are labeled or unlabeled. If unlabeled, # then use", "_check_weka_version(_weka_classpath) if version: print(('[Found Weka: %s (version %s)]' % (_weka_classpath,", "not None: _weka_classpath = classpath if _weka_classpath is None: searchpath", "= lines[i:] break if lines[0].split() == ['inst#', 'actual', 'predicted', 'error',", "stdout = subprocess.PIPE else: stdout = None java(cmd, classpath=_weka_classpath, stdout=stdout)", "full list of classifiers (some may be abstract?): # ADTree,", "the type. else: raise ValueError('Unsupported value type %r' % ftype)", "features. features = {} for tok, label in tokens: for", "M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple, NBTree, NNge,", "Weka ARFF file\\n' + '% Generated automatically by NLTK\\n' +", "quiet: stdout = subprocess.PIPE else: stdout = None java(cmd, classpath=_weka_classpath,", "Return the new classifier. return WekaClassifier(formatter, model_filename) finally: for f", "classifier else: raise ValueError('Unknown classifier %s' % classifier) # Train", "%s' % fname) features[fname] = ftype features = sorted(features.items()) return", "if line.strip().startswith(\"inst#\"): lines = lines[i:] break if lines[0].split() == ['inst#',", "# PreConstructedLinearModel, Prism, RandomForest, # RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor,", "javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass = classifier", "an ARFF header as a string.\"\"\" # Header comment. s", "Relation name s += '@RELATION rel\\n\\n' # Input attribute specifications", "the given data. :param tokens: a list of featuresets (dicts)", "installed version of weka does ' 'not support probability distribution", "ValueError('Unsupported value type %r' % ftype) if features.get(fname, ftype) !=", "[javaclass, '-d', model_filename, '-t', train_filename] cmd += list(options) if quiet:", "sys import stdin from nltk import compat from nltk.probability import", "determined from data using ``from_train``. \"\"\" def __init__(self, labels, features):", "_weka_search if 'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path in", "java & weka. config_weka() # Build an ARFF formatter. formatter", "in self._features: s += '@ATTRIBUTE %-30r %s\\n' % (fname, ftype)", "(_weka_classpath, version))) else: print('[Found Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath) if", "'\\n@DATA\\n' for (tok, label) in tokens: for fname, ftype in", "return self._classify_many(featuresets, ['-p', '0', '-distribution']) def classify_many(self, featuresets): return self._classify_many(featuresets,", "s) if v.strip()] probs = dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def", "given tokens are labeled or not. If None, then the", "fval): if fval is None: return '?' elif isinstance(fval, (bool,", "if fval is None: return '?' elif isinstance(fval, (bool, compat.integer_types)):", "= ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try: # Write the training", "is not None: _weka_classpath = classpath if _weka_classpath is None:", "None: searchpath = _weka_search if 'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME'])", "%s (version %s)]' % (_weka_classpath, version))) else: print('[Found Weka: %s]'", "train_filename] cmd += list(options) if quiet: stdout = subprocess.PIPE else:", "Natural Language Toolkit: Interface to Weka Classsifiers # # Copyright", "# Natural Language Toolkit: Interface to Weka Classsifiers # #", "ARFF formatter. formatter = ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try: #", "= set(label for (tok, label) in tokens) # Determine the", "if issubclass(type(fval), bool): ftype = '{True, False}' elif issubclass(type(fval), (compat.integer_types,", "assumed to be labeled if the first token's value is", "isinstance(fval, float): return '%r' % fval else: return '%r' %", "' 'output.') else: raise ValueError('Weka failed to generate output:\\n%s' %", "tok, label in tokens: for (fname, fval) in tok.items(): if", "finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self,", "for line in lines[1:] if line.strip()] # is this safe:?", "ARFF_Formatter instance with class labels and feature types determined from", "if 'Illegal options: -distribution' in stderr: raise ValueError('The installed version", "v.strip()] probs = dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def parse_weka_output(self, lines):", "= subprocess.PIPE else: stdout = None java(cmd, classpath=_weka_classpath, stdout=stdout) #", "%s]' % _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is None: raise LookupError('Unable", "information about Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try:", "self._classify_many(featuresets, ['-p', '0', '-distribution']) def classify_many(self, featuresets): return self._classify_many(featuresets, ['-p',", "KeyboardInterrupt: raise except: return None try: try: return zf.read('weka/core/version.txt') except", "= os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if classifier in cls._CLASSIFIER_CLASS: javaclass", "formatter. formatter = ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try: # Write", "for input into Weka. Features and classes can be specified", "data using ``from_train``. \"\"\" def __init__(self, labels, features): \"\"\" :param", "featuresets): return self._classify_many(featuresets, ['-p', '0']) def _classify_many(self, featuresets, options): #", "def data_section(self, tokens, labeled=None): \"\"\" Returns the ARFF data section", "# Make sure java's configured first. config_java() if classpath is", ":param features: A list of feature specifications, where each feature", "# JRip, KStar, LBR, LeastMedSq, LinearRegression, LMT, Logistic, # LogisticBase,", "'/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath # Make sure java's configured", "strings, appropriate for input into Weka. Features and classes can", "generate output:\\n%s' % stderr) # Parse weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n'))", "JRip, KStar, LBR, LeastMedSq, LinearRegression, LMT, Logistic, # LogisticBase, M5Base,", "to Weka Classsifiers # # Copyright (C) 2001-2015 NLTK Project", "for i,line in enumerate(lines): if line.strip().startswith(\"inst#\"): lines = lines[i:] break", "s def data_section(self, tokens, labeled=None): \"\"\" Returns the ARFF data", "data. Handles boolean, numeric and string (note: not nominal) types.", "the ARFF data section for the given data. :param tokens:", "labeled: Indicates whether the given tokens are labeled or not.", "elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass = classifier else: raise ValueError('Unknown", "'?' elif isinstance(fval, (bool, compat.integer_types)): return '%s' % fval elif", "% fval else: return '%r' % fval if __name__ ==", "weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir,", "re.split('[*,]+', s) if v.strip()] probs = dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs)", "Parse weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f in os.listdir(temp_dir):", "formatter self._model = model_filename def prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p',", "classifier in cls._CLASSIFIER_CLASS.values(): javaclass = classifier else: raise ValueError('Unknown classifier", "for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s):", "if quiet: stdout = subprocess.PIPE else: stdout = None java(cmd,", "& weka. config_weka() temp_dir = tempfile.mkdtemp() try: # Write the", "classes can be specified manually in the constructor, or may", "= open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod def from_train(tokens): \"\"\" Constructs", "quiet=True): # Make sure we can find java & weka.", "ftype in self._features: s += '@ATTRIBUTE %-30r %s\\n' % (fname,", "be generated. :param features: A list of feature specifications, where", "path in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar')", "data. :param tokens: a list of featuresets (dicts) or labelled", "features.get(fname, ftype) != ftype: raise ValueError('Inconsistent type for %s' %", "unlabeled, # then use 'None' if labeled is None: labeled", "\"\"\" from __future__ import print_function import time import tempfile import", "``from_train``. \"\"\" def __init__(self, labels, features): \"\"\" :param labels: A", "is None: searchpath = _weka_search if 'WEKAHOME' in os.environ: searchpath.insert(0,", "['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename] + options (stdout, stderr) =", "s = ('% Weka ARFF file\\n' + '% Generated automatically", "the data. cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename] +", "+= '@ATTRIBUTE %-30r %s\\n' % (fname, ftype) # Label attribute", "options (stdout, stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check", "Generated automatically by NLTK\\n' + '%% %s\\n\\n' % time.ctime()) #", "featuresets (dicts) or labelled featuresets which are tuples (featureset, label).", "self._fmt_arff_val(tok.get(fname)) s += '%s\\n' % self._fmt_arff_val(label) return s def _fmt_arff_val(self,", "ftype) != ftype: raise ValueError('Inconsistent type for %s' % fname)", "or labelled featuresets which are tuples (featureset, label). :param labeled:", "of weka does ' 'not support probability distribution ' 'output.')", "'weka.classifiers.rules.JRip', } @classmethod def train(cls, model_filename, featuresets, classifier='naivebayes', options=[], quiet=True):", "'-d', model_filename, '-t', train_filename] cmd += list(options) if quiet: stdout", "ValueError('Unhandled output format -- your version ' 'of weka may", "options): # Make sure we can find java & weka.", "@classmethod def train(cls, model_filename, featuresets, classifier='naivebayes', options=[], quiet=True): # Make", "# Call weka to classify the data. cmd = ['weka.classifiers.bayes.NaiveBayes',", "'/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath # Make sure java's", "in enumerate(lines): if line.strip().startswith(\"inst#\"): lines = lines[i:] break if lines[0].split()", "for line in lines[:10]: print(line) raise ValueError('Unhandled output format --", "fname, ftype in self._features: s += '@ATTRIBUTE %-30r %s\\n' %", "nltk.probability import DictionaryProbDist from nltk.internals import java, config_java from nltk.classify.api", "supported.\\n' ' Header: %s' % lines[0]) # [xx] full list", "token's value is a tuple or list. \"\"\" # Check", "not labeled: tokens = [(tok, None) for tok in tokens]", "re import zipfile from sys import stdin from nltk import", "'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', }", "zipfile from sys import stdin from nltk import compat from", "stderr=subprocess.PIPE) # Check if something went wrong: if stderr and", "return s def _fmt_arff_val(self, fval): if fval is None: return", "from nltk.classify.util import names_demo, binary_names_demo_features def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model', featuresets,", "\"\"\" :param labels: A list of all class labels that", "or list. \"\"\" # Check if the tokens are labeled", "line.strip()] # is this safe:? elif re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$',", "lines[1:] if line.strip()] elif lines[0].split() == ['inst#', 'actual', 'predicted', 'error',", "\"\"\" Classifiers that make use of the external 'Weka' package.", "import ClassifierI _weka_classpath = None _weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka',", "given data. Handles boolean, numeric and string (note: not nominal)", "% ftype) if features.get(fname, ftype) != ftype: raise ValueError('Inconsistent type", "be supported.\\n' ' Header: %s' % lines[0]) # [xx] full", "%s' % lines[0]) # [xx] full list of classifiers (some", "NLTK\\n' + '%% %s\\n\\n' % time.ctime()) # Relation name s", "labels, features): \"\"\" :param labels: A list of all class", "of classifiers (some may be abstract?): # ADTree, AODE, BayesNet,", "lines[1:] if line.strip()] # is this safe:? elif re.match(r'^0 \\w+", "NaiveBayesMultinomial, # NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression, PART, # PreConstructedLinearModel,", "None: continue # can't tell the type. else: raise ValueError('Unsupported", "raise ValueError('Unknown classifier %s' % classifier) # Train the weka", "= java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check if something went", "tuple or list. \"\"\" # Check if the tokens are", "(tok, label) in tokens) # Determine the types of all", "in stderr: raise ValueError('The installed version of weka does '", "a list of featuresets (dicts) or labelled featuresets which are", "os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')):", "\"\"\"Writes ARFF data to a file for the given data.\"\"\"", "in lines if line.strip()] else: for line in lines[:10]: print(line)", "zf.close() class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename): self._formatter = formatter", "self.header_section() + self.data_section(tokens) def labels(self): \"\"\"Returns the list of classes.\"\"\"", "= None _weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def", "make use of the external 'Weka' package. \"\"\" from __future__", "options: -distribution' in stderr: raise ValueError('The installed version of weka", "formatter = ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try: # Write the", "a string representation of ARFF output for the given data.\"\"\"", "fval else: return '%r' % fval if __name__ == '__main__':", "data.\"\"\" if not hasattr(outfile, 'write'): outfile = open(outfile, 'w') outfile.write(self.format(tokens))", "from nltk.internals import java, config_java from nltk.classify.api import ClassifierI _weka_classpath", "s += '@ATTRIBUTE %-30r {%s}\\n' % ('-label-', ','.join(self._labels)) return s", "Classifiers that make use of the external 'Weka' package. \"\"\"", "<http://nltk.org/> # For license information, see LICENSE.TXT \"\"\" Classifiers that", "Make sure we can find java & weka. config_weka() #", "package. \"\"\" from __future__ import print_function import time import tempfile", "'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod def train(cls, model_filename, featuresets, classifier='naivebayes',", "ftype); and ftype is an ARFF type string such as", "('-label-', ','.join(self._labels)) return s def data_section(self, tokens, labeled=None): \"\"\" Returns", "import time import tempfile import os import subprocess import re", "VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48',", "_weka_classpath is None: searchpath = _weka_search if 'WEKAHOME' in os.environ:", "issubclass(type(fval), (compat.integer_types, float, bool)): ftype = 'NUMERIC' elif issubclass(type(fval), compat.string_types):", "is None: continue # can't tell the type. else: raise", "'{True, False}' elif issubclass(type(fval), (compat.integer_types, float, bool)): ftype = 'NUMERIC'", "features = sorted(features.items()) return ARFF_Formatter(labels, features) def header_section(self): \"\"\"Returns an", "= classpath if _weka_classpath is None: searchpath = _weka_search if", "external 'Weka' package. \"\"\" from __future__ import print_function import time", "else: raise ValueError('Unsupported value type %r' % ftype) if features.get(fname,", "\"\"\" Returns the ARFF data section for the given data.", "s += '%s,' % self._fmt_arff_val(tok.get(fname)) s += '%s\\n' % self._fmt_arff_val(label)", "else: print('[Found Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is", "given data.\"\"\" if not hasattr(outfile, 'write'): outfile = open(outfile, 'w')", "global _weka_classpath # Make sure java's configured first. config_java() if", "string such as NUMERIC or STRING. \"\"\" self._labels = labels", "= zipfile.ZipFile(jar) except SystemExit as KeyboardInterrupt: raise except: return None", "(tok, label) in tokens: for fname, ftype in self._features: s", "if lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1]", "' 'or set the WEKAHOME environment variable. ' 'For more", "nltk import compat from nltk.probability import DictionaryProbDist from nltk.internals import", "lines): # Strip unwanted text from stdout for i,line in", "where each feature specification is a tuple (fname, ftype); and", "classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0']) def _classify_many(self, featuresets, options):", "support probability distribution ' 'output.') else: raise ValueError('Weka failed to", "sorted(features.items()) return ARFF_Formatter(labels, features) def header_section(self): \"\"\"Returns an ARFF header", "classifier='naivebayes', options=[], quiet=True): # Make sure we can find java", "weka to classify the data. cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model,", "raise ValueError('Weka failed to generate output:\\n%s' % stderr) # Parse", "s def _fmt_arff_val(self, fval): if fval is None: return '?'", "this safe:? elif re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]): return [line.split()[1]", "may not be supported.\\n' ' Header: %s' % lines[0]) #", "ARFF_Formatter: \"\"\" Converts featuresets and labeled featuresets to ARFF-formatted strings,", "['-p', '0', '-distribution']) def classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0'])", "'test.arff') self._formatter.write(test_filename, featuresets) # Call weka to classify the data.", "os.rmdir(temp_dir) class ARFF_Formatter: \"\"\" Converts featuresets and labeled featuresets to", "def format(self, tokens): \"\"\"Returns a string representation of ARFF output", "from_train(tokens): \"\"\" Constructs an ARFF_Formatter instance with class labels and", "s += '@ATTRIBUTE %-30r %s\\n' % (fname, ftype) # Label", "# Data section s = '\\n@DATA\\n' for (tok, label) in", "'/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath # Make", "except: return None try: try: return zf.read('weka/core/version.txt') except KeyError: return", "time.ctime()) # Relation name s += '@RELATION rel\\n\\n' # Input", "% fval if __name__ == '__main__': from nltk.classify.util import names_demo,", "test_filename] + options (stdout, stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "Indicates whether the given tokens are labeled or not. If", "SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI, # VotedPerceptron,", "PaceRegression, PART, # PreConstructedLinearModel, Prism, RandomForest, # RandomizableClassifier, RandomTree, RBFNetwork,", "or may be determined from data using ``from_train``. \"\"\" def", "searchpath.insert(0, os.environ['WEKAHOME']) for path in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath", "temp_dir = tempfile.mkdtemp() try: # Write the test data file.", "[line.split()[1] for line in lines if line.strip()] else: for line", "cls._CLASSIFIER_CLASS.values(): javaclass = classifier else: raise ValueError('Unknown classifier %s' %", "Write the training data file. train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename,", "= None java(cmd, classpath=_weka_classpath, stdout=stdout) # Return the new classifier.", "ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try: # Write the training data", "from the given data. Handles boolean, numeric and string (note:", "OneR, PaceRegression, PART, # PreConstructedLinearModel, Prism, RandomForest, # RandomizableClassifier, RandomTree,", "import stdin from nltk import compat from nltk.probability import DictionaryProbDist", "labels. labels = set(label for (tok, label) in tokens) #", "lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for", "string (note: not nominal) types. \"\"\" # Find the set", "['inst#', 'actual', 'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line in", "def config_weka(classpath=None): global _weka_classpath # Make sure java's configured first.", "ValueError('Weka failed to generate output:\\n%s' % stderr) # Parse weka's", "lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1] for", "import tempfile import os import subprocess import re import zipfile", "elif fval is None: continue # can't tell the type.", "labeled if the first token's value is a tuple or", "__init__(self, formatter, model_filename): self._formatter = formatter self._model = model_filename def", "stdout = None java(cmd, classpath=_weka_classpath, stdout=stdout) # Return the new", "'-l', self._model, '-T', test_filename] + options (stdout, stderr) = java(cmd,", "(some may be abstract?): # ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule,", "tokens and isinstance(tokens[0], (tuple, list)) if not labeled: tokens =", "LeastMedSq, LinearRegression, LMT, Logistic, # LogisticBase, M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner,", "%-30r %s\\n' % (fname, ftype) # Label attribute specification s", "the first token's value is a tuple or list. \"\"\"", "'0', '-distribution']) def classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0']) def", "lines[:10]: print(line) raise ValueError('Unhandled output format -- your version '", "weka. config_weka() # Build an ARFF formatter. formatter = ARFF_Formatter.from_train(featuresets)", "if features.get(fname, ftype) != ftype: raise ValueError('Inconsistent type for %s'", "Project # Author: <NAME> <<EMAIL>> # URL: <http://nltk.org/> # For", "to classify the data. cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T',", "in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass", "\"\"\" # Find the set of all attested labels. labels", "self._fmt_arff_val(label) return s def _fmt_arff_val(self, fval): if fval is None:", "from nltk.probability import DictionaryProbDist from nltk.internals import java, config_java from", "list of classes.\"\"\" return list(self._labels) def write(self, outfile, tokens): \"\"\"Writes", "value is a tuple or list. \"\"\" # Check if", "the given data.\"\"\" if not hasattr(outfile, 'write'): outfile = open(outfile,", "java, config_java from nltk.classify.api import ClassifierI _weka_classpath = None _weka_search", "os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs = [float(v) for v in", "REPTree, Ridor, # RuleNode, SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer, SMO, SMOreg,", "featuresets, classifier='naivebayes', options=[], quiet=True): # Make sure we can find", "features[fname] = ftype features = sorted(features.items()) return ARFF_Formatter(labels, features) def", "else: return '%r' % fval if __name__ == '__main__': from", "that make use of the external 'Weka' package. \"\"\" from", "compat.integer_types)): return '%s' % fval elif isinstance(fval, float): return '%r'", "'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod def train(cls,", "'%r' % fval if __name__ == '__main__': from nltk.classify.util import", "train(cls, model_filename, featuresets, classifier='naivebayes', options=[], quiet=True): # Make sure we", "# Write the test data file. test_filename = os.path.join(temp_dir, 'test.arff')", "'error', 'prediction']: return [line.split()[2].split(':')[1] for line in lines[1:] if line.strip()]", "_fmt_arff_val(self, fval): if fval is None: return '?' elif isinstance(fval,", "information, see LICENSE.TXT \"\"\" Classifiers that make use of the", "# Determine the types of all features. features = {}", "and not stdout: if 'Illegal options: -distribution' in stderr: raise", "first. config_java() if classpath is not None: _weka_classpath = classpath", "ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule, # DecisionStump, DecisionTable, HyperPipes, IB1,", "# Return the new classifier. return WekaClassifier(formatter, model_filename) finally: for", "# Build an ARFF formatter. formatter = ARFF_Formatter.from_train(featuresets) temp_dir =", "ftype) # Label attribute specification s += '@ATTRIBUTE %-30r {%s}\\n'", "version ' 'of weka may not be supported.\\n' ' Header:", "list(self._labels) def write(self, outfile, tokens): \"\"\"Writes ARFF data to a", "if labeled is None: labeled = tokens and isinstance(tokens[0], (tuple,", "if not labeled: tokens = [(tok, None) for tok in", "hasattr(outfile, 'write'): outfile = open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod def", "_weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global", "an ARFF formatter. formatter = ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp() try:", "or not. If None, then the tokens will be assumed", "the set of all attested labels. labels = set(label for", "%-30r {%s}\\n' % ('-label-', ','.join(self._labels)) return s def data_section(self, tokens,", "s += '%s\\n' % self._fmt_arff_val(label) return s def _fmt_arff_val(self, fval):", "% classifier) # Train the weka model. cmd = [javaclass,", "labeled or unlabeled. If unlabeled, # then use 'None' if", "parse_weka_distribution(self, s): probs = [float(v) for v in re.split('[*,]+', s)", "_check_weka_version(_weka_classpath) if _weka_classpath is None: raise LookupError('Unable to find weka.jar!", "_weka_classpath is None: raise LookupError('Unable to find weka.jar! Use config_weka()", "open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod def from_train(tokens): \"\"\" Constructs an", "or unlabeled. If unlabeled, # then use 'None' if labeled", "not nominal) types. \"\"\" # Find the set of all", "is a tuple or list. \"\"\" # Check if the", "= classifier else: raise ValueError('Unknown classifier %s' % classifier) #", "WEKAHOME environment variable. ' 'For more information about Weka, please", "probs = dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def parse_weka_output(self, lines): #", "sure we can find java & weka. config_weka() # Build", "= os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath) if version: print(('[Found Weka:", "labelled featuresets which are tuples (featureset, label). :param labeled: Indicates", "safe:? elif re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]): return [line.split()[1] for", "(C) 2001-2015 NLTK Project # Author: <NAME> <<EMAIL>> # URL:", "all features. features = {} for tok, label in tokens:", "_weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is None: raise LookupError('Unable to find", "are tuples (featureset, label). :param labeled: Indicates whether the given", "self._features: s += '%s,' % self._fmt_arff_val(tok.get(fname)) s += '%s\\n' %", "elif issubclass(type(fval), compat.string_types): ftype = 'STRING' elif fval is None:", "to be labeled if the first token's value is a", "'/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath # Make sure", "elif issubclass(type(fval), (compat.integer_types, float, bool)): ftype = 'NUMERIC' elif issubclass(type(fval),", "%s\\n' % (fname, ftype) # Label attribute specification s +=", "{} for tok, label in tokens: for (fname, fval) in", "in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs =", "re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]): return [line.split()[1] for line in", "outfile, tokens): \"\"\"Writes ARFF data to a file for the", "2001-2015 NLTK Project # Author: <NAME> <<EMAIL>> # URL: <http://nltk.org/>", "use 'None' if labeled is None: labeled = tokens and", "for (tok, label) in tokens) # Determine the types of", "of featuresets (dicts) or labelled featuresets which are tuples (featureset,", "= ('% Weka ARFF file\\n' + '% Generated automatically by", "fval) in tok.items(): if issubclass(type(fval), bool): ftype = '{True, False}'", "Use config_weka() ' 'or set the WEKAHOME environment variable. '", "'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line in lines[1:] if line.strip()] #", "else: raise ValueError('Unknown classifier %s' % classifier) # Train the", "If None, then the tokens will be assumed to be", "labeled = tokens and isinstance(tokens[0], (tuple, list)) if not labeled:", "False}' elif issubclass(type(fval), (compat.integer_types, float, bool)): ftype = 'NUMERIC' elif", "ZeroR _CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic',", "to a file for the given data.\"\"\" if not hasattr(outfile,", "ftype: raise ValueError('Inconsistent type for %s' % fname) features[fname] =", "ftype = '{True, False}' elif issubclass(type(fval), (compat.integer_types, float, bool)): ftype", "something went wrong: if stderr and not stdout: if 'Illegal", "\"\"\" self._labels = labels self._features = features def format(self, tokens):", "(note: not nominal) types. \"\"\" # Find the set of", "\\?\\s*$', lines[0]): return [line.split()[1] for line in lines if line.strip()]", "if line.strip()] elif lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'distribution']:", "went wrong: if stderr and not stdout: if 'Illegal options:", "'output.') else: raise ValueError('Weka failed to generate output:\\n%s' % stderr)", "For license information, see LICENSE.TXT \"\"\" Classifiers that make use", "def parse_weka_distribution(self, s): probs = [float(v) for v in re.split('[*,]+',", "not be supported.\\n' ' Header: %s' % lines[0]) # [xx]", "ConjunctiveRule, # DecisionStump, DecisionTable, HyperPipes, IB1, IBk, Id3, J48, #", "config_weka() ' 'or set the WEKAHOME environment variable. ' 'For", "self.data_section(tokens) def labels(self): \"\"\"Returns the list of classes.\"\"\" return list(self._labels)", "Constructs an ARFF_Formatter instance with class labels and feature types", "BayesNet, ComplementNaiveBayes, ConjunctiveRule, # DecisionStump, DecisionTable, HyperPipes, IB1, IBk, Id3,", "== '__main__': from nltk.classify.util import names_demo, binary_names_demo_features def make_classifier(featuresets): return", "'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper':", "fval is None: continue # can't tell the type. else:", "+ options (stdout, stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #", "output:\\n%s' % stderr) # Parse weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally:", "% (fname, ftype) # Label attribute specification s += '@ATTRIBUTE", "% lines[0]) # [xx] full list of classifiers (some may", "output for the given data.\"\"\" return self.header_section() + self.data_section(tokens) def", "'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype = 'STRING' elif fval is", "'%s\\n' % self._fmt_arff_val(label) return s def _fmt_arff_val(self, fval): if fval", "%r' % ftype) if features.get(fname, ftype) != ftype: raise ValueError('Inconsistent", "<reponame>wangyum/anaconda # Natural Language Toolkit: Interface to Weka Classsifiers #", "tell the type. else: raise ValueError('Unsupported value type %r' %", "list)) if not labeled: tokens = [(tok, None) for tok", "os import subprocess import re import zipfile from sys import", "print(line) raise ValueError('Unhandled output format -- your version ' 'of", "os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs = [float(v) for", "use of the external 'Weka' package. \"\"\" from __future__ import", "= tempfile.mkdtemp() try: # Write the test data file. test_filename", "that can be generated. :param features: A list of feature", "elif isinstance(fval, (bool, compat.integer_types)): return '%s' % fval elif isinstance(fval,", "file. train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if classifier in", "issubclass(type(fval), compat.string_types): ftype = 'STRING' elif fval is None: continue", "nltk.classify.api import ClassifierI _weka_classpath = None _weka_search = ['.', '/usr/share/weka',", "if 'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path in searchpath:", "wrong: if stderr and not stdout: if 'Illegal options: -distribution'", "float, bool)): ftype = 'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype =", "string.\"\"\" # Header comment. s = ('% Weka ARFF file\\n'", "if not hasattr(outfile, 'write'): outfile = open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close()", "return s def data_section(self, tokens, labeled=None): \"\"\" Returns the ARFF", "'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip',", "# Check if something went wrong: if stderr and not", "# Copyright (C) 2001-2015 NLTK Project # Author: <NAME> <<EMAIL>>", "(dicts) or labelled featuresets which are tuples (featureset, label). :param", "prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0', '-distribution']) def classify_many(self, featuresets):", "label). :param labeled: Indicates whether the given tokens are labeled", "tempfile import os import subprocess import re import zipfile from", "labels and feature types determined from the given data. Handles", "Write the test data file. test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename,", "# Label attribute specification s += '@ATTRIBUTE %-30r {%s}\\n' %", "data file. test_filename = os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) # Call", "may be abstract?): # ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule, #", "elif re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]): return [line.split()[1] for line", "label) in tokens) # Determine the types of all features.", "searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar') version =", "_weka_classpath = os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath) if version: print(('[Found", "format(self, tokens): \"\"\"Returns a string representation of ARFF output for", "+ self.data_section(tokens) def labels(self): \"\"\"Returns the list of classes.\"\"\" return", "for tok in tokens] # Data section s = '\\n@DATA\\n'", "fval if __name__ == '__main__': from nltk.classify.util import names_demo, binary_names_demo_features", "f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs = [float(v) for v", "format -- your version ' 'of weka may not be", "None _weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None):", "feature specifications, where each feature specification is a tuple (fname,", "can be generated. :param features: A list of feature specifications,", "def from_train(tokens): \"\"\" Constructs an ARFF_Formatter instance with class labels", "data section for the given data. :param tokens: a list", "return [line.split()[1] for line in lines if line.strip()] else: for", "subprocess import re import zipfile from sys import stdin from", "tokens will be assumed to be labeled if the first", "in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar') version", "types. \"\"\" # Find the set of all attested labels.", "+= '@RELATION rel\\n\\n' # Input attribute specifications for fname, ftype", "for line in lines if line.strip()] else: for line in", "= {} for tok, label in tokens: for (fname, fval)", "'%% %s\\n\\n' % time.ctime()) # Relation name s += '@RELATION", "lines if line.strip()] else: for line in lines[:10]: print(line) raise", "can be specified manually in the constructor, or may be", "of feature specifications, where each feature specification is a tuple", "string representation of ARFF output for the given data.\"\"\" return", "for (tok, label) in tokens: for fname, ftype in self._features:", "the training data file. train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets)", "attribute specification s += '@ATTRIBUTE %-30r {%s}\\n' % ('-label-', ','.join(self._labels))", "LMT, Logistic, # LogisticBase, M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial,", "ARFF_Formatter(labels, features) def header_section(self): \"\"\"Returns an ARFF header as a", "(fname, ftype) # Label attribute specification s += '@ATTRIBUTE %-30r", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check if something went wrong: if stderr", "# LogisticBase, M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple,", "labeled: tokens = [(tok, None) for tok in tokens] #", "== ['inst#', 'actual', 'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line", "DecisionTable, HyperPipes, IB1, IBk, Id3, J48, # JRip, KStar, LBR,", "classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check if something went wrong: if", "model_filename): self._formatter = formatter self._model = model_filename def prob_classify_many(self, featuresets):", "options=[], quiet=True): # Make sure we can find java &", "float): return '%r' % fval else: return '%r' % fval", "elif isinstance(fval, float): return '%r' % fval else: return '%r'", "= ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename] + options (stdout, stderr)", "in cls._CLASSIFIER_CLASS.values(): javaclass = classifier else: raise ValueError('Unknown classifier %s'", "be labeled if the first token's value is a tuple", "'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line in lines[1:] if line.strip()]", "which are tuples (featureset, label). :param labeled: Indicates whether the", "= [float(v) for v in re.split('[*,]+', s) if v.strip()] probs", "elif lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1])", "fval elif isinstance(fval, float): return '%r' % fval else: return", "A list of all class labels that can be generated.", "self._model, '-T', test_filename] + options (stdout, stderr) = java(cmd, classpath=_weka_classpath,", "' Header: %s' % lines[0]) # [xx] full list of", "MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple, NBTree, NNge, OneR,", "then use 'None' if labeled is None: labeled = tokens", "SystemExit as KeyboardInterrupt: raise except: return None try: try: return", "lines[0]): return [line.split()[1] for line in lines if line.strip()] else:", "labeled is None: labeled = tokens and isinstance(tokens[0], (tuple, list))", "return '%s' % fval elif isinstance(fval, float): return '%r' %", "the tokens are labeled or unlabeled. If unlabeled, # then", "header_section(self): \"\"\"Returns an ARFF header as a string.\"\"\" # Header", "classpath if _weka_classpath is None: searchpath = _weka_search if 'WEKAHOME'", "the weka model. cmd = [javaclass, '-d', model_filename, '-t', train_filename]", "def write(self, outfile, tokens): \"\"\"Writes ARFF data to a file", "not hasattr(outfile, 'write'): outfile = open(outfile, 'w') outfile.write(self.format(tokens)) outfile.close() @staticmethod", "import compat from nltk.probability import DictionaryProbDist from nltk.internals import java,", "PreConstructedLinearModel, Prism, RandomForest, # RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor, #", "to find weka.jar! Use config_weka() ' 'or set the WEKAHOME", "Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf =", "os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath) if version: print(('[Found Weka: %s", "distribution ' 'output.') else: raise ValueError('Weka failed to generate output:\\n%s'", "is this safe:? elif re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]): return", "stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check if something", "tempfile.mkdtemp() try: # Write the training data file. train_filename =", "with class labels and feature types determined from the given", "of all attested labels. labels = set(label for (tok, label)", "return '%r' % fval if __name__ == '__main__': from nltk.classify.util", "outfile.close() @staticmethod def from_train(tokens): \"\"\" Constructs an ARFF_Formatter instance with", "config_java from nltk.classify.api import ClassifierI _weka_classpath = None _weka_search =", "' 'not support probability distribution ' 'output.') else: raise ValueError('Weka", "javaclass = classifier else: raise ValueError('Unknown classifier %s' % classifier)", "version = _check_weka_version(_weka_classpath) if version: print(('[Found Weka: %s (version %s)]'", "determined from the given data. Handles boolean, numeric and string", "= sorted(features.items()) return ARFF_Formatter(labels, features) def header_section(self): \"\"\"Returns an ARFF", "list. \"\"\" # Check if the tokens are labeled or", "not stdout: if 'Illegal options: -distribution' in stderr: raise ValueError('The", "labels = set(label for (tok, label) in tokens) # Determine", "'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod def train(cls, model_filename, featuresets,", "features = {} for tok, label in tokens: for (fname,", "self._features: s += '@ATTRIBUTE %-30r %s\\n' % (fname, ftype) #", "SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI, # VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS", "' 'For more information about Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/')", "such as NUMERIC or STRING. \"\"\" self._labels = labels self._features", "= dict(zip(self._formatter.labels(), probs)) return DictionaryProbDist(probs) def parse_weka_output(self, lines): # Strip", "= features def format(self, tokens): \"\"\"Returns a string representation of", "all attested labels. labels = set(label for (tok, label) in", "Header comment. s = ('% Weka ARFF file\\n' + '%", "# is this safe:? elif re.match(r'^0 \\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]):", "file\\n' + '% Generated automatically by NLTK\\n' + '%% %s\\n\\n'", "Weka. Features and classes can be specified manually in the", "java's configured first. config_java() if classpath is not None: _weka_classpath", "line in lines[1:] if line.strip()] # is this safe:? elif", "Logistic, # LogisticBase, M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, #", "return zf.read('weka/core/version.txt') except KeyError: return None finally: zf.close() class WekaClassifier(ClassifierI):", "java(cmd, classpath=_weka_classpath, stdout=stdout) # Return the new classifier. return WekaClassifier(formatter,", "featuresets) if classifier in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier", "types of all features. features = {} for tok, label", "if __name__ == '__main__': from nltk.classify.util import names_demo, binary_names_demo_features def", "print_function import time import tempfile import os import subprocess import", "% fval elif isinstance(fval, float): return '%r' % fval else:", "# NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression, PART, # PreConstructedLinearModel, Prism,", "_CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm':", "<NAME> <<EMAIL>> # URL: <http://nltk.org/> # For license information, see", "ValueError('Unknown classifier %s' % classifier) # Train the weka model.", "{ 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar':", "new classifier. return WekaClassifier(formatter, model_filename) finally: for f in os.listdir(temp_dir):", "os.path.join(temp_dir, 'test.arff') self._formatter.write(test_filename, featuresets) # Call weka to classify the", "= formatter self._model = model_filename def prob_classify_many(self, featuresets): return self._classify_many(featuresets,", "first token's value is a tuple or list. \"\"\" #", "is None: return '?' elif isinstance(fval, (bool, compat.integer_types)): return '%s'", "cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values(): javaclass = classifier else: raise", "\"\"\" # Check if the tokens are labeled or unlabeled.", "manually in the constructor, or may be determined from data", "(tuple, list)) if not labeled: tokens = [(tok, None) for", "'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod def train(cls, model_filename,", ":param labels: A list of all class labels that can", "is None: labeled = tokens and isinstance(tokens[0], (tuple, list)) if", ":param tokens: a list of featuresets (dicts) or labelled featuresets", "{%s}\\n' % ('-label-', ','.join(self._labels)) return s def data_section(self, tokens, labeled=None):", "for v in re.split('[*,]+', s) if v.strip()] probs = dict(zip(self._formatter.labels(),", "and classes can be specified manually in the constructor, or", "of all features. features = {} for tok, label in", "stdout for i,line in enumerate(lines): if line.strip().startswith(\"inst#\"): lines = lines[i:]", "_weka_classpath # Make sure java's configured first. config_java() if classpath", "Header: %s' % lines[0]) # [xx] full list of classifiers", "tokens): \"\"\"Returns a string representation of ARFF output for the", "(stdout, stderr) = java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check if", "= _check_weka_version(_weka_classpath) if version: print(('[Found Weka: %s (version %s)]' %", "of the external 'Weka' package. \"\"\" from __future__ import print_function", "weka.jar! Use config_weka() ' 'or set the WEKAHOME environment variable.", "lines = lines[i:] break if lines[0].split() == ['inst#', 'actual', 'predicted',", "['-p', '0']) def _classify_many(self, featuresets, options): # Make sure we", "tuples (featureset, label). :param labeled: Indicates whether the given tokens", "zf.read('weka/core/version.txt') except KeyError: return None finally: zf.close() class WekaClassifier(ClassifierI): def", "please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf = zipfile.ZipFile(jar)", "tokens] # Data section s = '\\n@DATA\\n' for (tok, label)", "# Make sure we can find java & weka. config_weka()", "specifications for fname, ftype in self._features: s += '@ATTRIBUTE %-30r", "data file. train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if classifier", "WekaClassifier(ClassifierI): def __init__(self, formatter, model_filename): self._formatter = formatter self._model =", "instance with class labels and feature types determined from the", "attribute specifications for fname, ftype in self._features: s += '@ATTRIBUTE", "return DictionaryProbDist(probs) def parse_weka_output(self, lines): # Strip unwanted text from", "issubclass(type(fval), bool): ftype = '{True, False}' elif issubclass(type(fval), (compat.integer_types, float,", "None: raise LookupError('Unable to find weka.jar! Use config_weka() ' 'or", "== ['inst#', 'actual', 'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1] for line", "Author: <NAME> <<EMAIL>> # URL: <http://nltk.org/> # For license information,", "from data using ``from_train``. \"\"\" def __init__(self, labels, features): \"\"\"", "continue # can't tell the type. else: raise ValueError('Unsupported value", "for fname, ftype in self._features: s += '@ATTRIBUTE %-30r %s\\n'", "will be assumed to be labeled if the first token's", "Check if something went wrong: if stderr and not stdout:", "# MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression,", "unlabeled. If unlabeled, # then use 'None' if labeled is", "section s = '\\n@DATA\\n' for (tok, label) in tokens: for", "config_weka(classpath=None): global _weka_classpath # Make sure java's configured first. config_java()", "class labels that can be generated. :param features: A list", "try: try: return zf.read('weka/core/version.txt') except KeyError: return None finally: zf.close()", "'__main__': from nltk.classify.util import names_demo, binary_names_demo_features def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model',", "'For more information about Weka, please see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def", "Interface to Weka Classsifiers # # Copyright (C) 2001-2015 NLTK", "as KeyboardInterrupt: raise except: return None try: try: return zf.read('weka/core/version.txt')", "if _weka_classpath is None: searchpath = _weka_search if 'WEKAHOME' in", "IBk, Id3, J48, # JRip, KStar, LBR, LeastMedSq, LinearRegression, LMT,", "training data file. train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if", "specification is a tuple (fname, ftype); and ftype is an", "type %r' % ftype) if features.get(fname, ftype) != ftype: raise", "self._classify_many(featuresets, ['-p', '0']) def _classify_many(self, featuresets, options): # Make sure", "% _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is None: raise LookupError('Unable to", "temp_dir = tempfile.mkdtemp() try: # Write the training data file.", "'actual', 'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line in lines[1:]", "self._features = features def format(self, tokens): \"\"\"Returns a string representation", "stdout: if 'Illegal options: -distribution' in stderr: raise ValueError('The installed", "# For license information, see LICENSE.TXT \"\"\" Classifiers that make", "specified manually in the constructor, or may be determined from", "data. cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename] + options", "line.strip()] elif lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'distribution']: return", "constructor, or may be determined from data using ``from_train``. \"\"\"", "# Header comment. s = ('% Weka ARFF file\\n' +", "__name__ == '__main__': from nltk.classify.util import names_demo, binary_names_demo_features def make_classifier(featuresets):", "classify the data. cmd = ['weka.classifiers.bayes.NaiveBayes', '-l', self._model, '-T', test_filename]", "to ARFF-formatted strings, appropriate for input into Weka. Features and", "'None' if labeled is None: labeled = tokens and isinstance(tokens[0],", "import print_function import time import tempfile import os import subprocess", "DecisionStump, DecisionTable, HyperPipes, IB1, IBk, Id3, J48, # JRip, KStar,", "ftype features = sorted(features.items()) return ARFF_Formatter(labels, features) def header_section(self): \"\"\"Returns", "your version ' 'of weka may not be supported.\\n' '", "UserClassifier, VFI, # VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS = { 'naivebayes':", "in tokens) # Determine the types of all features. features", "automatically by NLTK\\n' + '%% %s\\n\\n' % time.ctime()) # Relation", "if line.strip()] # is this safe:? elif re.match(r'^0 \\w+ [01]\\.[0-9]*", "AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule, # DecisionStump, DecisionTable, HyperPipes, IB1, IBk,", "None: return '?' elif isinstance(fval, (bool, compat.integer_types)): return '%s' %", "else: stdout = None java(cmd, classpath=_weka_classpath, stdout=stdout) # Return the", "class labels and feature types determined from the given data.", "Classsifiers # # Copyright (C) 2001-2015 NLTK Project # Author:", "the types of all features. features = {} for tok,", "lines[i:] break if lines[0].split() == ['inst#', 'actual', 'predicted', 'error', 'prediction']:", "VFI, # VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS = { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes',", "the given data.\"\"\" return self.header_section() + self.data_section(tokens) def labels(self): \"\"\"Returns", "stderr and not stdout: if 'Illegal options: -distribution' in stderr:", "given data. :param tokens: a list of featuresets (dicts) or", "stderr) # Parse weka's output. return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f", "then the tokens will be assumed to be labeled if", "f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def parse_weka_distribution(self, s): probs", "fname) features[fname] = ftype features = sorted(features.items()) return ARFF_Formatter(labels, features)", "Call weka to classify the data. cmd = ['weka.classifiers.bayes.NaiveBayes', '-l',", "generated. :param features: A list of feature specifications, where each", "\"\"\" Constructs an ARFF_Formatter instance with class labels and feature", "= ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',] def config_weka(classpath=None): global _weka_classpath", "list of featuresets (dicts) or labelled featuresets which are tuples", "DictionaryProbDist from nltk.internals import java, config_java from nltk.classify.api import ClassifierI", "'predicted', 'error', 'distribution']: return [self.parse_weka_distribution(line.split()[-1]) for line in lines[1:] if", "# Find the set of all attested labels. labels =", "KeyError: return None finally: zf.close() class WekaClassifier(ClassifierI): def __init__(self, formatter,", "list of all class labels that can be generated. :param", "v in re.split('[*,]+', s) if v.strip()] probs = dict(zip(self._formatter.labels(), probs))", "= { 'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO',", "'0']) def _classify_many(self, featuresets, options): # Make sure we can", "types determined from the given data. Handles boolean, numeric and", "# Strip unwanted text from stdout for i,line in enumerate(lines):", "set(label for (tok, label) in tokens) # Determine the types", "bool): ftype = '{True, False}' elif issubclass(type(fval), (compat.integer_types, float, bool)):", "RandomTree, RBFNetwork, REPTree, Ridor, # RuleNode, SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer,", "PART, # PreConstructedLinearModel, Prism, RandomForest, # RandomizableClassifier, RandomTree, RBFNetwork, REPTree,", "labeled featuresets to ARFF-formatted strings, appropriate for input into Weka.", "except SystemExit as KeyboardInterrupt: raise except: return None try: try:", "the external 'Weka' package. \"\"\" from __future__ import print_function import", "None) for tok in tokens] # Data section s =", "' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf = zipfile.ZipFile(jar) except SystemExit", "try: # Write the test data file. test_filename = os.path.join(temp_dir,", "variable. ' 'For more information about Weka, please see '", "+= list(options) if quiet: stdout = subprocess.PIPE else: stdout =", "Make sure java's configured first. config_java() if classpath is not", "environment variable. ' 'For more information about Weka, please see", "self._model = model_filename def prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0',", "SimpleLogistic, # SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI, # VotedPerceptron, Winnow,", "model. cmd = [javaclass, '-d', model_filename, '-t', train_filename] cmd +=", "'-distribution']) def classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0']) def _classify_many(self,", "= '\\n@DATA\\n' for (tok, label) in tokens: for fname, ftype", "config_java() if classpath is not None: _weka_classpath = classpath if", "find java & weka. config_weka() temp_dir = tempfile.mkdtemp() try: #", "-distribution' in stderr: raise ValueError('The installed version of weka does", "can find java & weka. config_weka() # Build an ARFF", "we can find java & weka. config_weka() # Build an", "return self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir)", "classifiers (some may be abstract?): # ADTree, AODE, BayesNet, ComplementNaiveBayes,", "= _weka_search if 'WEKAHOME' in os.environ: searchpath.insert(0, os.environ['WEKAHOME']) for path", "try: return zf.read('weka/core/version.txt') except KeyError: return None finally: zf.close() class", "model_filename, '-t', train_filename] cmd += list(options) if quiet: stdout =", "configured first. config_java() if classpath is not None: _weka_classpath =", "MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression, PART,", "appropriate for input into Weka. Features and classes can be", "abstract?): # ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule, # DecisionStump, DecisionTable,", "(compat.integer_types, float, bool)): ftype = 'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype", "import zipfile from sys import stdin from nltk import compat", "model_filename def prob_classify_many(self, featuresets): return self._classify_many(featuresets, ['-p', '0', '-distribution']) def", "'STRING' elif fval is None: continue # can't tell the", "the constructor, or may be determined from data using ``from_train``.", "return self._classify_many(featuresets, ['-p', '0']) def _classify_many(self, featuresets, options): # Make", "\"\"\" Converts featuresets and labeled featuresets to ARFF-formatted strings, appropriate", "label in tokens: for (fname, fval) in tok.items(): if issubclass(type(fval),", "ARFF file\\n' + '% Generated automatically by NLTK\\n' + '%%", "'% Generated automatically by NLTK\\n' + '%% %s\\n\\n' % time.ctime())", "RBFNetwork, REPTree, Ridor, # RuleNode, SimpleLinearRegression, SimpleLogistic, # SingleClassifierEnhancer, SMO,", "tokens are labeled or not. If None, then the tokens", "# SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI, # VotedPerceptron, Winnow, ZeroR", "= 'STRING' elif fval is None: continue # can't tell", "ftype is an ARFF type string such as NUMERIC or", "import os import subprocess import re import zipfile from sys", "classifier in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier] elif classifier in cls._CLASSIFIER_CLASS.values():", "['inst#', 'actual', 'predicted', 'error', 'prediction']: return [line.split()[2].split(':')[1] for line in", "def train(cls, model_filename, featuresets, classifier='naivebayes', options=[], quiet=True): # Make sure", "NNge, OneR, PaceRegression, PART, # PreConstructedLinearModel, Prism, RandomForest, # RandomizableClassifier,", "& weka. config_weka() # Build an ARFF formatter. formatter =", "\"\"\"Returns a string representation of ARFF output for the given", "URL: <http://nltk.org/> # For license information, see LICENSE.TXT \"\"\" Classifiers", "LookupError('Unable to find weka.jar! Use config_weka() ' 'or set the", "None, then the tokens will be assumed to be labeled", "self._labels = labels self._features = features def format(self, tokens): \"\"\"Returns", "sure java's configured first. config_java() if classpath is not None:", "comment. s = ('% Weka ARFF file\\n' + '% Generated", "(featureset, label). :param labeled: Indicates whether the given tokens are", "section for the given data. :param tokens: a list of", "config_weka() temp_dir = tempfile.mkdtemp() try: # Write the test data", "a tuple or list. \"\"\" # Check if the tokens", "os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if classifier in cls._CLASSIFIER_CLASS: javaclass =", "Converts featuresets and labeled featuresets to ARFF-formatted strings, appropriate for", "to generate output:\\n%s' % stderr) # Parse weka's output. return", "lines[0]) # [xx] full list of classifiers (some may be", "STRING. \"\"\" self._labels = labels self._features = features def format(self,", "text from stdout for i,line in enumerate(lines): if line.strip().startswith(\"inst#\"): lines", "from sys import stdin from nltk import compat from nltk.probability", "[float(v) for v in re.split('[*,]+', s) if v.strip()] probs =", "data to a file for the given data.\"\"\" if not", "can find java & weka. config_weka() temp_dir = tempfile.mkdtemp() try:", "unwanted text from stdout for i,line in enumerate(lines): if line.strip().startswith(\"inst#\"):", "(fname, fval) in tok.items(): if issubclass(type(fval), bool): ftype = '{True,", "the given data. Handles boolean, numeric and string (note: not", "labeled=None): \"\"\" Returns the ARFF data section for the given", "os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) class ARFF_Formatter: \"\"\" Converts featuresets and", "_classify_many(self, featuresets, options): # Make sure we can find java", "_weka_classpath = None _weka_search = ['.', '/usr/share/weka', '/usr/local/share/weka', '/usr/lib/weka', '/usr/local/lib/weka',]", "return [self.parse_weka_distribution(line.split()[-1]) for line in lines[1:] if line.strip()] # is", "in lines[1:] if line.strip()] elif lines[0].split() == ['inst#', 'actual', 'predicted',", "def _check_weka_version(jar): try: zf = zipfile.ZipFile(jar) except SystemExit as KeyboardInterrupt:", "\\w+ [01]\\.[0-9]* \\?\\s*$', lines[0]): return [line.split()[1] for line in lines", "in lines[:10]: print(line) raise ValueError('Unhandled output format -- your version", "for path in searchpath: if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path,", "raise ValueError('Inconsistent type for %s' % fname) features[fname] = ftype", "def _classify_many(self, featuresets, options): # Make sure we can find", "subprocess.PIPE else: stdout = None java(cmd, classpath=_weka_classpath, stdout=stdout) # Return", "(fname, ftype); and ftype is an ARFF type string such", "in tokens: for (fname, fval) in tok.items(): if issubclass(type(fval), bool):", "in tok.items(): if issubclass(type(fval), bool): ftype = '{True, False}' elif", "in the constructor, or may be determined from data using", "# # Copyright (C) 2001-2015 NLTK Project # Author: <NAME>", "labeled or not. If None, then the tokens will be", "return '%r' % fval else: return '%r' % fval if", "[line.split()[2].split(':')[1] for line in lines[1:] if line.strip()] elif lines[0].split() ==", "are labeled or not. If None, then the tokens will", "names_demo, binary_names_demo_features def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model', featuresets, 'C4.5') classifier =", "compat from nltk.probability import DictionaryProbDist from nltk.internals import java, config_java", "if the tokens are labeled or unlabeled. If unlabeled, #", "Weka: %s]' % _weka_classpath) _check_weka_version(_weka_classpath) if _weka_classpath is None: raise", "weka. config_weka() temp_dir = tempfile.mkdtemp() try: # Write the test", "'naivebayes': 'weka.classifiers.bayes.NaiveBayes', 'C4.5': 'weka.classifiers.trees.J48', 'log_regression': 'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar',", "line.strip().startswith(\"inst#\"): lines = lines[i:] break if lines[0].split() == ['inst#', 'actual',", "ComplementNaiveBayes, ConjunctiveRule, # DecisionStump, DecisionTable, HyperPipes, IB1, IBk, Id3, J48,", "java(cmd, classpath=_weka_classpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Check if something went wrong:", "= '{True, False}' elif issubclass(type(fval), (compat.integer_types, float, bool)): ftype =", "None java(cmd, classpath=_weka_classpath, stdout=stdout) # Return the new classifier. return", "def _fmt_arff_val(self, fval): if fval is None: return '?' elif", "is a tuple (fname, ftype); and ftype is an ARFF", "LogisticBase, M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial, # NaiveBayesSimple, NBTree,", "if os.path.exists(os.path.join(path, 'weka.jar')): _weka_classpath = os.path.join(path, 'weka.jar') version = _check_weka_version(_weka_classpath)", "= 'NUMERIC' elif issubclass(type(fval), compat.string_types): ftype = 'STRING' elif fval", "version of weka does ' 'not support probability distribution '", "'train.arff') formatter.write(train_filename, featuresets) if classifier in cls._CLASSIFIER_CLASS: javaclass = cls._CLASSIFIER_CLASS[classifier]", "# DecisionStump, DecisionTable, HyperPipes, IB1, IBk, Id3, J48, # JRip,", "NBTree, NNge, OneR, PaceRegression, PART, # PreConstructedLinearModel, Prism, RandomForest, #", "ARFF output for the given data.\"\"\" return self.header_section() + self.data_section(tokens)", "raise ValueError('The installed version of weka does ' 'not support", "KStar, LBR, LeastMedSq, LinearRegression, LMT, Logistic, # LogisticBase, M5Base, MultilayerPerceptron,", "for the given data.\"\"\" return self.header_section() + self.data_section(tokens) def labels(self):", "SMO, SMOreg, UserClassifier, VFI, # VotedPerceptron, Winnow, ZeroR _CLASSIFIER_CLASS =", "+= '%s\\n' % self._fmt_arff_val(label) return s def _fmt_arff_val(self, fval): if", "tok.items(): if issubclass(type(fval), bool): ftype = '{True, False}' elif issubclass(type(fval),", "compat.string_types): ftype = 'STRING' elif fval is None: continue #", "'@ATTRIBUTE %-30r {%s}\\n' % ('-label-', ','.join(self._labels)) return s def data_section(self,", "from nltk.classify.api import ClassifierI _weka_classpath = None _weka_search = ['.',", "as a string.\"\"\" # Header comment. s = ('% Weka", "# Author: <NAME> <<EMAIL>> # URL: <http://nltk.org/> # For license", "in re.split('[*,]+', s) if v.strip()] probs = dict(zip(self._formatter.labels(), probs)) return", "train_filename = os.path.join(temp_dir, 'train.arff') formatter.write(train_filename, featuresets) if classifier in cls._CLASSIFIER_CLASS:", "parse_weka_output(self, lines): # Strip unwanted text from stdout for i,line", "from nltk import compat from nltk.probability import DictionaryProbDist from nltk.internals", "Build an ARFF formatter. formatter = ARFF_Formatter.from_train(featuresets) temp_dir = tempfile.mkdtemp()", "value type %r' % ftype) if features.get(fname, ftype) != ftype:", "(version %s)]' % (_weka_classpath, version))) else: print('[Found Weka: %s]' %", "(bool, compat.integer_types)): return '%s' % fval elif isinstance(fval, float): return", "'weka.jar') version = _check_weka_version(_weka_classpath) if version: print(('[Found Weka: %s (version", "if something went wrong: if stderr and not stdout: if", "into Weka. Features and classes can be specified manually in", "using ``from_train``. \"\"\" def __init__(self, labels, features): \"\"\" :param labels:", "boolean, numeric and string (note: not nominal) types. \"\"\" #", "try: # Write the training data file. train_filename = os.path.join(temp_dir,", "LinearRegression, LMT, Logistic, # LogisticBase, M5Base, MultilayerPerceptron, # MultipleClassifiersCombiner, NaiveBayes,", "'weka.classifiers.functions.Logistic', 'svm': 'weka.classifiers.functions.SMO', 'kstar': 'weka.classifiers.lazy.KStar', 'ripper': 'weka.classifiers.rules.JRip', } @classmethod def", "labels(self): \"\"\"Returns the list of classes.\"\"\" return list(self._labels) def write(self,", "a file for the given data.\"\"\" if not hasattr(outfile, 'write'):", "Find the set of all attested labels. labels = set(label", "in tokens] # Data section s = '\\n@DATA\\n' for (tok,", "if version: print(('[Found Weka: %s (version %s)]' % (_weka_classpath, version)))", "find weka.jar! Use config_weka() ' 'or set the WEKAHOME environment", "features def format(self, tokens): \"\"\"Returns a string representation of ARFF", "self._formatter = formatter self._model = model_filename def prob_classify_many(self, featuresets): return", "featuresets to ARFF-formatted strings, appropriate for input into Weka. Features", "outfile.write(self.format(tokens)) outfile.close() @staticmethod def from_train(tokens): \"\"\" Constructs an ARFF_Formatter instance", "Data section s = '\\n@DATA\\n' for (tok, label) in tokens:", "# RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor, # RuleNode, SimpleLinearRegression, SimpleLogistic,", "probs)) return DictionaryProbDist(probs) def parse_weka_output(self, lines): # Strip unwanted text", "formatter, model_filename): self._formatter = formatter self._model = model_filename def prob_classify_many(self,", "return WekaClassifier(formatter, model_filename) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f))", "None: _weka_classpath = classpath if _weka_classpath is None: searchpath =", "see ' 'http://www.cs.waikato.ac.nz/ml/weka/') def _check_weka_version(jar): try: zf = zipfile.ZipFile(jar) except", "try: zf = zipfile.ZipFile(jar) except SystemExit as KeyboardInterrupt: raise except:", "if line.strip()] else: for line in lines[:10]: print(line) raise ValueError('Unhandled", "tokens: a list of featuresets (dicts) or labelled featuresets which", "def make_classifier(featuresets): return WekaClassifier.train('/tmp/name.model', featuresets, 'C4.5') classifier = names_demo(make_classifier, binary_names_demo_features)", "if the first token's value is a tuple or list.", "probs = [float(v) for v in re.split('[*,]+', s) if v.strip()]", "a string.\"\"\" # Header comment. s = ('% Weka ARFF", "weka does ' 'not support probability distribution ' 'output.') else:", "all class labels that can be generated. :param features: A", "s = '\\n@DATA\\n' for (tok, label) in tokens: for fname,", "self.parse_weka_output(stdout.decode(stdin.encoding).split('\\n')) finally: for f in os.listdir(temp_dir): os.remove(os.path.join(temp_dir, f)) os.rmdir(temp_dir) def", "line in lines[1:] if line.strip()] elif lines[0].split() == ['inst#', 'actual',", "# Input attribute specifications for fname, ftype in self._features: s", "in lines[1:] if line.strip()] # is this safe:? elif re.match(r'^0", "# then use 'None' if labeled is None: labeled =", "for %s' % fname) features[fname] = ftype features = sorted(features.items())", "featuresets and labeled featuresets to ARFF-formatted strings, appropriate for input", "weka may not be supported.\\n' ' Header: %s' % lines[0])", "stdout=stdout) # Return the new classifier. return WekaClassifier(formatter, model_filename) finally:", "isinstance(fval, (bool, compat.integer_types)): return '%s' % fval elif isinstance(fval, float):", "sure we can find java & weka. config_weka() temp_dir =", "return self.header_section() + self.data_section(tokens) def labels(self): \"\"\"Returns the list of", "except KeyError: return None finally: zf.close() class WekaClassifier(ClassifierI): def __init__(self,", "'not support probability distribution ' 'output.') else: raise ValueError('Weka failed", "RandomForest, # RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor, # RuleNode, SimpleLinearRegression,", "# Write the training data file. train_filename = os.path.join(temp_dir, 'train.arff')", "NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression, PART, # PreConstructedLinearModel, Prism, RandomForest,", "fval is None: return '?' elif isinstance(fval, (bool, compat.integer_types)): return", "# can't tell the type. else: raise ValueError('Unsupported value type", "not. If None, then the tokens will be assumed to", "%s)]' % (_weka_classpath, version))) else: print('[Found Weka: %s]' % _weka_classpath)" ]
[ "# xnames = df.columns.tolist().remove(ylabel) yname = ylabel xnames = df.columns.tolist()", "def from_data(cls, filename, sep=\",\", labeled=True): \"\"\"Creates a DataSet from a", "def __len__(self): \"\"\"Returns the number of data points.\"\"\" return self.X.shape[0]", "np.var(data[:, i], axis=0) _maxs = np.max(data[:, i], axis=0) _mins =", "between 'df' and 'dict'.\") if dataset.hasLabel(): data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y),", "filename: The output file path :type filename: str :param sep:", "pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else: df = pd.DataFrame(self.X.copy(),", "return cls(X, Y) @classmethod def from_dataframe(cls, df, ylabel=None): \"\"\"Creates a", "{} if type(dataset.Y[0]) is str: for i in range(data.shape[1]-1): #ve", "} stats[columns[i]] = stat else: for i in range(data.shape[1]): #", "else: X = df.to_numpy() Y = None xnames = df.columns.tolist()", "None :type ylabel: [type], optional :return: [description] :rtype: [type] \"\"\"", "return self.X.shape[1] def getNumClasses(self): \"\"\"Returns the number of label classes", "_vars, \"max\": _maxs, \"min\": _mins } stats[columns[i]] = stat else:", "axis=0) _vars = np.var(data[:, i], axis=0) _maxs = np.max(data[:, i],", "= data Y = None return cls(X, Y) @classmethod def", "any data\") self.X = X self.Y = Y self.xnames =", "from_data(cls, filename, sep=\",\", labeled=True): \"\"\"Creates a DataSet from a data", "if yname else 'Y' @classmethod def from_data(cls, filename, sep=\",\", labeled=True):", "data file. :param filename: The filename :type filename: str :param", ":type dataset: si.data.Dataset :param format: Output format ('df':DataFrame, 'dict':dictionary ),", "= xnames if xnames else label_gen(X.shape[1]) self.yname = yname if", "(-1, 1))]) columns = dataset.xnames[:] + [dataset.yname] else: data =", "str, optional :return: A DataSet object :rtype: DataSet \"\"\" data", "format='df'): \"\"\" Returns the statistics of a dataset(mean, std, max,", "data Y = None return cls(X, Y) @classmethod def from_dataframe(cls,", "the dataset into a pandas DataFrame\"\"\" if self.hasLabel(): df =", "sep: str, optional \"\"\" fullds = np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename,", ":rtype: DataSet \"\"\" data = np.genfromtxt(filename, delimiter=sep) if labeled: X", "np.var(data, axis=0) # _maxs = np.max(data, axis=0) # _mins =", "\"\"\" if ylabel and ylabel in df.columns: X = df.loc[:,", "else: df = pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df def getXy(self): return", "= df.columns.tolist().remove(ylabel) yname = ylabel xnames = df.columns.tolist() for name", "= stat # _means = np.mean(data, axis=0) # _vars =", "== yname: xnames.remove(yname) else: X = df.to_numpy() Y = None", "sep=\",\"): \"\"\"Saves the dataset to a file :param filename: The", "optional :return: [description] :rtype: [type] \"\"\" if ylabel and ylabel", "#transforma num array de numpy Y = df.loc[:, ylabel].to_numpy() #", "ylabel: [type], optional :return: [description] :rtype: [type] \"\"\" if ylabel", ":type format: str, optional \"\"\" if format not in [\"df\",", "self.hasLabel(): df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else:", "axis=0) # _vars = np.var(data, axis=0) # _maxs = np.max(data,", "= None return cls(X, Y) @classmethod def from_dataframe(cls, df, ylabel=None):", "= np.var(data[:, i], axis=0) _maxs = np.max(data[:, i], axis=0) _mins", "X = df.loc[:, df.columns != ylabel].to_numpy() #transforma num array de", "[description] :type df: [type] :param ylabel: [description], defaults to None", "(a dependent variable)\"\"\" return self.Y is not None def getNumFeatures(self):", "+ [dataset.yname] else: data = dataset.X columns = dataset.xnames[:] stats", "\"\"\"Returns the number of features\"\"\" return self.X.shape[1] def getNumClasses(self): \"\"\"Returns", "dataset.hasLabel(): data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data = np.hstack([dataset.X, np.reshape(dataset.Y,", "_mins = np.min(data, axis=0) # stats = {} # for", "None): \"\"\" Tabular Dataset\"\"\" if X is None: raise Exception(\"Trying", "= {\"mean\": _means, \"var\": _vars, \"max\": _maxs, \"min\": _mins }", "def writeDataset(self, filename, sep=\",\"): \"\"\"Saves the dataset to a file", "= np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data = np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))])", "ve colunas _means = np.mean(data[:, i], axis=0) _vars = np.var(data[:,", "for i in range(data.shape[1]): # ve colunas _means = np.mean(data[:,", "dataset into a pandas DataFrame\"\"\" if self.hasLabel(): df = pd.DataFrame(np.hstack((self.X,", ":param sep: attributes separator, defaults to \",\" :type sep: str,", "a dataset(mean, std, max, min) :param dataset: A Dataset object", "to 'df' :type format: str, optional \"\"\" if format not", "the number of data points.\"\"\" return self.X.shape[0] def hasLabel(self): \"\"\"Returns", "from a pandas dataframe. :param df: [description] :type df: [type]", "dependent variable)\"\"\" return self.Y is not None def getNumFeatures(self): \"\"\"Returns", "Y = df.loc[:, ylabel].to_numpy() # xnames = df.columns.tolist().remove(ylabel) yname =", "\"min\": _mins } stats[columns[i]] = stat # _means = np.mean(data,", "df.columns.tolist() yname = None return cls(X, Y, xnames, yname) def", "dataset to a file :param filename: The output file path", "pandas dataframe. :param df: [description] :type df: [type] :param ylabel:", "= np.min(data, axis=0) # stats = {} # for i", "max, min) :param dataset: A Dataset object :type dataset: si.data.Dataset", "self.X.shape[0] def hasLabel(self): \"\"\"Returns True if the dataset constains labels", "delimiter=sep) def toDataframe(self): \"\"\" Converts the dataset into a pandas", "file :param filename: The output file path :type filename: str", "yname = ylabel xnames = df.columns.tolist() for name in xnames:", "ylabel].to_numpy() #transforma num array de numpy Y = df.loc[:, ylabel].to_numpy()", "range(data.shape[1]-1): #ve colunas _means = np.mean(data[:, i], axis=0) _vars =", "from src.si.util.util import label_gen __all__ = ['Dataset'] class Dataset: def", "= df.loc[:, ylabel].to_numpy() # xnames = df.columns.tolist().remove(ylabel) yname = ylabel", "= np.min(data[:, i], axis=0) stat = {\"mean\": _means, \"var\": _vars,", "return cls(X, Y, xnames, yname) def __len__(self): \"\"\"Returns the number", "= None): \"\"\" Tabular Dataset\"\"\" if X is None: raise", "dataset.xnames[:] + [dataset.yname] else: data = dataset.X columns = dataset.xnames[:]", "data\") self.X = X self.Y = Y self.xnames = xnames", ":type filename: str :param sep: attributes separator, defaults to \",\"", "label classes or 0 if the dataset has no dependent", "\"dict\"]: raise Exception(\"Invalid format. Choose between 'df' and 'dict'.\") if", "= {\"mean\": _means[i], # \"var\": _vars[i], # \"max\": _maxs[i], #", "Y = data[:, -1] else: X = data Y =", "i], axis=0) _vars = np.var(data[:, i], axis=0) _maxs = np.max(data[:,", "\"max\": _maxs, \"min\": _mins } stats[columns[i]] = stat else: for", "np.mean(data, axis=0) # _vars = np.var(data, axis=0) # _maxs =", "'df' and 'dict'.\") if dataset.hasLabel(): data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1)))", "[type] :param ylabel: [description], defaults to None :type ylabel: [type],", ":param ylabel: [description], defaults to None :type ylabel: [type], optional", "[type], optional :return: [description] :rtype: [type] \"\"\" if ylabel and", "Tabular Dataset\"\"\" if X is None: raise Exception(\"Trying to instanciate", "std, max, min) :param dataset: A Dataset object :type dataset:", "name in xnames: if name == yname: xnames.remove(yname) else: X", "defaults to \",\" :type sep: str, optional \"\"\" fullds =", "def getNumFeatures(self): \"\"\"Returns the number of features\"\"\" return self.X.shape[1] def", "self.Y is not None def getNumFeatures(self): \"\"\"Returns the number of", "_means, \"var\": _vars, \"max\": _maxs, \"min\": _mins } stats[columns[i]] =", "np.mean(data[:, i], axis=0) _vars = np.var(data[:, i], axis=0) _maxs =", "df.columns.tolist().remove(ylabel) yname = ylabel xnames = df.columns.tolist() for name in", "np from src.si.util.util import label_gen __all__ = ['Dataset'] class Dataset:", "Output format ('df':DataFrame, 'dict':dictionary ), defaults to 'df' :type format:", "the dataset to a file :param filename: The output file", "True if the dataset constains labels (a dependent variable)\"\"\" return", "X is None: raise Exception(\"Trying to instanciate a DataSet without", "if X is None: raise Exception(\"Trying to instanciate a DataSet", "if self.hasLabel() else 0 def writeDataset(self, filename, sep=\",\"): \"\"\"Saves the", "of features\"\"\" return self.X.shape[1] def getNumClasses(self): \"\"\"Returns the number of", "axis=0) _maxs = np.max(data[:, i], axis=0) _mins = np.min(data[:, i],", "# stats[columns[i]] = stat if format == \"dict\": return stats", "if self.hasLabel(): df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname)))", "'df' :type format: str, optional \"\"\" if format not in", "features\"\"\" return self.X.shape[1] def getNumClasses(self): \"\"\"Returns the number of label", "de numpy Y = df.loc[:, ylabel].to_numpy() # xnames = df.columns.tolist().remove(ylabel)", ":type filename: str :param sep: The fields separator, defaults to", "file. :param filename: The filename :type filename: str :param sep:", "# \"min\": _mins[i] # } # stats[columns[i]] = stat if", "0:-1] Y = data[:, -1] else: X = data Y", "columns = dataset.xnames[:] + [dataset.yname] else: data = dataset.X columns", "\"var\": _vars[i], # \"max\": _maxs[i], # \"min\": _mins[i] # }", "= {} # for i in range(data.shape[1]): # stat =", "columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else: df = pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df", "dataset has no dependent variable.\"\"\" return len(np.unique(self.Y)) if self.hasLabel() else", "\"\"\"Creates a DataSet from a pandas dataframe. :param df: [description]", "summary(dataset, format='df'): \"\"\" Returns the statistics of a dataset(mean, std,", "_vars[i], # \"max\": _maxs[i], # \"min\": _mins[i] # } #", "else 0 def writeDataset(self, filename, sep=\",\"): \"\"\"Saves the dataset to", "into a pandas DataFrame\"\"\" if self.hasLabel(): df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y),", "\"\"\"Returns the number of label classes or 0 if the", "stats = {} # for i in range(data.shape[1]): # stat", "= ['Dataset'] class Dataset: def __init__(self, X=None, Y=None, xnames: list", "'Y' @classmethod def from_data(cls, filename, sep=\",\", labeled=True): \"\"\"Creates a DataSet", "= df.columns.tolist() for name in xnames: if name == yname:", "X self.Y = Y self.xnames = xnames if xnames else", "def from_dataframe(cls, df, ylabel=None): \"\"\"Creates a DataSet from a pandas", "df.loc[:, df.columns != ylabel].to_numpy() #transforma num array de numpy Y", "_maxs = np.max(data, axis=0) # _mins = np.min(data, axis=0) #", "stat = {\"mean\": _means, \"var\": _vars, \"max\": _maxs, \"min\": _mins", "variable.\"\"\" return len(np.unique(self.Y)) if self.hasLabel() else 0 def writeDataset(self, filename,", "raise Exception(\"Invalid format. Choose between 'df' and 'dict'.\") if dataset.hasLabel():", "stats[columns[i]] = stat # _means = np.mean(data, axis=0) # _vars", "= dataset.xnames[:] stats = {} if type(dataset.Y[0]) is str: for", "_means = np.mean(data, axis=0) # _vars = np.var(data, axis=0) #", "df.loc[:, ylabel].to_numpy() # xnames = df.columns.tolist().remove(ylabel) yname = ylabel xnames", "axis=0) # _mins = np.min(data, axis=0) # stats = {}", "if the dataset has no dependent variable.\"\"\" return len(np.unique(self.Y)) if", "@classmethod def from_data(cls, filename, sep=\",\", labeled=True): \"\"\"Creates a DataSet from", "None, yname: str = None): \"\"\" Tabular Dataset\"\"\" if X", "X = df.to_numpy() Y = None xnames = df.columns.tolist() yname", "DataSet without any data\") self.X = X self.Y = Y", "return self.X, self.Y def summary(dataset, format='df'): \"\"\" Returns the statistics", ":return: A DataSet object :rtype: DataSet \"\"\" data = np.genfromtxt(filename,", "= df.columns.tolist() yname = None return cls(X, Y, xnames, yname)", "i in range(data.shape[1]): # stat = {\"mean\": _means[i], # \"var\":", "fullds, delimiter=sep) def toDataframe(self): \"\"\" Converts the dataset into a", "stat if format == \"dict\": return stats else: return pd.DataFrame(stats)", "ylabel=None): \"\"\"Creates a DataSet from a pandas dataframe. :param df:", "and 'dict'.\") if dataset.hasLabel(): data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data", "DataSet object :rtype: DataSet \"\"\" data = np.genfromtxt(filename, delimiter=sep) if", "getXy(self): return self.X, self.Y def summary(dataset, format='df'): \"\"\" Returns the", "np.genfromtxt(filename, delimiter=sep) if labeled: X = data[:, 0:-1] Y =", "number of label classes or 0 if the dataset has", "np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))]) columns = dataset.xnames[:] + [dataset.yname] else:", "A DataSet object :rtype: DataSet \"\"\" data = np.genfromtxt(filename, delimiter=sep)", "DataFrame\"\"\" if self.hasLabel(): df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames,", "= X self.Y = Y self.xnames = xnames if xnames", "for i in range(data.shape[1]-1): #ve colunas _means = np.mean(data[:, i],", "Exception(\"Invalid format. Choose between 'df' and 'dict'.\") if dataset.hasLabel(): data", "_maxs, \"min\": _mins } stats[columns[i]] = stat else: for i", "_maxs = np.max(data[:, i], axis=0) _mins = np.min(data[:, i], axis=0)", "# _means = np.mean(data, axis=0) # _vars = np.var(data, axis=0)", "in range(data.shape[1]): # ve colunas _means = np.mean(data[:, i], axis=0)", "Y=None, xnames: list = None, yname: str = None): \"\"\"", "the dataset constains labels (a dependent variable)\"\"\" return self.Y is", "self.yname))) else: df = pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df def getXy(self):", "\"\"\"Creates a DataSet from a data file. :param filename: The", "sep: The fields separator, defaults to \",\" :type sep: str,", "i in range(data.shape[1]-1): #ve colunas _means = np.mean(data[:, i], axis=0)", "sep=\",\", labeled=True): \"\"\"Creates a DataSet from a data file. :param", "statistics of a dataset(mean, std, max, min) :param dataset: A", "xnames: list = None, yname: str = None): \"\"\" Tabular", "Choose between 'df' and 'dict'.\") if dataset.hasLabel(): data = np.hstack((dataset.X,", "# ve colunas _means = np.mean(data[:, i], axis=0) _vars =", "('df':DataFrame, 'dict':dictionary ), defaults to 'df' :type format: str, optional", "class Dataset: def __init__(self, X=None, Y=None, xnames: list = None,", "stats = {} if type(dataset.Y[0]) is str: for i in", "number of features\"\"\" return self.X.shape[1] def getNumClasses(self): \"\"\"Returns the number", "df def getXy(self): return self.X, self.Y def summary(dataset, format='df'): \"\"\"", "as pd import numpy as np from src.si.util.util import label_gen", "points.\"\"\" return self.X.shape[0] def hasLabel(self): \"\"\"Returns True if the dataset", "as np from src.si.util.util import label_gen __all__ = ['Dataset'] class", "# _mins = np.min(data, axis=0) # stats = {} #", "of label classes or 0 if the dataset has no", "i in range(data.shape[1]): # ve colunas _means = np.mean(data[:, i],", "dataset constains labels (a dependent variable)\"\"\" return self.Y is not", "sep: attributes separator, defaults to \",\" :type sep: str, optional", "i], axis=0) _mins = np.min(data[:, i], axis=0) stat = {\"mean\":", "{\"mean\": _means[i], # \"var\": _vars[i], # \"max\": _maxs[i], # \"min\":", "[description] :rtype: [type] \"\"\" if ylabel and ylabel in df.columns:", "has no dependent variable.\"\"\" return len(np.unique(self.Y)) if self.hasLabel() else 0", "the number of label classes or 0 if the dataset", "A Dataset object :type dataset: si.data.Dataset :param format: Output format", "columns = dataset.xnames[:] stats = {} if type(dataset.Y[0]) is str:", "def getNumClasses(self): \"\"\"Returns the number of label classes or 0", "a DataSet without any data\") self.X = X self.Y =", "axis=0) # _maxs = np.max(data, axis=0) # _mins = np.min(data,", ":type sep: str, optional \"\"\" fullds = np.hstack((self.X, self.Y.reshape(len(self.Y), 1)))", "else label_gen(X.shape[1]) self.yname = yname if yname else 'Y' @classmethod", "None xnames = df.columns.tolist() yname = None return cls(X, Y,", "file path :type filename: str :param sep: The fields separator,", "\",\" :type sep: str, optional :return: A DataSet object :rtype:", "df.columns: X = df.loc[:, df.columns != ylabel].to_numpy() #transforma num array", "Y = None xnames = df.columns.tolist() yname = None return", ":param sep: The fields separator, defaults to \",\" :type sep:", ":param format: Output format ('df':DataFrame, 'dict':dictionary ), defaults to 'df'", "pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df def getXy(self): return self.X, self.Y def", "\",\" :type sep: str, optional \"\"\" fullds = np.hstack((self.X, self.Y.reshape(len(self.Y),", "data[:, -1] else: X = data Y = None return", "\"min\": _mins } stats[columns[i]] = stat else: for i in", "xnames.remove(yname) else: X = df.to_numpy() Y = None xnames =", "dataset.X columns = dataset.xnames[:] stats = {} if type(dataset.Y[0]) is", "__all__ = ['Dataset'] class Dataset: def __init__(self, X=None, Y=None, xnames:", "name == yname: xnames.remove(yname) else: X = df.to_numpy() Y =", "dataset: A Dataset object :type dataset: si.data.Dataset :param format: Output", "\"\"\" Returns the statistics of a dataset(mean, std, max, min)", "'dict'.\") if dataset.hasLabel(): data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data =", "filename, sep=\",\"): \"\"\"Saves the dataset to a file :param filename:", "df.to_numpy() Y = None xnames = df.columns.tolist() yname = None", "self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else: df = pd.DataFrame(self.X.copy(), columns=self.xnames[:])", "src.si.util.util import label_gen __all__ = ['Dataset'] class Dataset: def __init__(self,", "numpy as np from src.si.util.util import label_gen __all__ = ['Dataset']", "Dataset object :type dataset: si.data.Dataset :param format: Output format ('df':DataFrame,", "xnames = df.columns.tolist() for name in xnames: if name ==", "self.Y def summary(dataset, format='df'): \"\"\" Returns the statistics of a", "'dict':dictionary ), defaults to 'df' :type format: str, optional \"\"\"", "label_gen __all__ = ['Dataset'] class Dataset: def __init__(self, X=None, Y=None,", "self.Y = Y self.xnames = xnames if xnames else label_gen(X.shape[1])", "from a data file. :param filename: The filename :type filename:", "the statistics of a dataset(mean, std, max, min) :param dataset:", "ylabel and ylabel in df.columns: X = df.loc[:, df.columns !=", "str :param sep: attributes separator, defaults to \",\" :type sep:", "min) :param dataset: A Dataset object :type dataset: si.data.Dataset :param", "= np.mean(data[:, i], axis=0) _vars = np.var(data[:, i], axis=0) _maxs", "labeled=True): \"\"\"Creates a DataSet from a data file. :param filename:", "label_gen(X.shape[1]) self.yname = yname if yname else 'Y' @classmethod def", "# _vars = np.var(data, axis=0) # _maxs = np.max(data, axis=0)", "range(data.shape[1]): # stat = {\"mean\": _means[i], # \"var\": _vars[i], #", "1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else: df = pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return", "to \",\" :type sep: str, optional :return: A DataSet object", "filename: The filename :type filename: str :param sep: attributes separator,", "from_dataframe(cls, df, ylabel=None): \"\"\"Creates a DataSet from a pandas dataframe.", "df = pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df def getXy(self): return self.X,", "is str: for i in range(data.shape[1]-1): #ve colunas _means =", "stat else: for i in range(data.shape[1]): # ve colunas _means", "variable)\"\"\" return self.Y is not None def getNumFeatures(self): \"\"\"Returns the", "self.X = X self.Y = Y self.xnames = xnames if", "defaults to \",\" :type sep: str, optional :return: A DataSet", "xnames = df.columns.tolist().remove(ylabel) yname = ylabel xnames = df.columns.tolist() for", "= np.genfromtxt(filename, delimiter=sep) if labeled: X = data[:, 0:-1] Y", ":return: [description] :rtype: [type] \"\"\" if ylabel and ylabel in", "dataset: si.data.Dataset :param format: Output format ('df':DataFrame, 'dict':dictionary ), defaults", "_vars, \"max\": _maxs, \"min\": _mins } stats[columns[i]] = stat #", "filename: str :param sep: attributes separator, defaults to \",\" :type", "labeled: X = data[:, 0:-1] Y = data[:, -1] else:", "pandas as pd import numpy as np from src.si.util.util import", "def __init__(self, X=None, Y=None, xnames: list = None, yname: str", "\"\"\"Saves the dataset to a file :param filename: The output", "# stats = {} # for i in range(data.shape[1]): #", "_maxs, \"min\": _mins } stats[columns[i]] = stat # _means =", "-1] else: X = data Y = None return cls(X,", "a DataSet from a pandas dataframe. :param df: [description] :type", "num array de numpy Y = df.loc[:, ylabel].to_numpy() # xnames", ":param df: [description] :type df: [type] :param ylabel: [description], defaults", "_mins } stats[columns[i]] = stat # _means = np.mean(data, axis=0)", "), defaults to 'df' :type format: str, optional \"\"\" if", "a data file. :param filename: The filename :type filename: str", "data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data = np.hstack([dataset.X, np.reshape(dataset.Y, (-1,", "\"max\": _maxs[i], # \"min\": _mins[i] # } # stats[columns[i]] =", "= np.mean(data, axis=0) # _vars = np.var(data, axis=0) # _maxs", "xnames else label_gen(X.shape[1]) self.yname = yname if yname else 'Y'", "xnames: if name == yname: xnames.remove(yname) else: X = df.to_numpy()", "stat # _means = np.mean(data, axis=0) # _vars = np.var(data,", "Dataset: def __init__(self, X=None, Y=None, xnames: list = None, yname:", "dependent variable.\"\"\" return len(np.unique(self.Y)) if self.hasLabel() else 0 def writeDataset(self,", "= np.max(data, axis=0) # _mins = np.min(data, axis=0) # stats", "def hasLabel(self): \"\"\"Returns True if the dataset constains labels (a", "to instanciate a DataSet without any data\") self.X = X", "not None def getNumFeatures(self): \"\"\"Returns the number of features\"\"\" return", "format: str, optional \"\"\" if format not in [\"df\", \"dict\"]:", "path :type filename: str :param sep: The fields separator, defaults", "defaults to None :type ylabel: [type], optional :return: [description] :rtype:", "np.savetxt(filename, fullds, delimiter=sep) def toDataframe(self): \"\"\" Converts the dataset into", "def summary(dataset, format='df'): \"\"\" Returns the statistics of a dataset(mean,", "Returns the statistics of a dataset(mean, std, max, min) :param", "dataset.Y.reshape(len(dataset.Y), 1))) #data = np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))]) columns =", ":rtype: [type] \"\"\" if ylabel and ylabel in df.columns: X", "stat = {\"mean\": _means[i], # \"var\": _vars[i], # \"max\": _maxs[i],", "numpy Y = df.loc[:, ylabel].to_numpy() # xnames = df.columns.tolist().remove(ylabel) yname", "axis=0) # stats = {} # for i in range(data.shape[1]):", "df: [type] :param ylabel: [description], defaults to None :type ylabel:", "\"\"\"Returns the number of data points.\"\"\" return self.X.shape[0] def hasLabel(self):", "= data[:, 0:-1] Y = data[:, -1] else: X =", "defaults to 'df' :type format: str, optional \"\"\" if format", "# } # stats[columns[i]] = stat if format == \"dict\":", "for i in range(data.shape[1]): # stat = {\"mean\": _means[i], #", "raise Exception(\"Trying to instanciate a DataSet without any data\") self.X", "_means[i], # \"var\": _vars[i], # \"max\": _maxs[i], # \"min\": _mins[i]", "str, optional \"\"\" fullds = np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds,", "The fields separator, defaults to \",\" :type sep: str, optional", "cls(X, Y, xnames, yname) def __len__(self): \"\"\"Returns the number of", "yname = None return cls(X, Y, xnames, yname) def __len__(self):", "if name == yname: xnames.remove(yname) else: X = df.to_numpy() Y", "i], axis=0) stat = {\"mean\": _means, \"var\": _vars, \"max\": _maxs,", "#columns=np.hstack((self.xnames, self.yname))) else: df = pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df def", "else: data = dataset.X columns = dataset.xnames[:] stats = {}", "= np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))]) columns = dataset.xnames[:] + [dataset.yname]", "to a file :param filename: The output file path :type", "def getXy(self): return self.X, self.Y def summary(dataset, format='df'): \"\"\" Returns", "_mins } stats[columns[i]] = stat else: for i in range(data.shape[1]):", "yname: str = None): \"\"\" Tabular Dataset\"\"\" if X is", "@classmethod def from_dataframe(cls, df, ylabel=None): \"\"\"Creates a DataSet from a", "object :type dataset: si.data.Dataset :param format: Output format ('df':DataFrame, 'dict':dictionary", "pd import numpy as np from src.si.util.util import label_gen __all__", "= None, yname: str = None): \"\"\" Tabular Dataset\"\"\" if", "Y) @classmethod def from_dataframe(cls, df, ylabel=None): \"\"\"Creates a DataSet from", "} # stats[columns[i]] = stat if format == \"dict\": return", "optional :return: A DataSet object :rtype: DataSet \"\"\" data =", "format not in [\"df\", \"dict\"]: raise Exception(\"Invalid format. Choose between", "0 def writeDataset(self, filename, sep=\",\"): \"\"\"Saves the dataset to a", "data = dataset.X columns = dataset.xnames[:] stats = {} if", "if labeled: X = data[:, 0:-1] Y = data[:, -1]", "self.hasLabel() else 0 def writeDataset(self, filename, sep=\",\"): \"\"\"Saves the dataset", "return len(np.unique(self.Y)) if self.hasLabel() else 0 def writeDataset(self, filename, sep=\",\"):", "DataSet from a data file. :param filename: The filename :type", "_mins[i] # } # stats[columns[i]] = stat if format ==", "np.reshape(dataset.Y, (-1, 1))]) columns = dataset.xnames[:] + [dataset.yname] else: data", "['Dataset'] class Dataset: def __init__(self, X=None, Y=None, xnames: list =", "classes or 0 if the dataset has no dependent variable.\"\"\"", "import label_gen __all__ = ['Dataset'] class Dataset: def __init__(self, X=None,", "[\"df\", \"dict\"]: raise Exception(\"Invalid format. Choose between 'df' and 'dict'.\")", "of a dataset(mean, std, max, min) :param dataset: A Dataset", "format. Choose between 'df' and 'dict'.\") if dataset.hasLabel(): data =", "Dataset\"\"\" if X is None: raise Exception(\"Trying to instanciate a", "self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds, delimiter=sep) def toDataframe(self): \"\"\" Converts the", "type(dataset.Y[0]) is str: for i in range(data.shape[1]-1): #ve colunas _means", "ylabel xnames = df.columns.tolist() for name in xnames: if name", "ylabel in df.columns: X = df.loc[:, df.columns != ylabel].to_numpy() #transforma", "colunas _means = np.mean(data[:, i], axis=0) _vars = np.var(data[:, i],", "in xnames: if name == yname: xnames.remove(yname) else: X =", "and ylabel in df.columns: X = df.loc[:, df.columns != ylabel].to_numpy()", "xnames, yname) def __len__(self): \"\"\"Returns the number of data points.\"\"\"", "return self.X.shape[0] def hasLabel(self): \"\"\"Returns True if the dataset constains", "Y, xnames, yname) def __len__(self): \"\"\"Returns the number of data", "Converts the dataset into a pandas DataFrame\"\"\" if self.hasLabel(): df", "DataSet \"\"\" data = np.genfromtxt(filename, delimiter=sep) if labeled: X =", "return self.Y is not None def getNumFeatures(self): \"\"\"Returns the number", "!= ylabel].to_numpy() #transforma num array de numpy Y = df.loc[:,", "a DataSet from a data file. :param filename: The filename", "= dataset.xnames[:] + [dataset.yname] else: data = dataset.X columns =", "if the dataset constains labels (a dependent variable)\"\"\" return self.Y", "{} # for i in range(data.shape[1]): # stat = {\"mean\":", "getNumFeatures(self): \"\"\"Returns the number of features\"\"\" return self.X.shape[1] def getNumClasses(self):", "\"max\": _maxs, \"min\": _mins } stats[columns[i]] = stat # _means", "else: for i in range(data.shape[1]): # ve colunas _means =", "_vars = np.var(data, axis=0) # _maxs = np.max(data, axis=0) #", "in [\"df\", \"dict\"]: raise Exception(\"Invalid format. Choose between 'df' and", "Exception(\"Trying to instanciate a DataSet without any data\") self.X =", "len(np.unique(self.Y)) if self.hasLabel() else 0 def writeDataset(self, filename, sep=\",\"): \"\"\"Saves", "in range(data.shape[1]-1): #ve colunas _means = np.mean(data[:, i], axis=0) _vars", "np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds, delimiter=sep) def toDataframe(self): \"\"\" Converts", "np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data = np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))]) columns", "= np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds, delimiter=sep) def toDataframe(self): \"\"\"", "= yname if yname else 'Y' @classmethod def from_data(cls, filename,", "df.columns != ylabel].to_numpy() #transforma num array de numpy Y =", "\"min\": _mins[i] # } # stats[columns[i]] = stat if format", "self.yname = yname if yname else 'Y' @classmethod def from_data(cls,", "optional \"\"\" if format not in [\"df\", \"dict\"]: raise Exception(\"Invalid", "= np.max(data[:, i], axis=0) _mins = np.min(data[:, i], axis=0) stat", "writeDataset(self, filename, sep=\",\"): \"\"\"Saves the dataset to a file :param", "data points.\"\"\" return self.X.shape[0] def hasLabel(self): \"\"\"Returns True if the", "filename, sep=\",\", labeled=True): \"\"\"Creates a DataSet from a data file.", "\"\"\" if format not in [\"df\", \"dict\"]: raise Exception(\"Invalid format.", "a file :param filename: The output file path :type filename:", "xnames = df.columns.tolist() yname = None return cls(X, Y, xnames,", ":param filename: The output file path :type filename: str :param", "\"\"\" fullds = np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds, delimiter=sep) def", "object :rtype: DataSet \"\"\" data = np.genfromtxt(filename, delimiter=sep) if labeled:", "pandas DataFrame\"\"\" if self.hasLabel(): df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname])", "fullds = np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds, delimiter=sep) def toDataframe(self):", "str, optional \"\"\" if format not in [\"df\", \"dict\"]: raise", "is not None def getNumFeatures(self): \"\"\"Returns the number of features\"\"\"", "= None xnames = df.columns.tolist() yname = None return cls(X,", "else: X = data Y = None return cls(X, Y)", "= Y self.xnames = xnames if xnames else label_gen(X.shape[1]) self.yname", "The filename :type filename: str :param sep: attributes separator, defaults", "data = np.genfromtxt(filename, delimiter=sep) if labeled: X = data[:, 0:-1]", "no dependent variable.\"\"\" return len(np.unique(self.Y)) if self.hasLabel() else 0 def", "to \",\" :type sep: str, optional \"\"\" fullds = np.hstack((self.X,", "_means = np.mean(data[:, i], axis=0) _vars = np.var(data[:, i], axis=0)", "DataSet from a pandas dataframe. :param df: [description] :type df:", "np.max(data[:, i], axis=0) _mins = np.min(data[:, i], axis=0) stat =", "yname: xnames.remove(yname) else: X = df.to_numpy() Y = None xnames", "attributes separator, defaults to \",\" :type sep: str, optional :return:", "dataset(mean, std, max, min) :param dataset: A Dataset object :type", "= dataset.X columns = dataset.xnames[:] stats = {} if type(dataset.Y[0])", "1))) #data = np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))]) columns = dataset.xnames[:]", "a pandas dataframe. :param df: [description] :type df: [type] :param", "{\"mean\": _means, \"var\": _vars, \"max\": _maxs, \"min\": _mins } stats[columns[i]]", "# _maxs = np.max(data, axis=0) # _mins = np.min(data, axis=0)", "[description], defaults to None :type ylabel: [type], optional :return: [description]", "def toDataframe(self): \"\"\" Converts the dataset into a pandas DataFrame\"\"\"", "xnames if xnames else label_gen(X.shape[1]) self.yname = yname if yname", "instanciate a DataSet without any data\") self.X = X self.Y", "= df.loc[:, df.columns != ylabel].to_numpy() #transforma num array de numpy", "= data[:, -1] else: X = data Y = None", "for name in xnames: if name == yname: xnames.remove(yname) else:", "df, ylabel=None): \"\"\"Creates a DataSet from a pandas dataframe. :param", "if dataset.hasLabel(): data = np.hstack((dataset.X, dataset.Y.reshape(len(dataset.Y), 1))) #data = np.hstack([dataset.X,", "Y = None return cls(X, Y) @classmethod def from_dataframe(cls, df,", "None return cls(X, Y, xnames, yname) def __len__(self): \"\"\"Returns the", "# for i in range(data.shape[1]): # stat = {\"mean\": _means[i],", "list = None, yname: str = None): \"\"\" Tabular Dataset\"\"\"", "a pandas DataFrame\"\"\" if self.hasLabel(): df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))),", "str :param sep: The fields separator, defaults to \",\" :type", ":param filename: The filename :type filename: str :param sep: attributes", "= np.var(data, axis=0) # _maxs = np.max(data, axis=0) # _mins", "= stat if format == \"dict\": return stats else: return", "filename :type filename: str :param sep: attributes separator, defaults to", "np.min(data, axis=0) # stats = {} # for i in", "ylabel: [description], defaults to None :type ylabel: [type], optional :return:", "# stat = {\"mean\": _means[i], # \"var\": _vars[i], # \"max\":", "[type] \"\"\" if ylabel and ylabel in df.columns: X =", "without any data\") self.X = X self.Y = Y self.xnames", "constains labels (a dependent variable)\"\"\" return self.Y is not None", "str: for i in range(data.shape[1]-1): #ve colunas _means = np.mean(data[:,", "yname if yname else 'Y' @classmethod def from_data(cls, filename, sep=\",\",", "if format not in [\"df\", \"dict\"]: raise Exception(\"Invalid format. Choose", "columns=self.xnames[:]) return df def getXy(self): return self.X, self.Y def summary(dataset,", "[dataset.yname] else: data = dataset.X columns = dataset.xnames[:] stats =", "__init__(self, X=None, Y=None, xnames: list = None, yname: str =", "_maxs[i], # \"min\": _mins[i] # } # stats[columns[i]] = stat", "yname) def __len__(self): \"\"\"Returns the number of data points.\"\"\" return", "si.data.Dataset :param format: Output format ('df':DataFrame, 'dict':dictionary ), defaults to", "= stat else: for i in range(data.shape[1]): # ve colunas", "number of data points.\"\"\" return self.X.shape[0] def hasLabel(self): \"\"\"Returns True", "= pd.DataFrame(self.X.copy(), columns=self.xnames[:]) return df def getXy(self): return self.X, self.Y", "i], axis=0) _maxs = np.max(data[:, i], axis=0) _mins = np.min(data[:,", "# \"max\": _maxs[i], # \"min\": _mins[i] # } # stats[columns[i]]", "df: [description] :type df: [type] :param ylabel: [description], defaults to", "_mins = np.min(data[:, i], axis=0) stat = {\"mean\": _means, \"var\":", "\"\"\"Returns True if the dataset constains labels (a dependent variable)\"\"\"", "X = data Y = None return cls(X, Y) @classmethod", "self.X.shape[1] def getNumClasses(self): \"\"\"Returns the number of label classes or", ":type df: [type] :param ylabel: [description], defaults to None :type", ":type ylabel: [type], optional :return: [description] :rtype: [type] \"\"\" if", "= {} if type(dataset.Y[0]) is str: for i in range(data.shape[1]-1):", "data[:, 0:-1] Y = data[:, -1] else: X = data", "yname else 'Y' @classmethod def from_data(cls, filename, sep=\",\", labeled=True): \"\"\"Creates", "_vars = np.var(data[:, i], axis=0) _maxs = np.max(data[:, i], axis=0)", "import numpy as np from src.si.util.util import label_gen __all__ =", "getNumClasses(self): \"\"\"Returns the number of label classes or 0 if", "# \"var\": _vars[i], # \"max\": _maxs[i], # \"min\": _mins[i] #", "to None :type ylabel: [type], optional :return: [description] :rtype: [type]", "X=None, Y=None, xnames: list = None, yname: str = None):", "cls(X, Y) @classmethod def from_dataframe(cls, df, ylabel=None): \"\"\"Creates a DataSet", "dataframe. :param df: [description] :type df: [type] :param ylabel: [description],", "toDataframe(self): \"\"\" Converts the dataset into a pandas DataFrame\"\"\" if", "1))) np.savetxt(filename, fullds, delimiter=sep) def toDataframe(self): \"\"\" Converts the dataset", "df = pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else: df", "not in [\"df\", \"dict\"]: raise Exception(\"Invalid format. Choose between 'df'", "__len__(self): \"\"\"Returns the number of data points.\"\"\" return self.X.shape[0] def", "np.min(data[:, i], axis=0) stat = {\"mean\": _means, \"var\": _vars, \"max\":", "in range(data.shape[1]): # stat = {\"mean\": _means[i], # \"var\": _vars[i],", "The output file path :type filename: str :param sep: The", "= None return cls(X, Y, xnames, yname) def __len__(self): \"\"\"Returns", "\"var\": _vars, \"max\": _maxs, \"min\": _mins } stats[columns[i]] = stat", "if ylabel and ylabel in df.columns: X = df.loc[:, df.columns", "str = None): \"\"\" Tabular Dataset\"\"\" if X is None:", "} stats[columns[i]] = stat # _means = np.mean(data, axis=0) #", "is None: raise Exception(\"Trying to instanciate a DataSet without any", "0 if the dataset has no dependent variable.\"\"\" return len(np.unique(self.Y))", "format ('df':DataFrame, 'dict':dictionary ), defaults to 'df' :type format: str,", "np.max(data, axis=0) # _mins = np.min(data, axis=0) # stats =", "optional \"\"\" fullds = np.hstack((self.X, self.Y.reshape(len(self.Y), 1))) np.savetxt(filename, fullds, delimiter=sep)", "#data = np.hstack([dataset.X, np.reshape(dataset.Y, (-1, 1))]) columns = dataset.xnames[:] +", "Y self.xnames = xnames if xnames else label_gen(X.shape[1]) self.yname =", "the number of features\"\"\" return self.X.shape[1] def getNumClasses(self): \"\"\"Returns the", "or 0 if the dataset has no dependent variable.\"\"\" return", "if type(dataset.Y[0]) is str: for i in range(data.shape[1]-1): #ve colunas", "dataset.xnames[:] stats = {} if type(dataset.Y[0]) is str: for i", "range(data.shape[1]): # ve colunas _means = np.mean(data[:, i], axis=0) _vars", "\"\"\" data = np.genfromtxt(filename, delimiter=sep) if labeled: X = data[:,", "separator, defaults to \",\" :type sep: str, optional \"\"\" fullds", ":type sep: str, optional :return: A DataSet object :rtype: DataSet", "= df.to_numpy() Y = None xnames = df.columns.tolist() yname =", "= pd.DataFrame(np.hstack((self.X, self.Y.reshape(len(self.Y), 1))), columns=self.xnames[:]+[self.yname]) #columns=np.hstack((self.xnames, self.yname))) else: df =", "self.xnames = xnames if xnames else label_gen(X.shape[1]) self.yname = yname", "of data points.\"\"\" return self.X.shape[0] def hasLabel(self): \"\"\"Returns True if", "df.columns.tolist() for name in xnames: if name == yname: xnames.remove(yname)", "None def getNumFeatures(self): \"\"\"Returns the number of features\"\"\" return self.X.shape[1]", "fields separator, defaults to \",\" :type sep: str, optional \"\"\"", "\"\"\" Tabular Dataset\"\"\" if X is None: raise Exception(\"Trying to", ":param dataset: A Dataset object :type dataset: si.data.Dataset :param format:", "self.X, self.Y def summary(dataset, format='df'): \"\"\" Returns the statistics of", "axis=0) stat = {\"mean\": _means, \"var\": _vars, \"max\": _maxs, \"min\":", "\"\"\" Converts the dataset into a pandas DataFrame\"\"\" if self.hasLabel():", "1))]) columns = dataset.xnames[:] + [dataset.yname] else: data = dataset.X", "None return cls(X, Y) @classmethod def from_dataframe(cls, df, ylabel=None): \"\"\"Creates", "stats[columns[i]] = stat if format == \"dict\": return stats else:", "X = data[:, 0:-1] Y = data[:, -1] else: X", "output file path :type filename: str :param sep: The fields", "None: raise Exception(\"Trying to instanciate a DataSet without any data\")", "ylabel].to_numpy() # xnames = df.columns.tolist().remove(ylabel) yname = ylabel xnames =", "= ylabel xnames = df.columns.tolist() for name in xnames: if", "array de numpy Y = df.loc[:, ylabel].to_numpy() # xnames =", "the dataset has no dependent variable.\"\"\" return len(np.unique(self.Y)) if self.hasLabel()", "if xnames else label_gen(X.shape[1]) self.yname = yname if yname else", "import pandas as pd import numpy as np from src.si.util.util", "else 'Y' @classmethod def from_data(cls, filename, sep=\",\", labeled=True): \"\"\"Creates a", "in df.columns: X = df.loc[:, df.columns != ylabel].to_numpy() #transforma num", "hasLabel(self): \"\"\"Returns True if the dataset constains labels (a dependent", "separator, defaults to \",\" :type sep: str, optional :return: A", "format: Output format ('df':DataFrame, 'dict':dictionary ), defaults to 'df' :type", "return df def getXy(self): return self.X, self.Y def summary(dataset, format='df'):", "stats[columns[i]] = stat else: for i in range(data.shape[1]): # ve", "delimiter=sep) if labeled: X = data[:, 0:-1] Y = data[:,", "labels (a dependent variable)\"\"\" return self.Y is not None def", "axis=0) _mins = np.min(data[:, i], axis=0) stat = {\"mean\": _means,", "filename: str :param sep: The fields separator, defaults to \",\"", "sep: str, optional :return: A DataSet object :rtype: DataSet \"\"\"", "#ve colunas _means = np.mean(data[:, i], axis=0) _vars = np.var(data[:," ]
[ "backlight(): pass def circle(): pass def clear(): pass def clearwin():", "drawTriangle(): pass def ellipse(): pass def fill(): pass def fillCircle():", "LIGHTGREY = 12632256 M5STACK = 6 MAGENTA = 16515327 MAROON", "nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') #", "= 8388736 RED = 16515072 RIGHT = -9004 VSPI =", "pixel(): pass def polygon(): pass def print(): pass def println():", "pass def getCursor(): pass def get_bg(): pass def get_fg(): pass", "FONT_DejaVu24 = 2 FONT_DejaVu40 = 11 FONT_DejaVu56 = 12 FONT_DejaVu72", "pass def ellipse(): pass def fill(): pass def fillCircle(): pass", "YELLOW = 16579584 def arc(): pass def attrib7seg(): pass def", "= 1 LANDSCAPE_FLIP = 3 LASTX = 7000 LASTY =", "Module: 'display' on M5 FlowUI v1.4.0-beta \"\"\" # MCU: (sysname='esp32',", "MAGENTA = 16515327 MAROON = 8388608 NAVY = 128 OLIVE", "tft_writecmd(): pass def tft_writecmddata(): pass def triangle(): pass def winsize():", "= 16515327 MAROON = 8388608 NAVY = 128 OLIVE =", "8388608 NAVY = 128 OLIVE = 8421376 ORANGE = 16557056", "PURPLE = 8388736 RED = 16515072 RIGHT = -9004 VSPI", "= 5 FONT_Small = 7 FONT_Tooney = 6 FONT_Ubuntu =", "pass def drawPixel(): pass def drawRect(): pass def drawRoundRect(): pass", "def text_x(): pass def text_y(): pass def tft_deselect(): pass def", "= 12632256 M5STACK = 6 MAGENTA = 16515327 MAROON =", "LASTY = 8000 LIGHTGREY = 12632256 M5STACK = 6 MAGENTA", "version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1", "print(): pass def println(): pass def qrcode(): pass def rect():", "ORANGE = 16557056 PINK = 16564426 PORTRAIT = 0 PORTRAIT_FLIP", "= 16 COLOR_BITS24 = 24 CYAN = 65535 DARKCYAN =", "pass def setColor(): pass def setCursor(): pass def setRotation(): pass", "GREENYELLOW = 11336748 HSPI = 1 JPG = 1 LANDSCAPE", "fill(): pass def fillCircle(): pass def fillRect(): pass def fillRoundRect():", "pass def setwin(): pass def text(): pass def textClear(): pass", "pass def setCursor(): pass def setRotation(): pass def setTextColor(): pass", "32896 DARKGREEN = 32768 DARKGREY = 8421504 FONT_7seg = 9", "def circle(): pass def clear(): pass def clearwin(): pass def", "def set_fg(): pass def setwin(): pass def text(): pass def", "= 0 FONT_DefaultSmall = 8 FONT_DejaVu18 = 1 FONT_DejaVu24 =", "RIGHT = -9004 VSPI = 2 WHITE = 16579836 YELLOW", "pass def clear(): pass def clearwin(): pass def compileFont(): pass", "pass def backlight(): pass def circle(): pass def clear(): pass", "= 1 JPG = 1 LANDSCAPE = 1 LANDSCAPE_FLIP =", "text_y(): pass def tft_deselect(): pass def tft_readcmd(): pass def tft_select():", "get_fg(): pass def hsb2rgb(): pass def image(): pass def init():", "FONT_7seg = 9 FONT_Comic = 4 FONT_Default = 0 FONT_DefaultSmall", "M5 FlowUI v1.4.0-beta \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867", "M5STACK = 6 MAGENTA = 16515327 MAROON = 8388608 NAVY", "= 11336748 HSPI = 1 JPG = 1 LANDSCAPE =", "setCursor(): pass def setRotation(): pass def setTextColor(): pass def set_bg():", "getCursor(): pass def get_bg(): pass def get_fg(): pass def hsb2rgb():", "11 FONT_DejaVu56 = 12 FONT_DejaVu72 = 13 FONT_Minya = 5", "1 JPG = 1 LANDSCAPE = 1 LANDSCAPE_FLIP = 3", "-9003 COLOR_BITS16 = 16 COLOR_BITS24 = 24 CYAN = 65535", "= 3 GREEN = 65280 GREENYELLOW = 11336748 HSPI =", "def drawCircle(): pass def drawLine(): pass def drawPixel(): pass def", "get_bg(): pass def get_fg(): pass def hsb2rgb(): pass def image():", "text(): pass def textClear(): pass def textWidth(): pass def text_x():", "LANDSCAPE = 1 LANDSCAPE_FLIP = 3 LASTX = 7000 LASTY", "11336748 HSPI = 1 JPG = 1 LANDSCAPE = 1", "= 16579584 def arc(): pass def attrib7seg(): pass def backlight():", "pass def clearwin(): pass def compileFont(): pass def deinit(): pass", "LASTX = 7000 LASTY = 8000 LIGHTGREY = 12632256 M5STACK", "DARKGREY = 8421504 FONT_7seg = 9 FONT_Comic = 4 FONT_Default", "= 7 FONT_Tooney = 6 FONT_Ubuntu = 3 GREEN =", "16515072 RIGHT = -9004 VSPI = 2 WHITE = 16579836", "fillRect(): pass def fillRoundRect(): pass def fillScreen(): pass def fillTriangle():", "pass def fillScreen(): pass def fillTriangle(): pass def font(): pass", "BMP = 2 BOTTOM = -9004 CENTER = -9003 COLOR_BITS16", "pass def get_bg(): pass def get_fg(): pass def hsb2rgb(): pass", "GREEN = 65280 GREENYELLOW = 11336748 HSPI = 1 JPG", "fillTriangle(): pass def font(): pass def fontSize(): pass def getCursor():", "= 12 FONT_DejaVu72 = 13 FONT_Minya = 5 FONT_Small =", "= -9004 VSPI = 2 WHITE = 16579836 YELLOW =", "pass def tft_writecmddata(): pass def triangle(): pass def winsize(): pass", "3 GREEN = 65280 GREENYELLOW = 11336748 HSPI = 1", "screensize(): pass def setBrightness(): pass def setColor(): pass def setCursor():", "= 8388608 NAVY = 128 OLIVE = 8421376 ORANGE =", "qrcode(): pass def rect(): pass def resetwin(): pass def restorewin():", "pass def text(): pass def textClear(): pass def textWidth(): pass", "2 FONT_DejaVu40 = 11 FONT_DejaVu56 = 12 FONT_DejaVu72 = 13", "= 255 BMP = 2 BOTTOM = -9004 CENTER =", "0 PORTRAIT_FLIP = 2 PURPLE = 8388736 RED = 16515072", "fillScreen(): pass def fillTriangle(): pass def font(): pass def fontSize():", "machine='ESP32 module with ESP32') # Stubber: 1.3.1 class TFT: ''", "8421504 FONT_7seg = 9 FONT_Comic = 4 FONT_Default = 0", "tft_readcmd(): pass def tft_select(): pass def tft_setspeed(): pass def tft_writecmd():", "def fillCircle(): pass def fillRect(): pass def fillRoundRect(): pass def", "def println(): pass def qrcode(): pass def rect(): pass def", "def ellipse(): pass def fill(): pass def fillCircle(): pass def", "clearwin(): pass def compileFont(): pass def deinit(): pass def drawCircle():", "def setBrightness(): pass def setColor(): pass def setCursor(): pass def", "def text(): pass def textClear(): pass def textWidth(): pass def", "2 WHITE = 16579836 YELLOW = 16579584 def arc(): pass", "def line(): pass def lineByAngle(): pass def orient(): pass def", "FONT_Comic = 4 FONT_Default = 0 FONT_DefaultSmall = 8 FONT_DejaVu18", "16579584 def arc(): pass def attrib7seg(): pass def backlight(): pass", "= 32896 DARKGREEN = 32768 DARKGREY = 8421504 FONT_7seg =", "def attrib7seg(): pass def backlight(): pass def circle(): pass def", "with ESP32') # Stubber: 1.3.1 class TFT: '' BLACK =", "pass def font(): pass def fontSize(): pass def getCursor(): pass", "<reponame>RonaldHiemstra/micropython-stubs \"\"\" Module: 'display' on M5 FlowUI v1.4.0-beta \"\"\" #", "5 FONT_Small = 7 FONT_Tooney = 6 FONT_Ubuntu = 3", "orient(): pass def pixel(): pass def polygon(): pass def print():", "2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1 class TFT:", "pass def circle(): pass def clear(): pass def clearwin(): pass", "pass def savewin(): pass def screensize(): pass def setBrightness(): pass", "def clearwin(): pass def compileFont(): pass def deinit(): pass def", "Stubber: 1.3.1 class TFT: '' BLACK = 0 BLUE =", "# Stubber: 1.3.1 class TFT: '' BLACK = 0 BLUE", "PINK = 16564426 PORTRAIT = 0 PORTRAIT_FLIP = 2 PURPLE", "pass def fillRoundRect(): pass def fillScreen(): pass def fillTriangle(): pass", "1 LANDSCAPE_FLIP = 3 LASTX = 7000 LASTY = 8000", "tft_deselect(): pass def tft_readcmd(): pass def tft_select(): pass def tft_setspeed():", "def print(): pass def println(): pass def qrcode(): pass def", "FONT_DefaultSmall = 8 FONT_DejaVu18 = 1 FONT_DejaVu24 = 2 FONT_DejaVu40", "v1.4.0-beta \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30',", "def arc(): pass def attrib7seg(): pass def backlight(): pass def", "FONT_DejaVu18 = 1 FONT_DejaVu24 = 2 FONT_DejaVu40 = 11 FONT_DejaVu56", "2 PURPLE = 8388736 RED = 16515072 RIGHT = -9004", "pass def fillCircle(): pass def fillRect(): pass def fillRoundRect(): pass", "COLOR_BITS24 = 24 CYAN = 65535 DARKCYAN = 32896 DARKGREEN", "pass def fill(): pass def fillCircle(): pass def fillRect(): pass", "def compileFont(): pass def deinit(): pass def drawCircle(): pass def", "RED = 16515072 RIGHT = -9004 VSPI = 2 WHITE", "pass def attrib7seg(): pass def backlight(): pass def circle(): pass", "pass def set_bg(): pass def set_fg(): pass def setwin(): pass", "= 24 CYAN = 65535 DARKCYAN = 32896 DARKGREEN =", "def restorewin(): pass def roundrect(): pass def savewin(): pass def", "drawLine(): pass def drawPixel(): pass def drawRect(): pass def drawRoundRect():", "HSPI = 1 JPG = 1 LANDSCAPE = 1 LANDSCAPE_FLIP", "def setCursor(): pass def setRotation(): pass def setTextColor(): pass def", "= 1 FONT_DejaVu24 = 2 FONT_DejaVu40 = 11 FONT_DejaVu56 =", "def lineByAngle(): pass def orient(): pass def pixel(): pass def", "= 8000 LIGHTGREY = 12632256 M5STACK = 6 MAGENTA =", "pass def init(): pass def line(): pass def lineByAngle(): pass", "FONT_Ubuntu = 3 GREEN = 65280 GREENYELLOW = 11336748 HSPI", "= 0 BLUE = 255 BMP = 2 BOTTOM =", "4 FONT_Default = 0 FONT_DefaultSmall = 8 FONT_DejaVu18 = 1", "drawCircle(): pass def drawLine(): pass def drawPixel(): pass def drawRect():", "\"\"\" Module: 'display' on M5 FlowUI v1.4.0-beta \"\"\" # MCU:", "pass def tft_readcmd(): pass def tft_select(): pass def tft_setspeed(): pass", "= 13 FONT_Minya = 5 FONT_Small = 7 FONT_Tooney =", "7 FONT_Tooney = 6 FONT_Ubuntu = 3 GREEN = 65280", "textClear(): pass def textWidth(): pass def text_x(): pass def text_y():", "= 65535 DARKCYAN = 32896 DARKGREEN = 32768 DARKGREY =", "def qrcode(): pass def rect(): pass def resetwin(): pass def", "restorewin(): pass def roundrect(): pass def savewin(): pass def screensize():", "1 FONT_DejaVu24 = 2 FONT_DejaVu40 = 11 FONT_DejaVu56 = 12", "= 2 WHITE = 16579836 YELLOW = 16579584 def arc():", "8000 LIGHTGREY = 12632256 M5STACK = 6 MAGENTA = 16515327", "circle(): pass def clear(): pass def clearwin(): pass def compileFont():", "16515327 MAROON = 8388608 NAVY = 128 OLIVE = 8421376", "'display' on M5 FlowUI v1.4.0-beta \"\"\" # MCU: (sysname='esp32', nodename='esp32',", "= 9 FONT_Comic = 4 FONT_Default = 0 FONT_DefaultSmall =", "pass def drawLine(): pass def drawPixel(): pass def drawRect(): pass", "\"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32", "pass def pixel(): pass def polygon(): pass def print(): pass", "= 6 FONT_Ubuntu = 3 GREEN = 65280 GREENYELLOW =", "pass def tft_select(): pass def tft_setspeed(): pass def tft_writecmd(): pass", "def rect(): pass def resetwin(): pass def restorewin(): pass def", "def setColor(): pass def setCursor(): pass def setRotation(): pass def", "def setTextColor(): pass def set_bg(): pass def set_fg(): pass def", "pass def drawRoundRect(): pass def drawTriangle(): pass def ellipse(): pass", "16 COLOR_BITS24 = 24 CYAN = 65535 DARKCYAN = 32896", "FONT_Minya = 5 FONT_Small = 7 FONT_Tooney = 6 FONT_Ubuntu", "def getCursor(): pass def get_bg(): pass def get_fg(): pass def", "= 8421504 FONT_7seg = 9 FONT_Comic = 4 FONT_Default =", "pass def text_x(): pass def text_y(): pass def tft_deselect(): pass", "= -9004 CENTER = -9003 COLOR_BITS16 = 16 COLOR_BITS24 =", "pass def fillTriangle(): pass def font(): pass def fontSize(): pass", "println(): pass def qrcode(): pass def rect(): pass def resetwin():", "clear(): pass def clearwin(): pass def compileFont(): pass def deinit():", "= 6 MAGENTA = 16515327 MAROON = 8388608 NAVY =", "65280 GREENYELLOW = 11336748 HSPI = 1 JPG = 1", "drawRect(): pass def drawRoundRect(): pass def drawTriangle(): pass def ellipse():", "6 MAGENTA = 16515327 MAROON = 8388608 NAVY = 128", "FlowUI v1.4.0-beta \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on", "lineByAngle(): pass def orient(): pass def pixel(): pass def polygon():", "tft_select(): pass def tft_setspeed(): pass def tft_writecmd(): pass def tft_writecmddata():", "LANDSCAPE_FLIP = 3 LASTX = 7000 LASTY = 8000 LIGHTGREY", "def get_fg(): pass def hsb2rgb(): pass def image(): pass def", "line(): pass def lineByAngle(): pass def orient(): pass def pixel():", "def image(): pass def init(): pass def line(): pass def", "def hsb2rgb(): pass def image(): pass def init(): pass def", "= 2 FONT_DejaVu40 = 11 FONT_DejaVu56 = 12 FONT_DejaVu72 =", "pass def resetwin(): pass def restorewin(): pass def roundrect(): pass", "def roundrect(): pass def savewin(): pass def screensize(): pass def", "BOTTOM = -9004 CENTER = -9003 COLOR_BITS16 = 16 COLOR_BITS24", "16564426 PORTRAIT = 0 PORTRAIT_FLIP = 2 PURPLE = 8388736", "def backlight(): pass def circle(): pass def clear(): pass def", "tft_setspeed(): pass def tft_writecmd(): pass def tft_writecmddata(): pass def triangle():", "= 8 FONT_DejaVu18 = 1 FONT_DejaVu24 = 2 FONT_DejaVu40 =", "def fillRoundRect(): pass def fillScreen(): pass def fillTriangle(): pass def", "def text_y(): pass def tft_deselect(): pass def tft_readcmd(): pass def", "1.3.1 class TFT: '' BLACK = 0 BLUE = 255", "= 3 LASTX = 7000 LASTY = 8000 LIGHTGREY =", "BLACK = 0 BLUE = 255 BMP = 2 BOTTOM", "-9004 CENTER = -9003 COLOR_BITS16 = 16 COLOR_BITS24 = 24", "setwin(): pass def text(): pass def textClear(): pass def textWidth():", "pass def qrcode(): pass def rect(): pass def resetwin(): pass", "pass def textClear(): pass def textWidth(): pass def text_x(): pass", "init(): pass def line(): pass def lineByAngle(): pass def orient():", "NAVY = 128 OLIVE = 8421376 ORANGE = 16557056 PINK", "pass def text_y(): pass def tft_deselect(): pass def tft_readcmd(): pass", "= 8421376 ORANGE = 16557056 PINK = 16564426 PORTRAIT =", "VSPI = 2 WHITE = 16579836 YELLOW = 16579584 def", "255 BMP = 2 BOTTOM = -9004 CENTER = -9003", "CYAN = 65535 DARKCYAN = 32896 DARKGREEN = 32768 DARKGREY", "def fillRect(): pass def fillRoundRect(): pass def fillScreen(): pass def", "pass def setBrightness(): pass def setColor(): pass def setCursor(): pass", "16557056 PINK = 16564426 PORTRAIT = 0 PORTRAIT_FLIP = 2", "24 CYAN = 65535 DARKCYAN = 32896 DARKGREEN = 32768", "def tft_select(): pass def tft_setspeed(): pass def tft_writecmd(): pass def", "rect(): pass def resetwin(): pass def restorewin(): pass def roundrect():", "pass def fontSize(): pass def getCursor(): pass def get_bg(): pass", "COLOR_BITS16 = 16 COLOR_BITS24 = 24 CYAN = 65535 DARKCYAN", "pass def screensize(): pass def setBrightness(): pass def setColor(): pass", "PORTRAIT_FLIP = 2 PURPLE = 8388736 RED = 16515072 RIGHT", "7000 LASTY = 8000 LIGHTGREY = 12632256 M5STACK = 6", "def clear(): pass def clearwin(): pass def compileFont(): pass def", "def polygon(): pass def print(): pass def println(): pass def", "def tft_writecmd(): pass def tft_writecmddata(): pass def triangle(): pass def", "def get_bg(): pass def get_fg(): pass def hsb2rgb(): pass def", "ESP32') # Stubber: 1.3.1 class TFT: '' BLACK = 0", "3 LASTX = 7000 LASTY = 8000 LIGHTGREY = 12632256", "def init(): pass def line(): pass def lineByAngle(): pass def", "def resetwin(): pass def restorewin(): pass def roundrect(): pass def", "setRotation(): pass def setTextColor(): pass def set_bg(): pass def set_fg():", "set_bg(): pass def set_fg(): pass def setwin(): pass def text():", "text_x(): pass def text_y(): pass def tft_deselect(): pass def tft_readcmd():", "128 OLIVE = 8421376 ORANGE = 16557056 PINK = 16564426", "arc(): pass def attrib7seg(): pass def backlight(): pass def circle():", "on M5 FlowUI v1.4.0-beta \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.11.0',", "pass def fillRect(): pass def fillRoundRect(): pass def fillScreen(): pass", "pass def line(): pass def lineByAngle(): pass def orient(): pass", "def setwin(): pass def text(): pass def textClear(): pass def", "def fillScreen(): pass def fillTriangle(): pass def font(): pass def", "pass def lineByAngle(): pass def orient(): pass def pixel(): pass", "on 2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1 class", "set_fg(): pass def setwin(): pass def text(): pass def textClear():", "= 128 OLIVE = 8421376 ORANGE = 16557056 PINK =", "def textWidth(): pass def text_x(): pass def text_y(): pass def", "release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') # Stubber:", "def fontSize(): pass def getCursor(): pass def get_bg(): pass def", "JPG = 1 LANDSCAPE = 1 LANDSCAPE_FLIP = 3 LASTX", "fillCircle(): pass def fillRect(): pass def fillRoundRect(): pass def fillScreen():", "12632256 M5STACK = 6 MAGENTA = 16515327 MAROON = 8388608", "roundrect(): pass def savewin(): pass def screensize(): pass def setBrightness():", "pass def orient(): pass def pixel(): pass def polygon(): pass", "'' BLACK = 0 BLUE = 255 BMP = 2", "BLUE = 255 BMP = 2 BOTTOM = -9004 CENTER", "setBrightness(): pass def setColor(): pass def setCursor(): pass def setRotation():", "def tft_setspeed(): pass def tft_writecmd(): pass def tft_writecmddata(): pass def", "0 BLUE = 255 BMP = 2 BOTTOM = -9004", "FONT_Default = 0 FONT_DefaultSmall = 8 FONT_DejaVu18 = 1 FONT_DejaVu24", "MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with", "-9004 VSPI = 2 WHITE = 16579836 YELLOW = 16579584", "CENTER = -9003 COLOR_BITS16 = 16 COLOR_BITS24 = 24 CYAN", "16579836 YELLOW = 16579584 def arc(): pass def attrib7seg(): pass", "pass def roundrect(): pass def savewin(): pass def screensize(): pass", "pass def deinit(): pass def drawCircle(): pass def drawLine(): pass", "TFT: '' BLACK = 0 BLUE = 255 BMP =", "MAROON = 8388608 NAVY = 128 OLIVE = 8421376 ORANGE", "def setRotation(): pass def setTextColor(): pass def set_bg(): pass def", "= 11 FONT_DejaVu56 = 12 FONT_DejaVu72 = 13 FONT_Minya =", "fillRoundRect(): pass def fillScreen(): pass def fillTriangle(): pass def font():", "pass def drawCircle(): pass def drawLine(): pass def drawPixel(): pass", "def tft_readcmd(): pass def tft_select(): pass def tft_setspeed(): pass def", "2 BOTTOM = -9004 CENTER = -9003 COLOR_BITS16 = 16", "compileFont(): pass def deinit(): pass def drawCircle(): pass def drawLine():", "pass def rect(): pass def resetwin(): pass def restorewin(): pass", "def deinit(): pass def drawCircle(): pass def drawLine(): pass def", "def drawRect(): pass def drawRoundRect(): pass def drawTriangle(): pass def", "class TFT: '' BLACK = 0 BLUE = 255 BMP", "DARKCYAN = 32896 DARKGREEN = 32768 DARKGREY = 8421504 FONT_7seg", "FONT_DejaVu40 = 11 FONT_DejaVu56 = 12 FONT_DejaVu72 = 13 FONT_Minya", "textWidth(): pass def text_x(): pass def text_y(): pass def tft_deselect():", "32768 DARKGREY = 8421504 FONT_7seg = 9 FONT_Comic = 4", "def orient(): pass def pixel(): pass def polygon(): pass def", "def textClear(): pass def textWidth(): pass def text_x(): pass def", "8388736 RED = 16515072 RIGHT = -9004 VSPI = 2", "FONT_Tooney = 6 FONT_Ubuntu = 3 GREEN = 65280 GREENYELLOW", "module with ESP32') # Stubber: 1.3.1 class TFT: '' BLACK", "pass def println(): pass def qrcode(): pass def rect(): pass", "pass def hsb2rgb(): pass def image(): pass def init(): pass", "= 0 PORTRAIT_FLIP = 2 PURPLE = 8388736 RED =", "pass def tft_writecmd(): pass def tft_writecmddata(): pass def triangle(): pass", "= 7000 LASTY = 8000 LIGHTGREY = 12632256 M5STACK =", "13 FONT_Minya = 5 FONT_Small = 7 FONT_Tooney = 6", "def pixel(): pass def polygon(): pass def print(): pass def", "OLIVE = 8421376 ORANGE = 16557056 PINK = 16564426 PORTRAIT", "polygon(): pass def print(): pass def println(): pass def qrcode():", "resetwin(): pass def restorewin(): pass def roundrect(): pass def savewin():", "pass def polygon(): pass def print(): pass def println(): pass", "font(): pass def fontSize(): pass def getCursor(): pass def get_bg():", "= 4 FONT_Default = 0 FONT_DefaultSmall = 8 FONT_DejaVu18 =", "= -9003 COLOR_BITS16 = 16 COLOR_BITS24 = 24 CYAN =", "drawRoundRect(): pass def drawTriangle(): pass def ellipse(): pass def fill():", "9 FONT_Comic = 4 FONT_Default = 0 FONT_DefaultSmall = 8", "= 16515072 RIGHT = -9004 VSPI = 2 WHITE =", "= 16557056 PINK = 16564426 PORTRAIT = 0 PORTRAIT_FLIP =", "WHITE = 16579836 YELLOW = 16579584 def arc(): pass def", "fontSize(): pass def getCursor(): pass def get_bg(): pass def get_fg():", "pass def image(): pass def init(): pass def line(): pass", "pass def compileFont(): pass def deinit(): pass def drawCircle(): pass", "8421376 ORANGE = 16557056 PINK = 16564426 PORTRAIT = 0", "# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module", "image(): pass def init(): pass def line(): pass def lineByAngle():", "pass def setTextColor(): pass def set_bg(): pass def set_fg(): pass", "def set_bg(): pass def set_fg(): pass def setwin(): pass def", "FONT_DejaVu56 = 12 FONT_DejaVu72 = 13 FONT_Minya = 5 FONT_Small", "pass def drawRect(): pass def drawRoundRect(): pass def drawTriangle(): pass", "DARKGREEN = 32768 DARKGREY = 8421504 FONT_7seg = 9 FONT_Comic", "(sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')", "1 LANDSCAPE = 1 LANDSCAPE_FLIP = 3 LASTX = 7000", "ellipse(): pass def fill(): pass def fillCircle(): pass def fillRect():", "= 2 BOTTOM = -9004 CENTER = -9003 COLOR_BITS16 =", "deinit(): pass def drawCircle(): pass def drawLine(): pass def drawPixel():", "0 FONT_DefaultSmall = 8 FONT_DejaVu18 = 1 FONT_DejaVu24 = 2", "pass def tft_setspeed(): pass def tft_writecmd(): pass def tft_writecmddata(): pass", "def drawTriangle(): pass def ellipse(): pass def fill(): pass def", "65535 DARKCYAN = 32896 DARKGREEN = 32768 DARKGREY = 8421504", "def fillTriangle(): pass def font(): pass def fontSize(): pass def", "pass def textWidth(): pass def text_x(): pass def text_y(): pass", "pass def drawTriangle(): pass def ellipse(): pass def fill(): pass", "pass def restorewin(): pass def roundrect(): pass def savewin(): pass", "def drawRoundRect(): pass def drawTriangle(): pass def ellipse(): pass def", "def screensize(): pass def setBrightness(): pass def setColor(): pass def", "pass def tft_deselect(): pass def tft_readcmd(): pass def tft_select(): pass", "8 FONT_DejaVu18 = 1 FONT_DejaVu24 = 2 FONT_DejaVu40 = 11", "pass def get_fg(): pass def hsb2rgb(): pass def image(): pass", "pass def print(): pass def println(): pass def qrcode(): pass", "setColor(): pass def setCursor(): pass def setRotation(): pass def setTextColor():", "= 1 LANDSCAPE = 1 LANDSCAPE_FLIP = 3 LASTX =", "pass def set_fg(): pass def setwin(): pass def text(): pass", "PORTRAIT = 0 PORTRAIT_FLIP = 2 PURPLE = 8388736 RED", "def drawPixel(): pass def drawRect(): pass def drawRoundRect(): pass def", "def savewin(): pass def screensize(): pass def setBrightness(): pass def", "6 FONT_Ubuntu = 3 GREEN = 65280 GREENYELLOW = 11336748", "setTextColor(): pass def set_bg(): pass def set_fg(): pass def setwin():", "= 65280 GREENYELLOW = 11336748 HSPI = 1 JPG =", "savewin(): pass def screensize(): pass def setBrightness(): pass def setColor():", "FONT_Small = 7 FONT_Tooney = 6 FONT_Ubuntu = 3 GREEN", "= 32768 DARKGREY = 8421504 FONT_7seg = 9 FONT_Comic =", "def drawLine(): pass def drawPixel(): pass def drawRect(): pass def", "12 FONT_DejaVu72 = 13 FONT_Minya = 5 FONT_Small = 7", "def fill(): pass def fillCircle(): pass def fillRect(): pass def", "attrib7seg(): pass def backlight(): pass def circle(): pass def clear():", "= 16564426 PORTRAIT = 0 PORTRAIT_FLIP = 2 PURPLE =", "pass def setRotation(): pass def setTextColor(): pass def set_bg(): pass", "drawPixel(): pass def drawRect(): pass def drawRoundRect(): pass def drawTriangle():", "hsb2rgb(): pass def image(): pass def init(): pass def line():", "FONT_DejaVu72 = 13 FONT_Minya = 5 FONT_Small = 7 FONT_Tooney", "= 16579836 YELLOW = 16579584 def arc(): pass def attrib7seg():", "= 2 PURPLE = 8388736 RED = 16515072 RIGHT =", "def font(): pass def fontSize(): pass def getCursor(): pass def", "def tft_deselect(): pass def tft_readcmd(): pass def tft_select(): pass def" ]
[ "WorkspaceClient from .ScimClient import ScimClient from .LibraryClient import LibraryClient from", "import ClustersClient from .WorkspaceClient import WorkspaceClient from .ScimClient import ScimClient", "from .LibraryClient import LibraryClient from .HiveClient import HiveClient from .parser", "import json, requests, datetime from cron_descriptor import get_description from .dbclient", "ScimClient from .LibraryClient import LibraryClient from .HiveClient import HiveClient from", "from cron_descriptor import get_description from .dbclient import dbclient from .JobsClient", ".ScimClient import ScimClient from .LibraryClient import LibraryClient from .HiveClient import", "json, requests, datetime from cron_descriptor import get_description from .dbclient import", "ClustersClient from .WorkspaceClient import WorkspaceClient from .ScimClient import ScimClient from", ".ClustersClient import ClustersClient from .WorkspaceClient import WorkspaceClient from .ScimClient import", ".JobsClient import JobsClient from .ClustersClient import ClustersClient from .WorkspaceClient import", ".WorkspaceClient import WorkspaceClient from .ScimClient import ScimClient from .LibraryClient import", "import dbclient from .JobsClient import JobsClient from .ClustersClient import ClustersClient", "import JobsClient from .ClustersClient import ClustersClient from .WorkspaceClient import WorkspaceClient", ".dbclient import dbclient from .JobsClient import JobsClient from .ClustersClient import", "from .ScimClient import ScimClient from .LibraryClient import LibraryClient from .HiveClient", "import get_description from .dbclient import dbclient from .JobsClient import JobsClient", "get_description from .dbclient import dbclient from .JobsClient import JobsClient from", "from .JobsClient import JobsClient from .ClustersClient import ClustersClient from .WorkspaceClient", "import ScimClient from .LibraryClient import LibraryClient from .HiveClient import HiveClient", "import WorkspaceClient from .ScimClient import ScimClient from .LibraryClient import LibraryClient", ".LibraryClient import LibraryClient from .HiveClient import HiveClient from .parser import", "JobsClient from .ClustersClient import ClustersClient from .WorkspaceClient import WorkspaceClient from", "from .WorkspaceClient import WorkspaceClient from .ScimClient import ScimClient from .LibraryClient", "import LibraryClient from .HiveClient import HiveClient from .parser import *", "cron_descriptor import get_description from .dbclient import dbclient from .JobsClient import", "dbclient from .JobsClient import JobsClient from .ClustersClient import ClustersClient from", "datetime from cron_descriptor import get_description from .dbclient import dbclient from", "from .dbclient import dbclient from .JobsClient import JobsClient from .ClustersClient", "requests, datetime from cron_descriptor import get_description from .dbclient import dbclient", "from .ClustersClient import ClustersClient from .WorkspaceClient import WorkspaceClient from .ScimClient" ]
[ "General Public License for more details. # # See http://www.gnu.org/licenses/gpl.html", "# -*- coding: utf-8 -*- # SkinWeights command and component", "is free software: you can redistribute it and/or modify #", "# This program is distributed in the hope that it", "pyqt attribute sliders # Copyright (C) 2018 <NAME> # Website:", "any later version. # # This program is distributed in", "# Website: http://www.perryleijten.com # # This program is free software:", "more details. # # See http://www.gnu.org/licenses/gpl.html for a copy of", "GNU General Public License as published by # the Free", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "PURPOSE. See the # GNU General Public License for more", "# This program is free software: you can redistribute it", "This program is free software: you can redistribute it and/or", "FOR A PARTICULAR PURPOSE. See the # GNU General Public", "# skinningTools and UI # Copyright (C) 2018 <NAME> #", "the # GNU General Public License for more details. #", "http://danieleniero.com/ # # neighbour finding algorythm # Copyright (C) 2018", "and component editor # Copyright (C) 2018 <NAME> # Website:", "under the terms of the GNU General Public License as", "algorythm # Copyright (C) 2018 <NAME> # Website: http://www.janpijpers.com/ #", "See http://www.gnu.org/licenses/gpl.html for a copy of the GNU General #", "coding: utf-8 -*- # SkinWeights command and component editor #", "<NAME> # Website: http://www.trevorius.com # # pyqt attribute sliders #", "# the Free Software Foundation, either version 3 of the", "License as published by # the Free Software Foundation, either", "a copy of the GNU General # Public License. #", "# (at your option) any later version. # # This", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "attribute sliders # Copyright (C) 2018 <NAME> # Website: http://danieleniero.com/", "http://www.trevorius.com # # pyqt attribute sliders # Copyright (C) 2018", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "redistribute it and/or modify # it under the terms of", "See the # GNU General Public License for more details.", "sliders # Copyright (C) 2018 <NAME> # Website: http://danieleniero.com/ #", "# Copyright (C) 2018 <NAME> # Website: http://danieleniero.com/ # #", "Copyright (C) 2018 <NAME> # Website: http://danieleniero.com/ # # neighbour", "or # (at your option) any later version. # #", "2018 <NAME> # Website: http://www.trevorius.com # # pyqt attribute sliders", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "version. # # This program is distributed in the hope", "# Website: http://www.janpijpers.com/ # # skinningTools and UI # Copyright", "that it will be useful, # but WITHOUT ANY WARRANTY;", "Copyright (C) 2018 <NAME> # Website: http://www.janpijpers.com/ # # skinningTools", "editor # Copyright (C) 2018 <NAME> # Website: http://www.trevorius.com #", "# GNU General Public License for more details. # #", "# # See http://www.gnu.org/licenses/gpl.html for a copy of the GNU", "either version 3 of the License, or # (at your", "your option) any later version. # # This program is", "program is free software: you can redistribute it and/or modify", "http://www.janpijpers.com/ # # skinningTools and UI # Copyright (C) 2018", "-*- # SkinWeights command and component editor # Copyright (C)", "# Copyright (C) 2018 <NAME> # Website: http://www.perryleijten.com # #", "# Copyright (C) 2018 <NAME> # Website: http://www.trevorius.com # #", "the terms of the GNU General Public License as published", "Copyright (C) 2018 <NAME> # Website: http://www.perryleijten.com # # This", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "# Copyright (C) 2018 <NAME> # Website: http://www.janpijpers.com/ # #", "Website: http://www.perryleijten.com # # This program is free software: you", "(at your option) any later version. # # This program", "http://www.gnu.org/licenses/gpl.html for a copy of the GNU General # Public", "Foundation, either version 3 of the License, or # (at", "skinningTools and UI # Copyright (C) 2018 <NAME> # Website:", "command and component editor # Copyright (C) 2018 <NAME> #", "<NAME> # Website: http://www.perryleijten.com # # This program is free", "(C) 2018 <NAME> # Website: http://danieleniero.com/ # # neighbour finding", "be useful, # but WITHOUT ANY WARRANTY; without even the", "and UI # Copyright (C) 2018 <NAME> # Website: http://www.perryleijten.com", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "Software Foundation, either version 3 of the License, or #", "SkinWeights command and component editor # Copyright (C) 2018 <NAME>", "the hope that it will be useful, # but WITHOUT", "GNU General Public License for more details. # # See", "component editor # Copyright (C) 2018 <NAME> # Website: http://www.trevorius.com", "2018 <NAME> # Website: http://danieleniero.com/ # # neighbour finding algorythm", "Website: http://www.janpijpers.com/ # # skinningTools and UI # Copyright (C)", "software: you can redistribute it and/or modify # it under", "as published by # the Free Software Foundation, either version", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "version 3 of the License, or # (at your option)", "A PARTICULAR PURPOSE. See the # GNU General Public License", "the Free Software Foundation, either version 3 of the License,", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "free software: you can redistribute it and/or modify # it", "# # This program is distributed in the hope that", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "option) any later version. # # This program is distributed", "# # skinningTools and UI # Copyright (C) 2018 <NAME>", "# Website: http://danieleniero.com/ # # neighbour finding algorythm # Copyright", "# neighbour finding algorythm # Copyright (C) 2018 <NAME> #", "Website: http://www.trevorius.com # # pyqt attribute sliders # Copyright (C)", "of the GNU General Public License as published by #", "Public License as published by # the Free Software Foundation,", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "Free Software Foundation, either version 3 of the License, or", "can redistribute it and/or modify # it under the terms", "<filename>UI/ControlSlider/__init__.py # -*- coding: utf-8 -*- # SkinWeights command and", "UI # Copyright (C) 2018 <NAME> # Website: http://www.perryleijten.com #", "This program is distributed in the hope that it will", "distributed in the hope that it will be useful, #", "and/or modify # it under the terms of the GNU", "by # the Free Software Foundation, either version 3 of", "License, or # (at your option) any later version. #", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "for more details. # # See http://www.gnu.org/licenses/gpl.html for a copy", "# # pyqt attribute sliders # Copyright (C) 2018 <NAME>", "Website: http://danieleniero.com/ # # neighbour finding algorythm # Copyright (C)", "copy of the GNU General # Public License. # --------------------------------------------------------------------------------------", "utf-8 -*- # SkinWeights command and component editor # Copyright", "# # neighbour finding algorythm # Copyright (C) 2018 <NAME>", "in the hope that it will be useful, # but", "License for more details. # # See http://www.gnu.org/licenses/gpl.html for a", "finding algorythm # Copyright (C) 2018 <NAME> # Website: http://www.janpijpers.com/", "2018 <NAME> # Website: http://www.janpijpers.com/ # # skinningTools and UI", "it and/or modify # it under the terms of the", "# See http://www.gnu.org/licenses/gpl.html for a copy of the GNU General", "details. # # See http://www.gnu.org/licenses/gpl.html for a copy of the", "http://www.perryleijten.com # # This program is free software: you can", "it will be useful, # but WITHOUT ANY WARRANTY; without", "# pyqt attribute sliders # Copyright (C) 2018 <NAME> #", "# SkinWeights command and component editor # Copyright (C) 2018", "<NAME> # Website: http://www.janpijpers.com/ # # skinningTools and UI #", "for a copy of the GNU General # Public License.", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "<NAME> # Website: http://danieleniero.com/ # # neighbour finding algorythm #", "# it under the terms of the GNU General Public", "# # This program is free software: you can redistribute", "(C) 2018 <NAME> # Website: http://www.perryleijten.com # # This program", "you can redistribute it and/or modify # it under the", "of the License, or # (at your option) any later", "(C) 2018 <NAME> # Website: http://www.janpijpers.com/ # # skinningTools and", "later version. # # This program is distributed in the", "hope that it will be useful, # but WITHOUT ANY", "it under the terms of the GNU General Public License", "# Website: http://www.trevorius.com # # pyqt attribute sliders # Copyright", "the License, or # (at your option) any later version.", "2018 <NAME> # Website: http://www.perryleijten.com # # This program is", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "program is distributed in the hope that it will be", "-*- coding: utf-8 -*- # SkinWeights command and component editor", "PARTICULAR PURPOSE. See the # GNU General Public License for", "neighbour finding algorythm # Copyright (C) 2018 <NAME> # Website:", "Public License for more details. # # See http://www.gnu.org/licenses/gpl.html for", "(C) 2018 <NAME> # Website: http://www.trevorius.com # # pyqt attribute", "the GNU General Public License as published by # the", "modify # it under the terms of the GNU General", "terms of the GNU General Public License as published by", "Copyright (C) 2018 <NAME> # Website: http://www.trevorius.com # # pyqt", "is distributed in the hope that it will be useful,", "3 of the License, or # (at your option) any", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "General Public License as published by # the Free Software", "published by # the Free Software Foundation, either version 3", "will be useful, # but WITHOUT ANY WARRANTY; without even" ]
[ "attenuation.\"\"\" return status.attenuation[0] / 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_received_state(", "class.\"\"\" value_fn: Callable[[FritzStatus, Any], Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes", "max transmission rate.\"\"\" return round(status.max_bit_rate[0] / 1000, 1) # type:", "if ( not fritzbox_tools.connection or \"WANIPConn1\" not in fritzbox_tools.connection.services ):", "1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str)", "None: \"\"\"Init FRITZ!Box connectivity class.\"\"\" self.entity_description = description self._last_device_value: str", "the moment return dsl: bool = False try: dslinterface =", "FritzServiceError, ) from fritzconnection.lib.fritzstatus import FritzStatus from homeassistant.components.sensor import (", "return status.attenuation[1] / 10 # type: ignore[no-any-return] @dataclass class FritzRequireKeysMixin:", "class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz sensor entity.\"\"\" connection_type: Literal[\"dsl\"] |", "FritzBoxTools from .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__)", "FritzStatus, last_value: str) -> float: \"\"\"Return upload transmission rate.\"\"\" return", "ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload", "= False try: dslinterface = await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\",", "type: ignore[no-any-return] def _retrieve_link_attenuation_received_state( status: FritzStatus, last_value: str ) ->", "= False return self._attr_native_value = ( self._last_device_value ) = self.entity_description.value_fn(status,", "import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utcnow", "_retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload transmission rate.\"\"\"", "( not fritzbox_tools.connection or \"WANIPConn1\" not in fritzbox_tools.connection.services ): #", "Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download", "FritzConnectionException, FritzInternalError, FritzServiceError, ) from fritzconnection.lib.fritzstatus import FritzStatus from homeassistant.components.sensor", "# type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:", "self, fritzbox_tools: FritzBoxTools, device_friendly_name: str, description: FritzSensorEntityDescription, ) -> None:", "round(status.max_linked_bit_rate[1] / 1000, 1) # type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status:", "data.\"\"\" return round(status.bytes_received / 1000 / 1000 / 1000, 1)", "@dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz sensor entity.\"\"\" connection_type: Literal[\"dsl\"]", "entities = [ FritzBoxSensor(fritzbox_tools, entry.title, description) for description in SENSOR_TYPES", "Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link", "dataclasses import dataclass from datetime import datetime, timedelta import logging", "description self._last_device_value: str | None = None self._attr_available = True", "= True self._attr_name = f\"{device_friendly_name} {description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools,", "FRITZ!Box binary sensors.\"\"\" from __future__ import annotations from collections.abc import", ") -> float: \"\"\"Return upload noise margin.\"\"\" return status.noise_margin[0] /", "timedelta(seconds=seconds_uptime) if ( not last_value or abs((delta_uptime - last_value).total_seconds()) >", "): return delta_uptime return last_value def _retrieve_device_uptime_state( status: FritzStatus, last_value:", "), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription(", "float: \"\"\"Return upload link rate.\"\"\" return round(status.max_linked_bit_rate[0] / 1000, 1)", "Any, Literal from fritzconnection.core.exceptions import ( FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError,", "import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries import", "name=\"Link Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription(", "value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state,", "link rate.\"\"\" return round(status.max_linked_bit_rate[1] / 1000, 1) # type: ignore[no-any-return]", "FritzStatus, last_value: str ) -> float: \"\"\"Return download line attenuation.\"\"\"", "= None self._attr_available = True self._attr_name = f\"{device_friendly_name} {description.name}\" self._attr_unique_id", "# type: ignore[no-any-return] @dataclass class FritzRequireKeysMixin: \"\"\"Fritz sensor data class.\"\"\"", ") from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DATA_GIGABYTES,", "), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC,", "status.external_ip # type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) ->", "str) -> float: \"\"\"Return upload link rate.\"\"\" return round(status.max_linked_bit_rate[0] /", "link rate.\"\"\" return round(status.max_linked_bit_rate[0] / 1000, 1) # type: ignore[no-any-return]", "icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\",", "FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ),", "ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download", "last_value) def _retrieve_connection_uptime_state( status: FritzStatus, last_value: datetime | None )", "return round(status.transmission_rate[1] / 1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status:", "\"\"\"Return download noise margin.\"\"\" return status.noise_margin[1] / 10 # type:", "round(status.max_bit_rate[0] / 1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus,", "external ip from device.\"\"\" return status.external_ip # type: ignore[no-any-return] def", "), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state,", "last_value).total_seconds()) > UPTIME_DEVIATION ): return delta_uptime return last_value def _retrieve_device_uptime_state(", "from .common import FritzBoxBaseEntity, FritzBoxTools from .const import DOMAIN, DSL_CONNECTION,", ") async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback", "binary sensors.\"\"\" from __future__ import annotations from collections.abc import Callable", "utcnow() - timedelta(seconds=seconds_uptime) if ( not last_value or abs((delta_uptime -", ") -> float: \"\"\"Return download line attenuation.\"\"\" return status.attenuation[1] /", "value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,", "= f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def update(self) -> None: \"\"\"Update data.\"\"\"", "return round(status.bytes_received / 1000 / 1000 / 1000, 1) #", "Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download", "1000 / 1000, 1) # type: ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus,", "name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\",", "icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\",", "moment return dsl: bool = False try: dslinterface = await", "FritzStatus, last_value: str) -> float: \"\"\"Return download transmission rate.\"\"\" return", "datetime import datetime, timedelta import logging from typing import Any,", "from homeassistant.const import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS,", "- last_value).total_seconds()) > UPTIME_DEVIATION ): return delta_uptime return last_value def", "), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ),", ") -> datetime: \"\"\"Return uptime from connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value)", "FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription(", "name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max", "the state from the FRITZ!Box\", exc_info=True) self._attr_available = False return", "Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection", "\"\"\"Return upload max transmission rate.\"\"\" return round(status.max_bit_rate[0] / 1000, 1)", "name=\"Max Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription(", "DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core import HomeAssistant", "FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription(", "native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING,", "sensor entity.\"\"\" connection_type: Literal[\"dsl\"] | None = None SENSOR_TYPES: tuple[FritzSensorEntityDescription,", "ignore[no-any-return] @dataclass class FritzRequireKeysMixin: \"\"\"Fritz sensor data class.\"\"\" value_fn: Callable[[FritzStatus,", "str) -> float: \"\"\"Return download transmission rate.\"\"\" return round(status.transmission_rate[1] /", "name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\",", "upload transmission rate.\"\"\" return round(status.transmission_rate[0] / 1000, 1) # type:", "dslinterface[\"NewEnable\"] except ( FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError, ): pass entities", "import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float,", "ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload", "ignore[no-any-return] def _retrieve_link_attenuation_received_state( status: FritzStatus, last_value: str ) -> float:", "fritzconnection.lib.fritzstatus import FritzStatus from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity,", "up entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id]", "value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state,", "ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status: FritzStatus, last_value: str ) -> float:", "float: \"\"\"Return upload total data.\"\"\" return round(status.bytes_sent / 1000 /", "value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\",", "key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\",", "\"\"\"Return download line attenuation.\"\"\" return status.attenuation[1] / 10 # type:", "\"\"\"Return upload total data.\"\"\" return round(status.bytes_sent / 1000 / 1000", "def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload total", "key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\",", "key=\"link_noise_margin_received\", name=\"Link Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ),", "async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback )", "] async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box connectivity class.\"\"\"", "_uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state( status: FritzStatus, last_value: datetime | None", "transmission rate.\"\"\" return round(status.max_bit_rate[0] / 1000, 1) # type: ignore[no-any-return]", "return status.noise_margin[1] / 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status:", "-> str: \"\"\"Return external ip from device.\"\"\" return status.external_ip #", "), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ),", "rate.\"\"\" return round(status.max_linked_bit_rate[1] / 1000, 1) # type: ignore[no-any-return] def", "SensorEntityDescription, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import (", "1) # type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) ->", "ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: \"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting", "native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection Download", "dsl or description.connection_type != DSL_CONNECTION ] async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity,", "Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP,", "Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\",", "last_value: str) -> float: \"\"\"Return upload transmission rate.\"\"\" return round(status.transmission_rate[0]", "str, description: FritzSensorEntityDescription, ) -> None: \"\"\"Init FRITZ!Box connectivity class.\"\"\"", "name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB", "= dslinterface[\"NewEnable\"] except ( FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError, ): pass", "native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload Power", "connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state,", "_retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download total data.\"\"\"", "FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION,", "icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload Power Attenuation\",", "entity_description: FritzSensorEntityDescription def __init__( self, fritzbox_tools: FritzBoxTools, device_friendly_name: str, description:", "import Callable from dataclasses import dataclass from datetime import datetime,", "\"\"\"Return upload transmission rate.\"\"\" return round(status.transmission_rate[0] / 1000, 1) #", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value:", "1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str)", "1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str)", "FritzStatus, last_value: str ) -> float: \"\"\"Return download noise margin.\"\"\"", "/ 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_received_state( status: FritzStatus, last_value:", "key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection", "entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if", "hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl = dslinterface[\"NewEnable\"] except (", "entry.title, description) for description in SENSOR_TYPES if dsl or description.connection_type", "hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: \"\"\"Set", "Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link", "= [ FritzBoxSensor(fritzbox_tools, entry.title, description) for description in SENSOR_TYPES if", "key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\",", "/ 1000 / 1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status:", "state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection Upload", "sensors.\"\"\" from __future__ import annotations from collections.abc import Callable from", "), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION,", "-> datetime: \"\"\"Calculate uptime with deviation.\"\"\" delta_uptime = utcnow() -", "last_value: str ) -> float: \"\"\"Return upload line attenuation.\"\"\" return", "AddEntitiesCallback ) -> None: \"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box", "FritzStatus, last_value: str ) -> float: \"\"\"Return upload line attenuation.\"\"\"", "\"GetInfo\", ) dsl = dslinterface[\"NewEnable\"] except ( FritzInternalError, FritzActionError, FritzActionFailedError,", "icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload Noise Margin\",", "IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC,", "FritzBoxSensor(fritzbox_tools, entry.title, description) for description in SENSOR_TYPES if dsl or", "return _uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str:", "update(self) -> None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\") try: status:", "SENSOR_TYPES if dsl or description.connection_type != DSL_CONNECTION ] async_add_entities(entities, True)", ") dsl = dslinterface[\"NewEnable\"] except ( FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError,", "-> float: \"\"\"Return upload total data.\"\"\" return round(status.bytes_sent / 1000", "float: \"\"\"Return download line attenuation.\"\"\" return status.attenuation[1] / 10 #", "True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box connectivity class.\"\"\" entity_description: FritzSensorEntityDescription", "return last_value def _retrieve_device_uptime_state( status: FritzStatus, last_value: datetime ) ->", "<reponame>EuleMitKeule/core \"\"\"AVM FRITZ!Box binary sensors.\"\"\" from __future__ import annotations from", "last_value: str) -> float: \"\"\"Return upload link rate.\"\"\" return round(status.max_linked_bit_rate[0]", "FritzStatus, last_value: str ) -> float: \"\"\"Return upload noise margin.\"\"\"", "STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const", "from homeassistant.util.dt import utcnow from .common import FritzBoxBaseEntity, FritzBoxTools from", "connectivity class.\"\"\" entity_description: FritzSensorEntityDescription def __init__( self, fritzbox_tools: FritzBoxTools, device_friendly_name:", "-> None: \"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box sensors\") fritzbox_tools:", "self._fritzbox_tools.fritz_status self._attr_available = True except FritzConnectionException: _LOGGER.error(\"Error getting the state", "value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\",", "_LOGGER.error(\"Error getting the state from the FRITZ!Box\", exc_info=True) self._attr_available =", "homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries", "last_value: str) -> float: \"\"\"Return download transmission rate.\"\"\" return round(status.transmission_rate[1]", "value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state,", "FritzStatus, last_value: str) -> str: \"\"\"Return external ip from device.\"\"\"", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value:", "sensors\") fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if ( not fritzbox_tools.connection or", "upload max transmission rate.\"\"\" return round(status.max_bit_rate[0] / 1000, 1) #", "ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value: str ) -> float:", "FritzSensorEntityDescription def __init__( self, fritzbox_tools: FritzBoxTools, device_friendly_name: str, description: FritzSensorEntityDescription,", "type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "max transmission rate.\"\"\" return round(status.max_bit_rate[1] / 1000, 1) # type:", "\"\"\"Return uptime from device.\"\"\" return _uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state( status:", ") -> float: \"\"\"Return upload line attenuation.\"\"\" return status.attenuation[0] /", "value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ),", "FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION,", "value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ),", "fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl = dslinterface[\"NewEnable\"] except ( FritzInternalError,", "str) -> str: \"\"\"Return external ip from device.\"\"\" return status.external_ip", "data.\"\"\" return round(status.bytes_sent / 1000 / 1000 / 1000, 1)", "native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,", "= await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl = dslinterface[\"NewEnable\"]", "import utcnow from .common import FritzBoxBaseEntity, FritzBoxTools from .const import", "\"\"\"Describes Fritz sensor entity.\"\"\" connection_type: Literal[\"dsl\"] | None = None", "async_add_entities: AddEntitiesCallback ) -> None: \"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting up", "_retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str: \"\"\"Return external ip from", "1000, 1) # type: ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus, last_value: str)", "self.entity_description = description self._last_device_value: str | None = None self._attr_available", "description in SENSOR_TYPES if dsl or description.connection_type != DSL_CONNECTION ]", "), ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities:", "# type: ignore[no-any-return] def _retrieve_link_attenuation_received_state( status: FritzStatus, last_value: str )", "str) -> float: \"\"\"Return upload transmission rate.\"\"\" return round(status.transmission_rate[0] /", "\"\"\"Return upload link rate.\"\"\" return round(status.max_linked_bit_rate[0] / 1000, 1) #", "import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from", "name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download", "Literal from fritzconnection.core.exceptions import ( FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError,", "last_value: str ) -> float: \"\"\"Return download noise margin.\"\"\" return", "1) # type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) ->", "FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\",", "FRITZ!Box connectivity class.\"\"\" entity_description: FritzSensorEntityDescription def __init__( self, fritzbox_tools: FritzBoxTools,", "FritzActionError, FritzActionFailedError, FritzServiceError, ): pass entities = [ FritzBoxSensor(fritzbox_tools, entry.title,", "None ) -> datetime: \"\"\"Return uptime from connection.\"\"\" return _uptime_calculation(status.connection_uptime,", "Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link", "ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload", "type: ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "status: FritzStatus, last_value: str ) -> float: \"\"\"Return download noise", "type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "status: FritzStatus, last_value: str ) -> float: \"\"\"Return upload noise", "type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ),", "__init__( self, fritzbox_tools: FritzBoxTools, device_friendly_name: str, description: FritzSensorEntityDescription, ) ->", "return round(status.max_linked_bit_rate[1] / 1000, 1) # type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state(", "ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download", "FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device", "rate.\"\"\" return round(status.max_bit_rate[1] / 1000, 1) # type: ignore[no-any-return] def", "up FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if ( not", "state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING,", "from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND,", "value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), ) async def async_setup_entry( hass: HomeAssistant, entry:", "fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if ( not fritzbox_tools.connection or \"WANIPConn1\"", "download line attenuation.\"\"\" return status.attenuation[1] / 10 # type: ignore[no-any-return]", "_retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload total data.\"\"\"", "float: \"\"\"Return download total data.\"\"\" return round(status.bytes_received / 1000 /", "round(status.bytes_received / 1000 / 1000 / 1000, 1) # type:", "total data.\"\"\" return round(status.bytes_received / 1000 / 1000 / 1000,", "supported at the moment return dsl: bool = False try:", "def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download link", "import AddEntitiesCallback from homeassistant.util.dt import utcnow from .common import FritzBoxBaseEntity,", "_retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download link rate.\"\"\"", "_uptime_calculation(seconds_uptime: float, last_value: datetime | None) -> datetime: \"\"\"Calculate uptime", "upload total data.\"\"\" return round(status.bytes_sent / 1000 / 1000 /", "f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def update(self) -> None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating", "float: \"\"\"Return download noise margin.\"\"\" return status.noise_margin[1] / 10 #", "value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,", "FRITZ!Box\", exc_info=True) self._attr_available = False return self._attr_native_value = ( self._last_device_value", "upload noise margin.\"\"\" return status.noise_margin[0] / 10 # type: ignore[no-any-return]", "# type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float:", "round(status.transmission_rate[0] / 1000, 1) # type: ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus,", "from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from", "homeassistant.const import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, )", "key=\"link_kb_s_received\", name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription(", "def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload transmission", "_retrieve_link_attenuation_sent_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return upload", "upload link rate.\"\"\" return round(status.max_linked_bit_rate[0] / 1000, 1) # type:", "1) # type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value: str", "| None = None self._attr_available = True self._attr_name = f\"{device_friendly_name}", "def _retrieve_device_uptime_state( status: FritzStatus, last_value: datetime ) -> datetime: \"\"\"Return", "in fritzbox_tools.connection.services ): # Only routers are supported at the", "device_friendly_name) def update(self) -> None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\")", "1) # type: ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) ->", "= f\"{device_friendly_name} {description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def update(self)", "-> float: \"\"\"Return upload max transmission rate.\"\"\" return round(status.max_bit_rate[0] /", "| None) -> datetime: \"\"\"Calculate uptime with deviation.\"\"\" delta_uptime =", "AddEntitiesCallback from homeassistant.util.dt import utcnow from .common import FritzBoxBaseEntity, FritzBoxTools", "entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: \"\"\"Set up entry.\"\"\"", "collections.abc import Callable from dataclasses import dataclass from datetime import", "FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if ( not fritzbox_tools.connection", "FritzInternalError, FritzServiceError, ) from fritzconnection.lib.fritzstatus import FritzStatus from homeassistant.components.sensor import", "margin.\"\"\" return status.noise_margin[1] / 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state(", "SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback", "SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = ( FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\",", "= utcnow() - timedelta(seconds=seconds_uptime) if ( not last_value or abs((delta_uptime", "from device.\"\"\" return _uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state( status: FritzStatus, last_value:", "name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\",", "are supported at the moment return dsl: bool = False", "getting the state from the FRITZ!Box\", exc_info=True) self._attr_available = False", "-> None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\") try: status: FritzStatus", "_retrieve_connection_uptime_state( status: FritzStatus, last_value: datetime | None ) -> datetime:", "native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES,", "FritzActionFailedError, FritzServiceError, ): pass entities = [ FritzBoxSensor(fritzbox_tools, entry.title, description)", "\"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\") try: status: FritzStatus = self._fritzbox_tools.fritz_status", "self._attr_available = True except FritzConnectionException: _LOGGER.error(\"Error getting the state from", "name=\"Max Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription(", "!= DSL_CONNECTION ] async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box", "last_value: datetime | None ) -> datetime: \"\"\"Return uptime from", "import annotations from collections.abc import Callable from dataclasses import dataclass", "Callable from dataclasses import dataclass from datetime import datetime, timedelta", "None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\") try: status: FritzStatus =", "name=\"Link Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription(", "-> float: \"\"\"Return download line attenuation.\"\"\" return status.attenuation[1] / 10", "native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download Noise", "Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload", "device_friendly_name: str, description: FritzSensorEntityDescription, ) -> None: \"\"\"Init FRITZ!Box connectivity", "from the FRITZ!Box\", exc_info=True) self._attr_available = False return self._attr_native_value =", "\"\"\"Return download total data.\"\"\" return round(status.bytes_received / 1000 / 1000", ") from fritzconnection.lib.fritzstatus import FritzStatus from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT,", "# type: ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float:", "Fritz sensor entity.\"\"\" connection_type: Literal[\"dsl\"] | None = None SENSOR_TYPES:", "_retrieve_device_uptime_state( status: FritzStatus, last_value: datetime ) -> datetime: \"\"\"Return uptime", "round(status.max_linked_bit_rate[0] / 1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus,", "\"\"\"Return external ip from device.\"\"\" return status.external_ip # type: ignore[no-any-return]", "None self._attr_available = True self._attr_name = f\"{device_friendly_name} {description.name}\" self._attr_unique_id =", "def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload link", "10 # type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status: FritzStatus, last_value: str", "STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries import ConfigEntry from", "), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION,", "return round(status.bytes_sent / 1000 / 1000 / 1000, 1) #", "class FritzRequireKeysMixin: \"\"\"Fritz sensor data class.\"\"\" value_fn: Callable[[FritzStatus, Any], Any]", "from collections.abc import Callable from dataclasses import dataclass from datetime", "[ FritzBoxSensor(fritzbox_tools, entry.title, description) for description in SENSOR_TYPES if dsl", "FritzStatus, last_value: str) -> float: \"\"\"Return download max transmission rate.\"\"\"", "Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz sensor entity.\"\"\" connection_type:", "Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link", "name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\",", "await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl = dslinterface[\"NewEnable\"] except", "DSL_CONNECTION ] async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box connectivity", "10 # type: ignore[no-any-return] @dataclass class FritzRequireKeysMixin: \"\"\"Fritz sensor data", "_LOGGER.debug(\"Setting up FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if (", "at the moment return dsl: bool = False try: dslinterface", "last_value: str ) -> float: \"\"\"Return download line attenuation.\"\"\" return", "line attenuation.\"\"\" return status.attenuation[0] / 10 # type: ignore[no-any-return] def", "FritzStatus = self._fritzbox_tools.fritz_status self._attr_available = True except FritzConnectionException: _LOGGER.error(\"Error getting", "icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection Download Throughput\",", "| None = None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = ( FritzSensorEntityDescription(", "class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box connectivity class.\"\"\" entity_description: FritzSensorEntityDescription def", "FritzStatus, last_value: datetime | None ) -> datetime: \"\"\"Return uptime", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus, last_value:", "import dataclass from datetime import datetime, timedelta import logging from", "Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\",", "\"\"\"Fritz sensor data class.\"\"\" value_fn: Callable[[FritzStatus, Any], Any] @dataclass class", "@dataclass class FritzRequireKeysMixin: \"\"\"Fritz sensor data class.\"\"\" value_fn: Callable[[FritzStatus, Any],", "str) -> float: \"\"\"Return download total data.\"\"\" return round(status.bytes_received /", "\"\"\"Init FRITZ!Box connectivity class.\"\"\" self.entity_description = description self._last_device_value: str |", "last_value: str) -> float: \"\"\"Return download max transmission rate.\"\"\" return", "icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES,", "return round(status.max_bit_rate[0] / 1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status:", "SensorEntity): \"\"\"Define FRITZ!Box connectivity class.\"\"\" entity_description: FritzSensorEntityDescription def __init__( self,", "_LOGGER.debug(\"Updating FRITZ!Box sensors\") try: status: FritzStatus = self._fritzbox_tools.fritz_status self._attr_available =", "Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\",", "native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download Throughput\",", "datetime: \"\"\"Return uptime from connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status:", "datetime ) -> datetime: \"\"\"Return uptime from device.\"\"\" return _uptime_calculation(status.device_uptime,", "logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float, last_value: datetime | None) -> datetime:", "def _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download total", "FritzBoxTools = hass.data[DOMAIN][entry.entry_id] if ( not fritzbox_tools.connection or \"WANIPConn1\" not", "import FritzBoxBaseEntity, FritzBoxTools from .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER", "\"\"\"Return upload noise margin.\"\"\" return status.noise_margin[0] / 10 # type:", "or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION ): return delta_uptime return", "Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload", "/ 10 # type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status: FritzStatus, last_value:", "str) -> float: \"\"\"Return download link rate.\"\"\" return round(status.max_linked_bit_rate[1] /", ") -> None: \"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box sensors\")", "return round(status.transmission_rate[0] / 1000, 1) # type: ignore[no-any-return] def _retrieve_kb_s_received_state(status:", "last_value: str) -> float: \"\"\"Return upload max transmission rate.\"\"\" return", "self._attr_available = False return self._attr_native_value = ( self._last_device_value ) =", "download transmission rate.\"\"\" return round(status.transmission_rate[1] / 1000, 1) # type:", "def _retrieve_link_noise_margin_received_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return", "-> float: \"\"\"Return download transmission rate.\"\"\" return round(status.transmission_rate[1] / 1000,", "FritzStatus, last_value: str) -> float: \"\"\"Return download total data.\"\"\" return", "data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\") try: status: FritzStatus = self._fritzbox_tools.fritz_status self._attr_available", "_retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return upload", "if dsl or description.connection_type != DSL_CONNECTION ] async_add_entities(entities, True) class", "return delta_uptime return last_value def _retrieve_device_uptime_state( status: FritzStatus, last_value: datetime", "deviation.\"\"\" delta_uptime = utcnow() - timedelta(seconds=seconds_uptime) if ( not last_value", "transmission rate.\"\"\" return round(status.max_bit_rate[1] / 1000, 1) # type: ignore[no-any-return]", "...] = ( FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ),", "-> float: \"\"\"Return download total data.\"\"\" return round(status.bytes_received / 1000", "ip from device.\"\"\" return status.external_ip # type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status:", "Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), ) async", "status.attenuation[1] / 10 # type: ignore[no-any-return] @dataclass class FritzRequireKeysMixin: \"\"\"Fritz", "FritzRequireKeysMixin: \"\"\"Fritz sensor data class.\"\"\" value_fn: Callable[[FritzStatus, Any], Any] @dataclass", "HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utcnow from", "FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box connectivity class.\"\"\" entity_description: FritzSensorEntityDescription def __init__(", "dsl = dslinterface[\"NewEnable\"] except ( FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError, ):", "or \"WANIPConn1\" not in fritzbox_tools.connection.services ): # Only routers are", "Literal[\"dsl\"] | None = None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = (", "class.\"\"\" entity_description: FritzSensorEntityDescription def __init__( self, fritzbox_tools: FritzBoxTools, device_friendly_name: str,", "FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription(", "FritzStatus, last_value: datetime ) -> datetime: \"\"\"Return uptime from device.\"\"\"", "type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "\"\"\"Define FRITZ!Box connectivity class.\"\"\" entity_description: FritzSensorEntityDescription def __init__( self, fritzbox_tools:", "/ 1000 / 1000, 1) # type: ignore[no-any-return] def _retrieve_gb_received_state(status:", "not fritzbox_tools.connection or \"WANIPConn1\" not in fritzbox_tools.connection.services ): # Only", "float: \"\"\"Return download transmission rate.\"\"\" return round(status.transmission_rate[1] / 1000, 1)", "\"\"\"Return upload line attenuation.\"\"\" return status.attenuation[0] / 10 # type:", "from dataclasses import dataclass from datetime import datetime, timedelta import", "| None ) -> datetime: \"\"\"Return uptime from connection.\"\"\" return", "# type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:", "import ( FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError, ) from fritzconnection.lib.fritzstatus", "last_value: str) -> float: \"\"\"Return download link rate.\"\"\" return round(status.max_linked_bit_rate[1]", "data class.\"\"\" value_fn: Callable[[FritzStatus, Any], Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin):", "state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload Throughput\",", ") -> None: \"\"\"Init FRITZ!Box connectivity class.\"\"\" self.entity_description = description", "round(status.bytes_sent / 1000 / 1000 / 1000, 1) # type:", "description) for description in SENSOR_TYPES if dsl or description.connection_type !=", "def update(self) -> None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box sensors\") try:", "import Any, Literal from fritzconnection.core.exceptions import ( FritzActionError, FritzActionFailedError, FritzConnectionException,", "FritzServiceError, ): pass entities = [ FritzBoxSensor(fritzbox_tools, entry.title, description) for", "from __future__ import annotations from collections.abc import Callable from dataclasses", "Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\",", "ConfigEntry from homeassistant.const import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC,", "( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core", "super().__init__(fritzbox_tools, device_friendly_name) def update(self) -> None: \"\"\"Update data.\"\"\" _LOGGER.debug(\"Updating FRITZ!Box", "FritzBoxBaseEntity, FritzBoxTools from .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER =", "connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\",", "key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\",", "dsl: bool = False try: dslinterface = await hass.async_add_executor_job( fritzbox_tools.connection.call_action,", "datetime | None) -> datetime: \"\"\"Calculate uptime with deviation.\"\"\" delta_uptime", "key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\",", "), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ),", "- timedelta(seconds=seconds_uptime) if ( not last_value or abs((delta_uptime - last_value).total_seconds())", "type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status: FritzStatus, last_value: str ) ->", "ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import", "Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB", "ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download", "return status.attenuation[0] / 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_received_state( status:", "name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP,", "FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state,", "1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value: str)", "-> None: \"\"\"Init FRITZ!Box connectivity class.\"\"\" self.entity_description = description self._last_device_value:", "float: \"\"\"Return upload noise margin.\"\"\" return status.noise_margin[0] / 10 #", "fritzbox_tools: FritzBoxTools, device_friendly_name: str, description: FritzSensorEntityDescription, ) -> None: \"\"\"Init", "bool = False try: dslinterface = await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\",", "_LOGGER = logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float, last_value: datetime | None)", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status: FritzStatus, last_value:", "or description.connection_type != DSL_CONNECTION ] async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity):", "= None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = ( FritzSensorEntityDescription( key=\"external_ip\", name=\"External", "DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core import", "value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,", "exc_info=True) self._attr_available = False return self._attr_native_value = ( self._last_device_value )", "description: FritzSensorEntityDescription, ) -> None: \"\"\"Init FRITZ!Box connectivity class.\"\"\" self.entity_description", "status.noise_margin[1] / 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status: FritzStatus,", "homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import", "type: ignore[no-any-return] @dataclass class FritzRequireKeysMixin: \"\"\"Fritz sensor data class.\"\"\" value_fn:", "in SENSOR_TYPES if dsl or description.connection_type != DSL_CONNECTION ] async_add_entities(entities,", "str ) -> float: \"\"\"Return download line attenuation.\"\"\" return status.attenuation[1]", "delta_uptime = utcnow() - timedelta(seconds=seconds_uptime) if ( not last_value or", "last_value def _retrieve_device_uptime_state( status: FritzStatus, last_value: datetime ) -> datetime:", "f\"{device_friendly_name} {description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def update(self) ->", "line attenuation.\"\"\" return status.attenuation[1] / 10 # type: ignore[no-any-return] @dataclass", "): pass entities = [ FritzBoxSensor(fritzbox_tools, entry.title, description) for description", "def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download transmission", "DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform", "from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt", "10 # type: ignore[no-any-return] def _retrieve_link_attenuation_received_state( status: FritzStatus, last_value: str", "1) # type: ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) ->", "), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC,", "native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download Power", "total data.\"\"\" return round(status.bytes_sent / 1000 / 1000 / 1000,", "value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state,", "entity.\"\"\" connection_type: Literal[\"dsl\"] | None = None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...]", "last_value: str) -> float: \"\"\"Return upload total data.\"\"\" return round(status.bytes_sent", "float: \"\"\"Return download link rate.\"\"\" return round(status.max_linked_bit_rate[1] / 1000, 1)", "-> float: \"\"\"Return upload line attenuation.\"\"\" return status.attenuation[0] / 10", "rate.\"\"\" return round(status.transmission_rate[1] / 1000, 1) # type: ignore[no-any-return] def", "\"\"\"Calculate uptime with deviation.\"\"\" delta_uptime = utcnow() - timedelta(seconds=seconds_uptime) if", "= ( FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription(", "FritzSensorEntityDescription, ) -> None: \"\"\"Init FRITZ!Box connectivity class.\"\"\" self.entity_description =", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus, last_value:", "True self._attr_name = f\"{device_friendly_name} {description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name)", "\"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools =", "self._attr_name = f\"{device_friendly_name} {description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def", "the FRITZ!Box\", exc_info=True) self._attr_available = False return self._attr_native_value = (", "FRITZ!Box connectivity class.\"\"\" self.entity_description = description self._last_device_value: str | None", "entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\",", "1000, 1) # type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value:", "return dsl: bool = False try: dslinterface = await hass.async_add_executor_job(", "( FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError, ) from fritzconnection.lib.fritzstatus import", "None = None self._attr_available = True self._attr_name = f\"{device_friendly_name} {description.name}\"", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status: FritzStatus,", "sensor data class.\"\"\" value_fn: Callable[[FritzStatus, Any], Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription,", "type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value: str ) ->", "datetime: \"\"\"Calculate uptime with deviation.\"\"\" delta_uptime = utcnow() - timedelta(seconds=seconds_uptime)", "_retrieve_link_noise_margin_received_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return download", "from connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status: FritzStatus, last_value: str)", "with deviation.\"\"\" delta_uptime = utcnow() - timedelta(seconds=seconds_uptime) if ( not", "SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import", "import FritzStatus from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription,", "try: status: FritzStatus = self._fritzbox_tools.fritz_status self._attr_available = True except FritzConnectionException:", "# type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float:", "str) -> float: \"\"\"Return download max transmission rate.\"\"\" return round(status.max_bit_rate[1]", "/ 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status: FritzStatus, last_value:", "uptime from connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status: FritzStatus, last_value:", "import datetime, timedelta import logging from typing import Any, Literal", "= description self._last_device_value: str | None = None self._attr_available =", "str: \"\"\"Return external ip from device.\"\"\" return status.external_ip # type:", "status: FritzStatus, last_value: datetime ) -> datetime: \"\"\"Return uptime from", ") -> datetime: \"\"\"Return uptime from device.\"\"\" return _uptime_calculation(status.device_uptime, last_value)", "connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status: FritzStatus, last_value: str) ->", "1) # type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) ->", "device.\"\"\" return status.external_ip # type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus, last_value:", "native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection Upload Throughput\",", "try: dslinterface = await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl", "homeassistant.util.dt import utcnow from .common import FritzBoxBaseEntity, FritzBoxTools from .const", "float: \"\"\"Return upload line attenuation.\"\"\" return status.attenuation[0] / 10 #", "import ConfigEntry from homeassistant.const import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP,", "last_value) def _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str: \"\"\"Return external", "device.\"\"\" return _uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state( status: FritzStatus, last_value: datetime", "return round(status.max_bit_rate[1] / 1000, 1) # type: ignore[no-any-return] def _retrieve_gb_sent_state(status:", "_retrieve_link_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload link rate.\"\"\"", "fritzbox_tools.connection.services ): # Only routers are supported at the moment", "1000, 1) # type: ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str)", "native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND,", "ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload", "icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,", "FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError, ) from fritzconnection.lib.fritzstatus import FritzStatus from", "Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_kb_s_received\", name=\"Link Download", "{description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def update(self) -> None:", "last_value: str) -> float: \"\"\"Return download total data.\"\"\" return round(status.bytes_received", "-> float: \"\"\"Return download max transmission rate.\"\"\" return round(status.max_bit_rate[1] /", "value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\",", "datetime | None ) -> datetime: \"\"\"Return uptime from connection.\"\"\"", "= logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float, last_value: datetime | None) ->", "def _retrieve_link_attenuation_sent_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return", "return _uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state( status: FritzStatus, last_value: datetime |", "float, last_value: datetime | None) -> datetime: \"\"\"Calculate uptime with", "-> float: \"\"\"Return download link rate.\"\"\" return round(status.max_linked_bit_rate[1] / 1000,", "FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError, ) from fritzconnection.lib.fritzstatus import FritzStatus", "key=\"max_kb_s_received\", name=\"Max Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ),", "def _retrieve_link_attenuation_received_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return", "status: FritzStatus, last_value: datetime | None ) -> datetime: \"\"\"Return", "-> datetime: \"\"\"Return uptime from device.\"\"\" return _uptime_calculation(status.device_uptime, last_value) def", "last_value: str) -> str: \"\"\"Return external ip from device.\"\"\" return", "status: FritzStatus, last_value: str ) -> float: \"\"\"Return upload line", "FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription(", "FritzStatus, last_value: str) -> float: \"\"\"Return upload total data.\"\"\" return", "UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float, last_value: datetime |", "Any], Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz sensor entity.\"\"\"", "from typing import Any, Literal from fritzconnection.core.exceptions import ( FritzActionError,", "FRITZ!Box sensors\") try: status: FritzStatus = self._fritzbox_tools.fritz_status self._attr_available = True", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value:", "received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload", "( FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError, ): pass entities = [", "1000 / 1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_sent_state(status: FritzStatus,", "state from the FRITZ!Box\", exc_info=True) self._attr_available = False return self._attr_native_value", "from .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__) def", "Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT,", "( not last_value or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION ):", "FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz sensor entity.\"\"\" connection_type: Literal[\"dsl\"] | None", "from fritzconnection.lib.fritzstatus import FritzStatus from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING,", "str ) -> float: \"\"\"Return upload noise margin.\"\"\" return status.noise_margin[0]", "\"\"\"Return download max transmission rate.\"\"\" return round(status.max_bit_rate[1] / 1000, 1)", "UPTIME_DEVIATION ): return delta_uptime return last_value def _retrieve_device_uptime_state( status: FritzStatus,", "), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state,", "def _uptime_calculation(seconds_uptime: float, last_value: datetime | None) -> datetime: \"\"\"Calculate", "icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download Noise Margin\",", "# type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float:", "FritzStatus, last_value: str) -> float: \"\"\"Return upload link rate.\"\"\" return", "description.connection_type != DSL_CONNECTION ] async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define", "-> datetime: \"\"\"Return uptime from connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value) def", "FritzBoxTools, device_friendly_name: str, description: FritzSensorEntityDescription, ) -> None: \"\"\"Init FRITZ!Box", "homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DATA_GIGABYTES, DATA_RATE_KILOBITS_PER_SECOND, DATA_RATE_KILOBYTES_PER_SECOND,", "annotations from collections.abc import Callable from dataclasses import dataclass from", "str ) -> float: \"\"\"Return upload line attenuation.\"\"\" return status.attenuation[0]", "\"\"\"Return download link rate.\"\"\" return round(status.max_linked_bit_rate[1] / 1000, 1) #", "\"WANIPConn1\" not in fritzbox_tools.connection.services ): # Only routers are supported", "datetime: \"\"\"Return uptime from device.\"\"\" return _uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state(", "from device.\"\"\" return status.external_ip # type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus,", "entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state,", "key=\"max_kb_s_sent\", name=\"Max Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ),", "_retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download transmission rate.\"\"\"", "type: ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state,", "connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\",", "FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION,", "FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\",", "FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state,", "-> float: \"\"\"Return upload noise margin.\"\"\" return status.noise_margin[0] / 10", "type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status: FritzStatus, last_value: str ) ->", "attenuation.\"\"\" return status.attenuation[1] / 10 # type: ignore[no-any-return] @dataclass class", "logging from typing import Any, Literal from fritzconnection.core.exceptions import (", "-> float: \"\"\"Return download noise margin.\"\"\" return status.noise_margin[1] / 10", "value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS,", "FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError, ): pass entities = [ FritzBoxSensor(fritzbox_tools,", "hass.data[DOMAIN][entry.entry_id] if ( not fritzbox_tools.connection or \"WANIPConn1\" not in fritzbox_tools.connection.services", "sensors\") try: status: FritzStatus = self._fritzbox_tools.fritz_status self._attr_available = True except", "type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "float: \"\"\"Return upload transmission rate.\"\"\" return round(status.transmission_rate[0] / 1000, 1)", "device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription( key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC,", "True except FritzConnectionException: _LOGGER.error(\"Error getting the state from the FRITZ!Box\",", "status.attenuation[0] / 10 # type: ignore[no-any-return] def _retrieve_link_attenuation_received_state( status: FritzStatus,", "state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT,", "# type: ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float:", "( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries import ConfigEntry", "# type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status: FritzStatus, last_value: str )", "_retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload max transmission", "last_value: datetime ) -> datetime: \"\"\"Return uptime from device.\"\"\" return", "1000 / 1000 / 1000, 1) # type: ignore[no-any-return] def", "key=\"link_attenuation_sent\", name=\"Link Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ),", "1) # type: ignore[no-any-return] def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) ->", "_uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str: \"\"\"Return", "= True except FritzConnectionException: _LOGGER.error(\"Error getting the state from the", "DSL_CONNECTION, UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float, last_value: datetime", "Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), ) async def async_setup_entry(", "key=\"link_attenuation_received\", name=\"Link Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ),", "False return self._attr_native_value = ( self._last_device_value ) = self.entity_description.value_fn(status, self._last_device_value)", "Callable[[FritzStatus, Any], Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz sensor", "noise margin.\"\"\" return status.noise_margin[1] / 10 # type: ignore[no-any-return] def", "icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_attenuation_received\", name=\"Link Download Power Attenuation\",", "key=\"link_kb_s_sent\", name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription(", "Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), ) async def", "# type: ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status: FritzStatus, last_value: str )", "key=\"connection_uptime\", name=\"Connection Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload", "return status.noise_margin[0] / 10 # type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status:", "margin.\"\"\" return status.noise_margin[0] / 10 # type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state(", "async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None:", "connection_type: Literal[\"dsl\"] | None = None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] =", "transmission rate.\"\"\" return round(status.transmission_rate[1] / 1000, 1) # type: ignore[no-any-return]", "last_value: datetime | None) -> datetime: \"\"\"Calculate uptime with deviation.\"\"\"", "1000, 1) # type: ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus, last_value: str)", "fritzbox_tools.connection or \"WANIPConn1\" not in fritzbox_tools.connection.services ): # Only routers", "None: \"\"\"Set up entry.\"\"\" _LOGGER.debug(\"Setting up FRITZ!Box sensors\") fritzbox_tools: FritzBoxTools", "name=\"Link Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_noise_margin_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription(", "icon=\"mdi:upload\", value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\",", "entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,", "pass entities = [ FritzBoxSensor(fritzbox_tools, entry.title, description) for description in", "> UPTIME_DEVIATION ): return delta_uptime return last_value def _retrieve_device_uptime_state( status:", "datetime, timedelta import logging from typing import Any, Literal from", "= hass.data[DOMAIN][entry.entry_id] if ( not fritzbox_tools.connection or \"WANIPConn1\" not in", "rate.\"\"\" return round(status.max_bit_rate[0] / 1000, 1) # type: ignore[no-any-return] def", "FritzConnectionException: _LOGGER.error(\"Error getting the state from the FRITZ!Box\", exc_info=True) self._attr_available", "\"\"\"Return download transmission rate.\"\"\" return round(status.transmission_rate[1] / 1000, 1) #", "timedelta import logging from typing import Any, Literal from fritzconnection.core.exceptions", "not last_value or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION ): return", "), FritzSensorEntityDescription( key=\"link_attenuation_sent\", name=\"Link Upload Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_attenuation_sent_state,", "connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\",", "( FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state, ), FritzSensorEntityDescription( key=\"device_uptime\",", "icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), ) async def async_setup_entry( hass: HomeAssistant,", "DATA_RATE_KILOBYTES_PER_SECOND, DEVICE_CLASS_TIMESTAMP, ENTITY_CATEGORY_DIAGNOSTIC, SIGNAL_STRENGTH_DECIBELS, ) from homeassistant.core import HomeAssistant from", "status: FritzStatus, last_value: str ) -> float: \"\"\"Return download line", "value_fn=_retrieve_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"kb_s_received\", name=\"Download Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state,", "for description in SENSOR_TYPES if dsl or description.connection_type != DSL_CONNECTION", "10 # type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status: FritzStatus, last_value: str", "key=\"link_noise_margin_sent\", name=\"Link Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ),", "self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\" super().__init__(fritzbox_tools, device_friendly_name) def update(self) -> None: \"\"\"Update", "upload line attenuation.\"\"\" return status.attenuation[0] / 10 # type: ignore[no-any-return]", "_retrieve_link_attenuation_received_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return download", "ignore[no-any-return] def _retrieve_link_attenuation_sent_state( status: FritzStatus, last_value: str ) -> float:", "# type: ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus, last_value: str) -> float:", ".common import FritzBoxBaseEntity, FritzBoxTools from .const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION", "not in fritzbox_tools.connection.services ): # Only routers are supported at", "= self._fritzbox_tools.fritz_status self._attr_available = True except FritzConnectionException: _LOGGER.error(\"Error getting the", "def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) ->", "download link rate.\"\"\" return round(status.max_linked_bit_rate[1] / 1000, 1) # type:", "str | None = None self._attr_available = True self._attr_name =", "DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__) def _uptime_calculation(seconds_uptime: float, last_value:", "type: ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return", "Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max Connection", "HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: \"\"\"Set up", "/ 10 # type: ignore[no-any-return] @dataclass class FritzRequireKeysMixin: \"\"\"Fritz sensor", "device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND,", "status.noise_margin[0] / 10 # type: ignore[no-any-return] def _retrieve_link_noise_margin_received_state( status: FritzStatus,", "dataclass from datetime import datetime, timedelta import logging from typing", "# type: ignore[no-any-return] def _retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value: str )", "/ 1000, 1) # type: ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus, last_value:", "last_value: str ) -> float: \"\"\"Return upload noise margin.\"\"\" return", "utcnow from .common import FritzBoxBaseEntity, FritzBoxTools from .const import DOMAIN,", "str) -> float: \"\"\"Return upload max transmission rate.\"\"\" return round(status.max_bit_rate[0]", "def _retrieve_external_ip_state(status: FritzStatus, last_value: str) -> str: \"\"\"Return external ip", "), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state,", "ignore[no-any-return] def _retrieve_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download", "from fritzconnection.core.exceptions import ( FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError, )", "except FritzConnectionException: _LOGGER.error(\"Error getting the state from the FRITZ!Box\", exc_info=True)", "class.\"\"\" self.entity_description = description self._last_device_value: str | None = None", "abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION ): return delta_uptime return last_value", "False try: dslinterface = await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", )", "return status.external_ip # type: ignore[no-any-return] def _retrieve_kb_s_sent_state(status: FritzStatus, last_value: str)", "status: FritzStatus = self._fritzbox_tools.fritz_status self._attr_available = True except FritzConnectionException: _LOGGER.error(\"Error", "/ 1000 / 1000 / 1000, 1) # type: ignore[no-any-return]", "\"\"\"Return uptime from connection.\"\"\" return _uptime_calculation(status.connection_uptime, last_value) def _retrieve_external_ip_state(status: FritzStatus,", "Only routers are supported at the moment return dsl: bool", "entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_connection_uptime_state, ), FritzSensorEntityDescription( key=\"kb_s_sent\", name=\"Upload Throughput\", state_class=STATE_CLASS_MEASUREMENT, native_unit_of_measurement=DATA_RATE_KILOBYTES_PER_SECOND, icon=\"mdi:upload\",", "icon=\"mdi:download\", value_fn=_retrieve_kb_s_received_state, ), FritzSensorEntityDescription( key=\"max_kb_s_sent\", name=\"Max Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND,", "def __init__( self, fritzbox_tools: FritzBoxTools, device_friendly_name: str, description: FritzSensorEntityDescription, )", "noise margin.\"\"\" return status.noise_margin[0] / 10 # type: ignore[no-any-return] def", "round(status.max_bit_rate[1] / 1000, 1) # type: ignore[no-any-return] def _retrieve_gb_sent_state(status: FritzStatus,", "async_add_entities(entities, True) class FritzBoxSensor(FritzBoxBaseEntity, SensorEntity): \"\"\"Define FRITZ!Box connectivity class.\"\"\" entity_description:", "except ( FritzInternalError, FritzActionError, FritzActionFailedError, FritzServiceError, ): pass entities =", "1) # type: ignore[no-any-return] def _retrieve_gb_received_state(status: FritzStatus, last_value: str) ->", "Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\", name=\"Max", "def _retrieve_connection_uptime_state( status: FritzStatus, last_value: datetime | None ) ->", "rate.\"\"\" return round(status.transmission_rate[0] / 1000, 1) # type: ignore[no-any-return] def", "connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\", name=\"Link Download Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\",", "native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), ) async def async_setup_entry( hass:", "): # Only routers are supported at the moment return", "FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION,", "str) -> float: \"\"\"Return upload total data.\"\"\" return round(status.bytes_sent /", "Upload Noise Margin\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:upload\", value_fn=_retrieve_link_noise_margin_sent_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_received\",", "float: \"\"\"Return upload max transmission rate.\"\"\" return round(status.max_bit_rate[0] / 1000,", "homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utcnow from .common import", "def _retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download max", "uptime with deviation.\"\"\" delta_uptime = utcnow() - timedelta(seconds=seconds_uptime) if (", "typing import Any, Literal from fritzconnection.core.exceptions import ( FritzActionError, FritzActionFailedError,", "download total data.\"\"\" return round(status.bytes_received / 1000 / 1000 /", "_retrieve_max_kb_s_received_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return download max transmission", "), FritzSensorEntityDescription( key=\"device_uptime\", name=\"Device Uptime\", device_class=DEVICE_CLASS_TIMESTAMP, entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_device_uptime_state, ), FritzSensorEntityDescription(", "fritzconnection.core.exceptions import ( FritzActionError, FritzActionFailedError, FritzConnectionException, FritzInternalError, FritzServiceError, ) from", "FritzStatus from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, )", "-> float: \"\"\"Return upload link rate.\"\"\" return round(status.max_linked_bit_rate[0] / 1000,", ") -> float: \"\"\"Return download noise margin.\"\"\" return status.noise_margin[1] /", "rate.\"\"\" return round(status.max_linked_bit_rate[0] / 1000, 1) # type: ignore[no-any-return] def", "routers are supported at the moment return dsl: bool =", "Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_received_state, ), FritzSensorEntityDescription( key=\"gb_sent\", name=\"GB sent\",", "# Only routers are supported at the moment return dsl:", "None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = ( FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\",", "Download Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link", "\"\"\"AVM FRITZ!Box binary sensors.\"\"\" from __future__ import annotations from collections.abc", "if ( not last_value or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION", "download max transmission rate.\"\"\" return round(status.max_bit_rate[1] / 1000, 1) #", "float: \"\"\"Return download max transmission rate.\"\"\" return round(status.max_bit_rate[1] / 1000,", "sent\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:upload\", value_fn=_retrieve_gb_sent_state, ), FritzSensorEntityDescription( key=\"gb_received\", name=\"GB received\",", "from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util.dt import utcnow from .common", "tuple[FritzSensorEntityDescription, ...] = ( FritzSensorEntityDescription( key=\"external_ip\", name=\"External IP\", icon=\"mdi:earth\", value_fn=_retrieve_external_ip_state,", "Connection Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", entity_category=ENTITY_CATEGORY_DIAGNOSTIC, value_fn=_retrieve_max_kb_s_sent_state, ), FritzSensorEntityDescription( key=\"max_kb_s_received\",", ".const import DOMAIN, DSL_CONNECTION, UPTIME_DEVIATION _LOGGER = logging.getLogger(__name__) def _uptime_calculation(seconds_uptime:", "round(status.transmission_rate[1] / 1000, 1) # type: ignore[no-any-return] def _retrieve_max_kb_s_sent_state(status: FritzStatus,", "FritzRequireKeysMixin): \"\"\"Describes Fritz sensor entity.\"\"\" connection_type: Literal[\"dsl\"] | None =", "from datetime import datetime, timedelta import logging from typing import", "None) -> datetime: \"\"\"Calculate uptime with deviation.\"\"\" delta_uptime = utcnow()", "-> float: \"\"\"Return upload transmission rate.\"\"\" return round(status.transmission_rate[0] / 1000,", "str ) -> float: \"\"\"Return download noise margin.\"\"\" return status.noise_margin[1]", "connection_type=DSL_CONNECTION, ), ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry,", "name=\"Link Download Power Attenuation\", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, icon=\"mdi:download\", value_fn=_retrieve_link_attenuation_received_state, connection_type=DSL_CONNECTION, ), )", "self._attr_available = True self._attr_name = f\"{device_friendly_name} {description.name}\" self._attr_unique_id = f\"{fritzbox_tools.unique_id}-{description.key}\"", "FritzStatus, last_value: str) -> float: \"\"\"Return download link rate.\"\"\" return", "\"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl = dslinterface[\"NewEnable\"] except ( FritzInternalError, FritzActionError,", "dslinterface = await hass.async_add_executor_job( fritzbox_tools.connection.call_action, \"WANDSLInterfaceConfig:1\", \"GetInfo\", ) dsl =", "FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link Upload Throughput\", native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:upload\", value_fn=_retrieve_link_kb_s_sent_state, connection_type=DSL_CONNECTION, ),", "def _retrieve_max_kb_s_sent_state(status: FritzStatus, last_value: str) -> float: \"\"\"Return upload max", "__future__ import annotations from collections.abc import Callable from dataclasses import", "native_unit_of_measurement=DATA_RATE_KILOBITS_PER_SECOND, icon=\"mdi:download\", value_fn=_retrieve_link_kb_s_received_state, connection_type=DSL_CONNECTION, ), FritzSensorEntityDescription( key=\"link_noise_margin_sent\", name=\"Link Upload Noise", "last_value or abs((delta_uptime - last_value).total_seconds()) > UPTIME_DEVIATION ): return delta_uptime", "def _retrieve_link_noise_margin_sent_state( status: FritzStatus, last_value: str ) -> float: \"\"\"Return", "connectivity class.\"\"\" self.entity_description = description self._last_device_value: str | None =", "download noise margin.\"\"\" return status.noise_margin[1] / 10 # type: ignore[no-any-return]", "transmission rate.\"\"\" return round(status.transmission_rate[0] / 1000, 1) # type: ignore[no-any-return]", "uptime from device.\"\"\" return _uptime_calculation(status.device_uptime, last_value) def _retrieve_connection_uptime_state( status: FritzStatus,", "None = None SENSOR_TYPES: tuple[FritzSensorEntityDescription, ...] = ( FritzSensorEntityDescription( key=\"external_ip\",", "delta_uptime return last_value def _retrieve_device_uptime_state( status: FritzStatus, last_value: datetime )", "FritzStatus, last_value: str) -> float: \"\"\"Return upload max transmission rate.\"\"\"", "name=\"GB received\", state_class=STATE_CLASS_TOTAL_INCREASING, native_unit_of_measurement=DATA_GIGABYTES, icon=\"mdi:download\", value_fn=_retrieve_gb_received_state, ), FritzSensorEntityDescription( key=\"link_kb_s_sent\", name=\"Link", ") from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from", "value_fn: Callable[[FritzStatus, Any], Any] @dataclass class FritzSensorEntityDescription(SensorEntityDescription, FritzRequireKeysMixin): \"\"\"Describes Fritz", "self._last_device_value: str | None = None self._attr_available = True self._attr_name", "return round(status.max_linked_bit_rate[0] / 1000, 1) # type: ignore[no-any-return] def _retrieve_link_kb_s_received_state(status:", "import logging from typing import Any, Literal from fritzconnection.core.exceptions import" ]
[ "add(self, e): self.fields[e.rtype] = e def __str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda", "= e def __str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}: {v}\".format(n=f[0],", "derived (calculated) value, so it no longer makes sense to", "self.args = args self.args.reverse() def __str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args)", "defined that attribute, but in the subtype it is a", "to create multiple instances (doesn't hurt though) omitted = Omitted()", "so it no longer makes sense to explicitely assign value", "= {} def add(self, e): self.fields[e.rtype] = e def __str__(self):", "NUMBER(IfcScalarValue): pass @ifc_class class STRING(IfcScalarValue): pass @ifc_class class LOGICAL(IfcScalarValue): pass", "Resource type args: Arguments in *reverse* order, so you can", "values. \"\"\" def __init__(self, value): self.value = value def __str__(self):", "args): \"\"\" rtype: Resource type args: Arguments in *reverse* order,", "@ifc_class class INTEGER(IfcScalarValue): pass @ifc_class class NUMBER(IfcScalarValue): pass @ifc_class class", "class INTEGER(IfcScalarValue): pass @ifc_class class NUMBER(IfcScalarValue): pass @ifc_class class STRING(IfcScalarValue):", "so you can just args.pop() from it \"\"\" self.rtype =", "class-level, enough to reference, no need to create multiple instances", "class BOOLEAN(IfcScalarValue): pass @ifc_class class REAL(IfcScalarValue): pass @ifc_class class BINARY(IfcScalarValue):", "Omitted() class Reference: \"\"\" Refers to another entity by its", "class IfcScalarValue(IfcEntity): def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.value", "\"\"\" Generic IFC entity, only for subclassing from it \"\"\"", "args) self.args = args self.args.reverse() def __str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self),", "pass @ifc_class class INTEGER(IfcScalarValue): pass @ifc_class class NUMBER(IfcScalarValue): pass @ifc_class", "'*' it states that some supertype had defined that attribute,", "\"STEPHeader\", []) self.fields = {} def add(self, e): self.fields[e.rtype] =", "def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.value = args.pop()", "None # class-level, enough to reference, no need to create", "\"<omitted>\" def __json__(self): return None # class-level, enough to reference,", "subclassing from it \"\"\" def __init__(self, rtype, args): \"\"\" rtype:", "= value def __str__(self): return \"<.{val}.>\".format(val=self.value) def __json__(self): return self.value", "attribute, but in the subtype it is a derived (calculated)", "class IfcGenericEntity(IfcEntity): \"\"\" Generic IFC entity: type and args \"\"\"", "it no longer makes sense to explicitely assign value to", "explicitely assign value to it. \"\"\" # TODO: Haven't tried", "can be handled 'just as expected' def __init__(self): pass def", "pass def __str__(self): return \"<omitted>\" def __json__(self): return None #", "def __init__(self, rtype, args): \"\"\" rtype: Resource type args: Arguments", "__init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.args = args self.args.reverse()", "pass @ifc_class class STRING(IfcScalarValue): pass @ifc_class class LOGICAL(IfcScalarValue): pass class", "rtype, args) self.args = args self.args.reverse() def __str__(self): return \"Gen<{sup}>{a}\".format(", "rtype def __str__(self): return self.rtype def __json__(self): return {'rtype': self.rtype}", "__str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems()))) #", "pass @ifc_class class BINARY(IfcScalarValue): pass @ifc_class class INTEGER(IfcScalarValue): pass @ifc_class", "from Ifc.ClassRegistry import ifc_class, ifc_abstract_class, ifc_fallback_class @ifc_abstract_class class IfcEntity: \"\"\"", "need to create multiple instances (doesn't hurt though) omitted =", "args \"\"\" def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.args", "@ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\" Generic IFC entity: type and args", "def add(self, e): self.fields[e.rtype] = e def __str__(self): return \"STEPHeader({f})\".format(f=\",", "index \"\"\" def __init__(self, index): self.index = index def __str__(self):", "REAL(IfcScalarValue): pass @ifc_class class BINARY(IfcScalarValue): pass @ifc_class class INTEGER(IfcScalarValue): pass", "def __json__(self): return None # class-level, enough to reference, no", "rtype: Resource type args: Arguments in *reverse* order, so you", "though) omitted = Omitted() class Reference: \"\"\" Refers to another", "order, so you can just args.pop() from it \"\"\" self.rtype", "def __str__(self): return str(self.value) @ifc_class class BOOLEAN(IfcScalarValue): pass @ifc_class class", "return \"<omitted>\" def __json__(self): return None # class-level, enough to", "args): IfcEntity.__init__(self, rtype, args) self.args = args self.args.reverse() def __str__(self):", "__init__(self): IfcEntity.__init__(self, \"STEPHeader\", []) self.fields = {} def add(self, e):", "pass @ifc_class class REAL(IfcScalarValue): pass @ifc_class class BINARY(IfcScalarValue): pass @ifc_class", "self.rtype = rtype def __str__(self): return self.rtype def __json__(self): return", "and args \"\"\" def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args)", "__str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class class IfcScalarValue(IfcEntity): def __init__(self,", "\"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems()))) # vim: set sw=4 ts=4 et:", "IfcEntity.__init__(self, \"STEPHeader\", []) self.fields = {} def add(self, e): self.fields[e.rtype]", "enough to reference, no need to create multiple instances (doesn't", "@ifc_class class LOGICAL(IfcScalarValue): pass class Omitted: \"\"\" Marked with '*'", "value, so it no longer makes sense to explicitely assign", "by its index \"\"\" def __init__(self, index): self.index = index", "set of enumerated values. \"\"\" def __init__(self, value): self.value =", "hurt though) omitted = Omitted() class Reference: \"\"\" Refers to", "return None # class-level, enough to reference, no need to", "__str__(self): return \"<omitted>\" def __json__(self): return None # class-level, enough", "to explicitely assign value to it. \"\"\" # TODO: Haven't", "class EnumValue: \"\"\" Item from some set of enumerated values.", "\"\"\" Marked with '*' it states that some supertype had", "args: Arguments in *reverse* order, so you can just args.pop()", "@ifc_abstract_class class IfcEntity: \"\"\" Generic IFC entity, only for subclassing", "args) self.value = args.pop() def __str__(self): return str(self.value) @ifc_class class", "had defined that attribute, but in the subtype it is", "self.index} class EnumValue: \"\"\" Item from some set of enumerated", "can just args.pop() from it \"\"\" self.rtype = rtype def", "self.value @ifc_class class STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self, \"STEPHeader\", []) self.fields", "just args.pop() from it \"\"\" self.rtype = rtype def __str__(self):", "args.pop() from it \"\"\" self.rtype = rtype def __str__(self): return", "rtype, args): \"\"\" rtype: Resource type args: Arguments in *reverse*", "class Reference: \"\"\" Refers to another entity by its index", "to it. \"\"\" # TODO: Haven't tried if it can", "\"\"\" def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.args =", "IfcEntity.__init__(self, rtype, args) self.args = args self.args.reverse() def __str__(self): return", "'just as expected' def __init__(self): pass def __str__(self): return \"<omitted>\"", "{'ref': self.index} class EnumValue: \"\"\" Item from some set of", "Reference: \"\"\" Refers to another entity by its index \"\"\"", "@ifc_class class REAL(IfcScalarValue): pass @ifc_class class BINARY(IfcScalarValue): pass @ifc_class class", "[]) self.fields = {} def add(self, e): self.fields[e.rtype] = e", "is a derived (calculated) value, so it no longer makes", "LOGICAL(IfcScalarValue): pass class Omitted: \"\"\" Marked with '*' it states", "entity by its index \"\"\" def __init__(self, index): self.index =", "def __str__(self): return \"<.{val}.>\".format(val=self.value) def __json__(self): return self.value @ifc_class class", "\".join(map(lambda f: \"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems()))) # vim: set sw=4", "type and args \"\"\" def __init__(self, rtype, args): IfcEntity.__init__(self, rtype,", "@ifc_class class STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self, \"STEPHeader\", []) self.fields =", "tried if it can be handled 'just as expected' def", "enumerated values. \"\"\" def __init__(self, value): self.value = value def", "it. \"\"\" # TODO: Haven't tried if it can be", "ifc_abstract_class, ifc_fallback_class @ifc_abstract_class class IfcEntity: \"\"\" Generic IFC entity, only", "value to it. \"\"\" # TODO: Haven't tried if it", "class Omitted: \"\"\" Marked with '*' it states that some", "return self.value @ifc_class class STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self, \"STEPHeader\", [])", "__json__(self): return self.value @ifc_class class STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self, \"STEPHeader\",", "@ifc_class class NUMBER(IfcScalarValue): pass @ifc_class class STRING(IfcScalarValue): pass @ifc_class class", "Omitted: \"\"\" Marked with '*' it states that some supertype", "from it \"\"\" def __init__(self, rtype, args): \"\"\" rtype: Resource", "BOOLEAN(IfcScalarValue): pass @ifc_class class REAL(IfcScalarValue): pass @ifc_class class BINARY(IfcScalarValue): pass", "INTEGER(IfcScalarValue): pass @ifc_class class NUMBER(IfcScalarValue): pass @ifc_class class STRING(IfcScalarValue): pass", "pass @ifc_class class LOGICAL(IfcScalarValue): pass class Omitted: \"\"\" Marked with", "\"\"\" Item from some set of enumerated values. \"\"\" def", "@ifc_class class BINARY(IfcScalarValue): pass @ifc_class class INTEGER(IfcScalarValue): pass @ifc_class class", "__init__(self, value): self.value = value def __str__(self): return \"<.{val}.>\".format(val=self.value) def", "\"<.{val}.>\".format(val=self.value) def __json__(self): return self.value @ifc_class class STEPHeader(IfcEntity): def __init__(self):", "create multiple instances (doesn't hurt though) omitted = Omitted() class", "IfcEntity.__init__(self, rtype, args) self.value = args.pop() def __str__(self): return str(self.value)", "with '*' it states that some supertype had defined that", "__json__(self): return {'rtype': self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\" Generic IFC", "as expected' def __init__(self): pass def __str__(self): return \"<omitted>\" def", "class STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self, \"STEPHeader\", []) self.fields = {}", "def __str__(self): return \"<#{idx}>\".format(idx=self.index) def __json__(self): return {'ref': self.index} class", "TODO: Haven't tried if it can be handled 'just as", "handled 'just as expected' def __init__(self): pass def __str__(self): return", "IFC entity, only for subclassing from it \"\"\" def __init__(self,", "args self.args.reverse() def __str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class class", "rtype, args): IfcEntity.__init__(self, rtype, args) self.value = args.pop() def __str__(self):", "class LOGICAL(IfcScalarValue): pass class Omitted: \"\"\" Marked with '*' it", "\"<#{idx}>\".format(idx=self.index) def __json__(self): return {'ref': self.index} class EnumValue: \"\"\" Item", "__init__(self): pass def __str__(self): return \"<omitted>\" def __json__(self): return None", "a=self.args) @ifc_class class IfcScalarValue(IfcEntity): def __init__(self, rtype, args): IfcEntity.__init__(self, rtype,", "but in the subtype it is a derived (calculated) value,", "index): self.index = index def __str__(self): return \"<#{idx}>\".format(idx=self.index) def __json__(self):", "@ifc_class class STRING(IfcScalarValue): pass @ifc_class class LOGICAL(IfcScalarValue): pass class Omitted:", "the subtype it is a derived (calculated) value, so it", "sense to explicitely assign value to it. \"\"\" # TODO:", "BINARY(IfcScalarValue): pass @ifc_class class INTEGER(IfcScalarValue): pass @ifc_class class NUMBER(IfcScalarValue): pass", "multiple instances (doesn't hurt though) omitted = Omitted() class Reference:", "args): IfcEntity.__init__(self, rtype, args) self.value = args.pop() def __str__(self): return", "__json__(self): return {'ref': self.index} class EnumValue: \"\"\" Item from some", "entity, only for subclassing from it \"\"\" def __init__(self, rtype,", "it \"\"\" def __init__(self, rtype, args): \"\"\" rtype: Resource type", "def __init__(self, index): self.index = index def __str__(self): return \"<#{idx}>\".format(idx=self.index)", "self.args.reverse() def __str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class class IfcScalarValue(IfcEntity):", "ifc_fallback_class @ifc_abstract_class class IfcEntity: \"\"\" Generic IFC entity, only for", "Haven't tried if it can be handled 'just as expected'", "\"\"\" rtype: Resource type args: Arguments in *reverse* order, so", "IfcGenericEntity(IfcEntity): \"\"\" Generic IFC entity: type and args \"\"\" def", "Item from some set of enumerated values. \"\"\" def __init__(self,", "in *reverse* order, so you can just args.pop() from it", "@ifc_class class IfcScalarValue(IfcEntity): def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args)", "e): self.fields[e.rtype] = e def __str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f:", "from it \"\"\" self.rtype = rtype def __str__(self): return self.rtype", "self.fields[e.rtype] = e def __str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}:", "omitted = Omitted() class Reference: \"\"\" Refers to another entity", "if it can be handled 'just as expected' def __init__(self):", "def __str__(self): return self.rtype def __json__(self): return {'rtype': self.rtype} @ifc_fallback_class", "value def __str__(self): return \"<.{val}.>\".format(val=self.value) def __json__(self): return self.value @ifc_class", "it \"\"\" self.rtype = rtype def __str__(self): return self.rtype def", "def __json__(self): return {'rtype': self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\" Generic", "def __json__(self): return {'ref': self.index} class EnumValue: \"\"\" Item from", "IFC entity: type and args \"\"\" def __init__(self, rtype, args):", "it states that some supertype had defined that attribute, but", "in the subtype it is a derived (calculated) value, so", "supertype had defined that attribute, but in the subtype it", "import ifc_class, ifc_abstract_class, ifc_fallback_class @ifc_abstract_class class IfcEntity: \"\"\" Generic IFC", "assign value to it. \"\"\" # TODO: Haven't tried if", "class NUMBER(IfcScalarValue): pass @ifc_class class STRING(IfcScalarValue): pass @ifc_class class LOGICAL(IfcScalarValue):", "of enumerated values. \"\"\" def __init__(self, value): self.value = value", "be handled 'just as expected' def __init__(self): pass def __str__(self):", "__init__(self, rtype, args): \"\"\" rtype: Resource type args: Arguments in", "type args: Arguments in *reverse* order, so you can just", "EnumValue: \"\"\" Item from some set of enumerated values. \"\"\"", "str(self.value) @ifc_class class BOOLEAN(IfcScalarValue): pass @ifc_class class REAL(IfcScalarValue): pass @ifc_class", "some supertype had defined that attribute, but in the subtype", "instances (doesn't hurt though) omitted = Omitted() class Reference: \"\"\"", "(doesn't hurt though) omitted = Omitted() class Reference: \"\"\" Refers", "you can just args.pop() from it \"\"\" self.rtype = rtype", "{'rtype': self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\" Generic IFC entity: type", "subtype it is a derived (calculated) value, so it no", "self.fields = {} def add(self, e): self.fields[e.rtype] = e def", "\"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems()))) # vim: set", "Generic IFC entity, only for subclassing from it \"\"\" def", "return str(self.value) @ifc_class class BOOLEAN(IfcScalarValue): pass @ifc_class class REAL(IfcScalarValue): pass", "(calculated) value, so it no longer makes sense to explicitely", "value): self.value = value def __str__(self): return \"<.{val}.>\".format(val=self.value) def __json__(self):", "def __str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems())))", "self.index = index def __str__(self): return \"<#{idx}>\".format(idx=self.index) def __json__(self): return", "from some set of enumerated values. \"\"\" def __init__(self, value):", "__json__(self): return None # class-level, enough to reference, no need", "__init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.value = args.pop() def", "class REAL(IfcScalarValue): pass @ifc_class class BINARY(IfcScalarValue): pass @ifc_class class INTEGER(IfcScalarValue):", "pass class Omitted: \"\"\" Marked with '*' it states that", "class IfcEntity: \"\"\" Generic IFC entity, only for subclassing from", "Refers to another entity by its index \"\"\" def __init__(self,", "= index def __str__(self): return \"<#{idx}>\".format(idx=self.index) def __json__(self): return {'ref':", "__str__(self): return str(self.value) @ifc_class class BOOLEAN(IfcScalarValue): pass @ifc_class class REAL(IfcScalarValue):", "that attribute, but in the subtype it is a derived", "\"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class class IfcScalarValue(IfcEntity): def __init__(self, rtype, args):", "def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.args = args", "index def __str__(self): return \"<#{idx}>\".format(idx=self.index) def __json__(self): return {'ref': self.index}", "return \"<.{val}.>\".format(val=self.value) def __json__(self): return self.value @ifc_class class STEPHeader(IfcEntity): def", "return {'rtype': self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\" Generic IFC entity:", "sup=IfcEntity.__str__(self), a=self.args) @ifc_class class IfcScalarValue(IfcEntity): def __init__(self, rtype, args): IfcEntity.__init__(self,", "__str__(self): return self.rtype def __json__(self): return {'rtype': self.rtype} @ifc_fallback_class class", "@ifc_class class BOOLEAN(IfcScalarValue): pass @ifc_class class REAL(IfcScalarValue): pass @ifc_class class", "it is a derived (calculated) value, so it no longer", "return \"<#{idx}>\".format(idx=self.index) def __json__(self): return {'ref': self.index} class EnumValue: \"\"\"", "return {'ref': self.index} class EnumValue: \"\"\" Item from some set", "self.value = value def __str__(self): return \"<.{val}.>\".format(val=self.value) def __json__(self): return", "class BINARY(IfcScalarValue): pass @ifc_class class INTEGER(IfcScalarValue): pass @ifc_class class NUMBER(IfcScalarValue):", "ifc_class, ifc_abstract_class, ifc_fallback_class @ifc_abstract_class class IfcEntity: \"\"\" Generic IFC entity,", "STRING(IfcScalarValue): pass @ifc_class class LOGICAL(IfcScalarValue): pass class Omitted: \"\"\" Marked", "Arguments in *reverse* order, so you can just args.pop() from", "IfcEntity: \"\"\" Generic IFC entity, only for subclassing from it", "e def __str__(self): return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}: {v}\".format(n=f[0], v=str(f[1])),", "= args self.args.reverse() def __str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class", "rtype, args) self.value = args.pop() def __str__(self): return str(self.value) @ifc_class", "def __json__(self): return self.value @ifc_class class STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self,", "self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\" Generic IFC entity: type and", "\"\"\" def __init__(self, value): self.value = value def __str__(self): return", "some set of enumerated values. \"\"\" def __init__(self, value): self.value", "return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class class IfcScalarValue(IfcEntity): def __init__(self, rtype,", "to reference, no need to create multiple instances (doesn't hurt", "Ifc.ClassRegistry import ifc_class, ifc_abstract_class, ifc_fallback_class @ifc_abstract_class class IfcEntity: \"\"\" Generic", "states that some supertype had defined that attribute, but in", "def __init__(self): pass def __str__(self): return \"<omitted>\" def __json__(self): return", "\"\"\" self.rtype = rtype def __str__(self): return self.rtype def __json__(self):", "Generic IFC entity: type and args \"\"\" def __init__(self, rtype,", "no need to create multiple instances (doesn't hurt though) omitted", "reference, no need to create multiple instances (doesn't hurt though)", "\"\"\" Refers to another entity by its index \"\"\" def", "self.value = args.pop() def __str__(self): return str(self.value) @ifc_class class BOOLEAN(IfcScalarValue):", "\"\"\" Generic IFC entity: type and args \"\"\" def __init__(self,", "def __init__(self, value): self.value = value def __str__(self): return \"<.{val}.>\".format(val=self.value)", "rtype, args): IfcEntity.__init__(self, rtype, args) self.args = args self.args.reverse() def", "Marked with '*' it states that some supertype had defined", "__str__(self): return \"<.{val}.>\".format(val=self.value) def __json__(self): return self.value @ifc_class class STEPHeader(IfcEntity):", "\"\"\" def __init__(self, index): self.index = index def __str__(self): return", "IfcScalarValue(IfcEntity): def __init__(self, rtype, args): IfcEntity.__init__(self, rtype, args) self.value =", "pass @ifc_class class NUMBER(IfcScalarValue): pass @ifc_class class STRING(IfcScalarValue): pass @ifc_class", "that some supertype had defined that attribute, but in the", "makes sense to explicitely assign value to it. \"\"\" #", "its index \"\"\" def __init__(self, index): self.index = index def", "longer makes sense to explicitely assign value to it. \"\"\"", "\"\"\" # TODO: Haven't tried if it can be handled", "only for subclassing from it \"\"\" def __init__(self, rtype, args):", "self.rtype def __json__(self): return {'rtype': self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity): \"\"\"", "__init__(self, index): self.index = index def __str__(self): return \"<#{idx}>\".format(idx=self.index) def", "def __str__(self): return \"Gen<{sup}>{a}\".format( sup=IfcEntity.__str__(self), a=self.args) @ifc_class class IfcScalarValue(IfcEntity): def", "entity: type and args \"\"\" def __init__(self, rtype, args): IfcEntity.__init__(self,", "a derived (calculated) value, so it no longer makes sense", "# TODO: Haven't tried if it can be handled 'just", "__str__(self): return \"<#{idx}>\".format(idx=self.index) def __json__(self): return {'ref': self.index} class EnumValue:", "# class-level, enough to reference, no need to create multiple", "to another entity by its index \"\"\" def __init__(self, index):", "\"\"\" def __init__(self, rtype, args): \"\"\" rtype: Resource type args:", "= rtype def __str__(self): return self.rtype def __json__(self): return {'rtype':", "STEPHeader(IfcEntity): def __init__(self): IfcEntity.__init__(self, \"STEPHeader\", []) self.fields = {} def", "*reverse* order, so you can just args.pop() from it \"\"\"", "no longer makes sense to explicitely assign value to it.", "= args.pop() def __str__(self): return str(self.value) @ifc_class class BOOLEAN(IfcScalarValue): pass", "def __init__(self): IfcEntity.__init__(self, \"STEPHeader\", []) self.fields = {} def add(self,", "= Omitted() class Reference: \"\"\" Refers to another entity by", "f: \"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems()))) # vim: set sw=4 ts=4", "return self.rtype def __json__(self): return {'rtype': self.rtype} @ifc_fallback_class class IfcGenericEntity(IfcEntity):", "expected' def __init__(self): pass def __str__(self): return \"<omitted>\" def __json__(self):", "{} def add(self, e): self.fields[e.rtype] = e def __str__(self): return", "args.pop() def __str__(self): return str(self.value) @ifc_class class BOOLEAN(IfcScalarValue): pass @ifc_class", "it can be handled 'just as expected' def __init__(self): pass", "for subclassing from it \"\"\" def __init__(self, rtype, args): \"\"\"", "def __str__(self): return \"<omitted>\" def __json__(self): return None # class-level,", "another entity by its index \"\"\" def __init__(self, index): self.index", "class STRING(IfcScalarValue): pass @ifc_class class LOGICAL(IfcScalarValue): pass class Omitted: \"\"\"", "return \"STEPHeader({f})\".format(f=\", \".join(map(lambda f: \"{n}: {v}\".format(n=f[0], v=str(f[1])), self.fields.iteritems()))) # vim:" ]
[ "element): if element not in self.data_dict: LOG.error(\"Error: invalid element requested", "self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node %s (%s) is experiencing high", "ts # LOG.debug(\"%s: e = %s, v= %f\" % (self.node,", "%d\" % (self.node, ma_sma, ma_med, ma_lar, self.congestion_await_sustained)) return self.congestion_status def", "logging import os from io_monitor.constants import DOMAIN from io_monitor.utils.data_window import", "# # Copyright (c) 2016 Wind River Systems, Inc. #", "self.name)) elif ma_sma < self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL if self.congestion_status", "%9.2f ]\" % ( element, self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element,", "DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self): # Bail if threshold is not", "self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element): return \"%s", "# Device status STATUS_NORMAL = \"N\" STATUS_BUILDING = \"B\" STATUS_CONGESTED", "-1} self.timestamp = None self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike = -1", "= %s\" % window) return 0 if element not in", "update_congestion_status(self): # Bail if threshold is not set if self.congestion_await_sustained", "element requested = %s\" % element) return 0 return self.data_dict[element][window].get_average()", "= -1 for element in data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True),", "if os.path.exists('/sys/block/' + self.node + '/dm/name'): self.name = open('/sys/block/' +", "self.congestion_await_sustained = await_sustained_congestion def get_element_windows_avg_list(self, element): return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element,", "= self.STATUS_NORMAL self.congestion_await_minimal_spike = -1 self.congestion_await_sustained = -1 for element", "STATUS_NORMAL = \"N\" STATUS_BUILDING = \"B\" STATUS_CONGESTED = \"L\" #", "Device status STATUS_NORMAL = \"N\" STATUS_BUILDING = \"B\" STATUS_CONGESTED =", "experiencing high await times.\" % (self.node, self.name)) elif ma_sma <", "self.node + '/dm/name'): self.name = open('/sys/block/' + self.node + '/dm/name',", "= logging.getLogger(DOMAIN) class DeviceDataCollector(object): # Moving average windows MA_WINDOW_SMA =", "cap): if element in self.data_caps: self.data_caps[element] = cap def set_congestion_thresholds(self,", "# Set the congestion status based on await moving average", "window) return 0 if element not in self.data_dict: LOG.error(\"Error: invalid", "status STATUS_NORMAL = \"N\" STATUS_BUILDING = \"B\" STATUS_CONGESTED = \"L\"", "self.congestion_status = self.STATUS_NORMAL if self.congestion_status is self.STATUS_CONGESTED: if ma_med <", "self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike = -1 self.congestion_await_sustained = -1 for", "def set_data_caps(self, element, cap): if element in self.data_caps: self.data_caps[element] =", "%6.2f %6.2f %6.2f ] %d\" % (self.node, ma_sma, ma_med, ma_lar,", "await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained = await_sustained_congestion def get_element_windows_avg_list(self, element):", "is self.STATUS_NORMAL: if ma_sma > self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING if", "is_data_stale(self, ts): return not (ts == self.timestamp) def get_congestion_status(self, debug=False):", "self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained = await_sustained_congestion def get_element_windows_avg_list(self, element): return", "ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar =", "elif ma_sma < self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL if self.congestion_status is", "moving average if self.congestion_status is self.STATUS_NORMAL: if ma_sma > self.congestion_await_sustained:", "Inc. # # SPDX-License-Identifier: Apache-2.0 # import logging import os", "LOG.error(\"Error: invalid element requested = %s\" % element) return 0", "ma_lar, self.congestion_await_sustained)) return self.congestion_status def set_data_caps(self, element, cap): if element", "Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import logging import", "= device_node if os.path.exists('/sys/block/' + self.node + '/dm/name'): self.name =", "if ma_sma > self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING if self.congestion_status is", "= {self.DATA_AWAIT: -1, self.DATA_IOPS: -1} self.timestamp = None self.congestion_status =", "windows MA_WINDOW_SMA = 0 MA_WINDOW_MED = 1 MA_WINDOW_LAR = 2", "self.data_caps[element] = cap def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike", "self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self, element): if element not in", "w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self, element):", "# # SPDX-License-Identifier: Apache-2.0 # import logging import os from", "self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element): return \"%s [ %9.2f,", "self.data_caps = {self.DATA_AWAIT: -1, self.DATA_IOPS: -1} self.timestamp = None self.congestion_status", "softtabstop=4 # # Copyright (c) 2016 Wind River Systems, Inc.", "\"L\" # Data tracked DATA_IOPS = \"iops\" DATA_AWAIT = \"await\"", "self.name = open('/sys/block/' + self.node + '/dm/name', 'r').read().rstrip() else: self.name", "self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self):", "return ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar", "requested = %s\" % element) return 0 return self.data_dict[element][window].get_average() def", "self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set the congestion", "ts, element, value): self.timestamp = ts # LOG.debug(\"%s: e =", "based on await moving average if self.congestion_status is self.STATUS_NORMAL: if", "= \"B\" STATUS_CONGESTED = \"L\" # Data tracked DATA_IOPS =", "status based on await moving average if self.congestion_status is self.STATUS_NORMAL:", "\"B\" STATUS_CONGESTED = \"L\" # Data tracked DATA_IOPS = \"iops\"", "element): return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self,", "window): if window not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid", "%6.2f ] %d\" % (self.node, ma_sma, ma_med, ma_lar, self.congestion_await_sustained)) return", "self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set the congestion status", "self.congestion_status = self.STATUS_BUILDING if self.congestion_status is self.STATUS_BUILDING: if ma_lar >", "+ self.node + '/dm/name'): self.name = open('/sys/block/' + self.node +", "{} self.data_caps = {self.DATA_AWAIT: -1, self.DATA_IOPS: -1} self.timestamp = None", "def get_congestion_status(self, debug=False): if debug: ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med", "self.STATUS_NORMAL if self.congestion_status is self.STATUS_CONGESTED: if ma_med < self.congestion_await_sustained: self.congestion_status", "requested = %s\" % window) return 0 if element not", "await_sustained_congestion def get_element_windows_avg_list(self, element): return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element,", "ma_sma < self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL if self.congestion_status is self.STATUS_CONGESTED:", "MA_WINDOW_SMA = 0 MA_WINDOW_MED = 1 MA_WINDOW_LAR = 2 #", "ma_med < self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING def update_data(self, ts, element,", "self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s", "% (self.node, self.name)) elif ma_sma < self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL", "import os from io_monitor.constants import DOMAIN from io_monitor.utils.data_window import DataCollectionWindow", "= 0 MA_WINDOW_MED = 1 MA_WINDOW_LAR = 2 # Device", "self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set the congestion status based on await", "%s (%s) is experiencing high await times.\" % (self.node, self.name))", "= self.node self.data_dict = {} self.data_caps = {self.DATA_AWAIT: -1, self.DATA_IOPS:", "-1 for element in data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med,", "on await moving average if self.congestion_status is self.STATUS_NORMAL: if ma_sma", "= await_minimal_spike self.congestion_await_sustained = await_sustained_congestion def get_element_windows_avg_list(self, element): return [self.get_average(element,", "def update_congestion_status(self): # Bail if threshold is not set if", "\"N\" STATUS_BUILDING = \"B\" STATUS_CONGESTED = \"L\" # Data tracked", "import DOMAIN from io_monitor.utils.data_window import DataCollectionWindow LOG = logging.getLogger(DOMAIN) class", "self.STATUS_CONGESTED LOG.warn(\"Node %s (%s) is experiencing high await times.\" %", "% (self.node, ma_sma, ma_med, ma_lar, self.congestion_await_sustained)) return self.congestion_status def set_data_caps(self,", "e = %s, v= %f\" % (self.node, element, value)) for", "%6.2f %6.2f ] %d\" % (self.node, ma_sma, ma_med, ma_lar, self.congestion_await_sustained))", "size_med, size_lar): self.node = device_node if os.path.exists('/sys/block/' + self.node +", "def get_latest(self, element): if element not in self.data_dict: LOG.error(\"Error: invalid", "in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self, element): if", "-1: return ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED)", "if element not in self.data_dict: LOG.error(\"Error: invalid element requested =", "% window) return 0 if element not in self.data_dict: LOG.error(\"Error:", "self.congestion_await_minimal_spike = -1 self.congestion_await_sustained = -1 for element in data_elements:", "is self.STATUS_CONGESTED: if ma_med < self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING def", "self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) #", "]\" % ( element, self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR))", "River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import logging", "return 0 return self.data_dict[element][window].get_average() def is_data_stale(self, ts): return not (ts", "device_node, data_elements, size_sma, size_med, size_lar): self.node = device_node if os.path.exists('/sys/block/'", "Bail if threshold is not set if self.congestion_await_sustained == -1:", "-1 self.congestion_await_sustained = -1 for element in data_elements: self.data_dict.update({element: [", "element in self.data_caps: self.data_caps[element] = cap def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion):", "(self.node, element, value)) for w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value,", "self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window requested = %s\" % window) return", "def __init__(self, device_node, data_elements, size_sma, size_med, size_lar): self.node = device_node", "def get_element_windows_avg_list(self, element): return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)]", "Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import", "if self.congestion_status is self.STATUS_NORMAL: if ma_sma > self.congestion_await_sustained: self.congestion_status =", "def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained = await_sustained_congestion", "stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self): # Bail if threshold is", "(%s) is experiencing high await times.\" % (self.node, self.name)) elif", "0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element, window): if window not", "debug: ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar", "data_elements, size_sma, size_med, size_lar): self.node = device_node if os.path.exists('/sys/block/' +", "self.congestion_status is self.STATUS_NORMAL: if ma_sma > self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING", "self.MA_WINDOW_LAR) # Set the congestion status based on await moving", "LOG.error(\"WindowError: invalid window requested = %s\" % window) return 0", "if ma_med < self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING def update_data(self, ts,", "is not set if self.congestion_await_sustained == -1: return ma_sma =", "% element) return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element, window):", "(ts == self.timestamp) def get_congestion_status(self, debug=False): if debug: ma_sma =", "self.STATUS_NORMAL self.congestion_await_minimal_spike = -1 self.congestion_await_sustained = -1 for element in", "self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element): return \"%s [ %9.2f, %9.2f,", "self.congestion_status is self.STATUS_BUILDING: if ma_lar > self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED", "{self.DATA_AWAIT: -1, self.DATA_IOPS: -1} self.timestamp = None self.congestion_status = self.STATUS_NORMAL", "= 1 MA_WINDOW_LAR = 2 # Device status STATUS_NORMAL =", "self.STATUS_CONGESTED: if ma_med < self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING def update_data(self,", "%f\" % (self.node, element, value)) for w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED,", "DATA_IOPS = \"iops\" DATA_AWAIT = \"await\" def __init__(self, device_node, data_elements,", "device_node if os.path.exists('/sys/block/' + self.node + '/dm/name'): self.name = open('/sys/block/'", "not (ts == self.timestamp) def get_congestion_status(self, debug=False): if debug: ma_sma", "element, value)) for w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element])", "self.STATUS_BUILDING: if ma_lar > self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node %s", "stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self): # Bail if", "Apache-2.0 # import logging import os from io_monitor.constants import DOMAIN", "< self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING def update_data(self, ts, element, value):", "[ %9.2f, %9.2f, %9.2f ]\" % ( element, self.get_average(element, self.MA_WINDOW_SMA),", "'/dm/name'): self.name = open('/sys/block/' + self.node + '/dm/name', 'r').read().rstrip() else:", "# Data tracked DATA_IOPS = \"iops\" DATA_AWAIT = \"await\" def", "= ts # LOG.debug(\"%s: e = %s, v= %f\" %", "self.STATUS_BUILDING if self.congestion_status is self.STATUS_BUILDING: if ma_lar > self.congestion_await_sustained: self.congestion_status", "v= %f\" % (self.node, element, value)) for w in [self.MA_WINDOW_SMA,", "if ma_lar > self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node %s (%s)", "await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained = await_sustained_congestion def get_element_windows_avg_list(self,", "= None self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike = -1 self.congestion_await_sustained =", "= self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set the", "0 return self.data_dict[element][window].get_average() def is_data_stale(self, ts): return not (ts ==", "STATUS_CONGESTED = \"L\" # Data tracked DATA_IOPS = \"iops\" DATA_AWAIT", "window not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window requested", "2 # Device status STATUS_NORMAL = \"N\" STATUS_BUILDING = \"B\"", "SPDX-License-Identifier: Apache-2.0 # import logging import os from io_monitor.constants import", "is experiencing high await times.\" % (self.node, self.name)) elif ma_sma", "= self.STATUS_NORMAL if self.congestion_status is self.STATUS_CONGESTED: if ma_med < self.congestion_await_sustained:", "= 2 # Device status STATUS_NORMAL = \"N\" STATUS_BUILDING =", "= self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT,", "DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self): # Bail if threshold", "= \"iops\" DATA_AWAIT = \"await\" def __init__(self, device_node, data_elements, size_sma,", "self.timestamp = ts # LOG.debug(\"%s: e = %s, v= %f\"", "self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING if self.congestion_status is self.STATUS_BUILDING: if ma_lar", "# LOG.debug(\"%s: e = %s, v= %f\" % (self.node, element,", "size_lar): self.node = device_node if os.path.exists('/sys/block/' + self.node + '/dm/name'):", "self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node %s (%s) is experiencing high await", "None self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike = -1 self.congestion_await_sustained = -1", "= {} self.data_caps = {self.DATA_AWAIT: -1, self.DATA_IOPS: -1} self.timestamp =", "# import logging import os from io_monitor.constants import DOMAIN from", "congestion status based on await moving average if self.congestion_status is", "self.congestion_status is self.STATUS_CONGESTED: if ma_med < self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING", "the congestion status based on await moving average if self.congestion_status", "self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f %6.2f %6.2f ] %d\" % (self.node,", "LOG.warn(\"Node %s (%s) is experiencing high await times.\" % (self.node,", "debug=False): if debug: ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT,", "in self.data_caps: self.data_caps[element] = cap def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike", "= \"L\" # Data tracked DATA_IOPS = \"iops\" DATA_AWAIT =", "# Bail if threshold is not set if self.congestion_await_sustained ==", "= %s\" % element) return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self,", "await_minimal_spike self.congestion_await_sustained = await_sustained_congestion def get_element_windows_avg_list(self, element): return [self.get_average(element, self.MA_WINDOW_SMA),", "1 MA_WINDOW_LAR = 2 # Device status STATUS_NORMAL = \"N\"", "if threshold is not set if self.congestion_await_sustained == -1: return", "self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element, window): if window not in [self.MA_WINDOW_SMA,", "element requested = %s\" % element) return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest()", "update_data(self, ts, element, value): self.timestamp = ts # LOG.debug(\"%s: e", "Data tracked DATA_IOPS = \"iops\" DATA_AWAIT = \"await\" def __init__(self,", "ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f %6.2f %6.2f ]", "Moving average windows MA_WINDOW_SMA = 0 MA_WINDOW_MED = 1 MA_WINDOW_LAR", "self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self, element): if element not in self.data_dict:", "self.data_caps[element]) def get_latest(self, element): if element not in self.data_dict: LOG.error(\"Error:", "# Moving average windows MA_WINDOW_SMA = 0 MA_WINDOW_MED = 1", "element): return \"%s [ %9.2f, %9.2f, %9.2f ]\" % (", "for w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self,", "= %s\" % element) return 0 return self.data_dict[element][window].get_average() def is_data_stale(self,", "%s\" % element) return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element,", "self.DATA_IOPS: -1} self.timestamp = None self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike =", "%s, v= %f\" % (self.node, element, value)) for w in", "(self.node, ma_sma, ma_med, ma_lar, self.congestion_await_sustained)) return self.congestion_status def set_data_caps(self, element,", "element) return 0 return self.data_dict[element][window].get_average() def is_data_stale(self, ts): return not", "value)) for w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def", "element in data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar,", "tracked DATA_IOPS = \"iops\" DATA_AWAIT = \"await\" def __init__(self, device_node,", "not set if self.congestion_await_sustained == -1: return ma_sma = self.get_average(self.DATA_AWAIT,", "LOG = logging.getLogger(DOMAIN) class DeviceDataCollector(object): # Moving average windows MA_WINDOW_SMA", "STATUS_BUILDING = \"B\" STATUS_CONGESTED = \"L\" # Data tracked DATA_IOPS", "element, window): if window not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError:", "average if self.congestion_status is self.STATUS_NORMAL: if ma_sma > self.congestion_await_sustained: self.congestion_status", "get_element_windows_avg_list(self, element): return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def", "ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [", "from io_monitor.constants import DOMAIN from io_monitor.utils.data_window import DataCollectionWindow LOG =", "self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element): return \"%s [ %9.2f, %9.2f, %9.2f", "element) return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element, window): if", "return self.data_dict[element][window].get_average() def is_data_stale(self, ts): return not (ts == self.timestamp)", "Set the congestion status based on await moving average if", "= open('/sys/block/' + self.node + '/dm/name', 'r').read().rstrip() else: self.name =", "data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def", "in self.data_dict: LOG.error(\"Error: invalid element requested = %s\" % element)", "= \"await\" def __init__(self, device_node, data_elements, size_sma, size_med, size_lar): self.node", "self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING def update_data(self, ts, element, value): self.timestamp", "import DataCollectionWindow LOG = logging.getLogger(DOMAIN) class DeviceDataCollector(object): # Moving average", "element, value): self.timestamp = ts # LOG.debug(\"%s: e = %s,", "self.congestion_status = self.STATUS_BUILDING def update_data(self, ts, element, value): self.timestamp =", "from io_monitor.utils.data_window import DataCollectionWindow LOG = logging.getLogger(DOMAIN) class DeviceDataCollector(object): #", "threshold is not set if self.congestion_await_sustained == -1: return ma_sma", "= self.STATUS_BUILDING if self.congestion_status is self.STATUS_BUILDING: if ma_lar > self.congestion_await_sustained:", "ma_sma, ma_med, ma_lar, self.congestion_await_sustained)) return self.congestion_status def set_data_caps(self, element, cap):", "class DeviceDataCollector(object): # Moving average windows MA_WINDOW_SMA = 0 MA_WINDOW_MED", "import logging import os from io_monitor.constants import DOMAIN from io_monitor.utils.data_window", "%9.2f, %9.2f ]\" % ( element, self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED),", "LOG.debug(\"%s [ %6.2f %6.2f %6.2f ] %d\" % (self.node, ma_sma,", "'r').read().rstrip() else: self.name = self.node self.data_dict = {} self.data_caps =", "LOG.debug(\"%s: e = %s, v= %f\" % (self.node, element, value))", "value): self.timestamp = ts # LOG.debug(\"%s: e = %s, v=", "return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element, window): if window", "set if self.congestion_await_sustained == -1: return ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA)", "io_monitor.constants import DOMAIN from io_monitor.utils.data_window import DataCollectionWindow LOG = logging.getLogger(DOMAIN)", "[ %6.2f %6.2f %6.2f ] %d\" % (self.node, ma_sma, ma_med,", "return 0 if element not in self.data_dict: LOG.error(\"Error: invalid element", "if element in self.data_caps: self.data_caps[element] = cap def set_congestion_thresholds(self, await_minimal_spike,", "2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 #", "\"iops\" DATA_AWAIT = \"await\" def __init__(self, device_node, data_elements, size_sma, size_med,", "# Copyright (c) 2016 Wind River Systems, Inc. # #", "%9.2f, %9.2f, %9.2f ]\" % ( element, self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element,", "ma_lar > self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node %s (%s) is", "= self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f %6.2f %6.2f ] %d\"", "in data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]})", "self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f %6.2f %6.2f", "# SPDX-License-Identifier: Apache-2.0 # import logging import os from io_monitor.constants", "get_latest(self, element): if element not in self.data_dict: LOG.error(\"Error: invalid element", "vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2016 Wind", "= self.STATUS_CONGESTED LOG.warn(\"Node %s (%s) is experiencing high await times.\"", "self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL if self.congestion_status is self.STATUS_CONGESTED: if ma_med", "set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained = await_sustained_congestion def", "(self.node, self.name)) elif ma_sma < self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL if", "tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2016 Wind River", "size_sma, size_med, size_lar): self.node = device_node if os.path.exists('/sys/block/' + self.node", "os.path.exists('/sys/block/' + self.node + '/dm/name'): self.name = open('/sys/block/' + self.node", "self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window requested = %s\" % window)", "invalid element requested = %s\" % element) return 0 return", "not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window requested =", "requested = %s\" % element) return 0 return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def", "def get_average(self, element, window): if window not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED,", "DOMAIN from io_monitor.utils.data_window import DataCollectionWindow LOG = logging.getLogger(DOMAIN) class DeviceDataCollector(object):", "# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2016", "% (self.node, element, value)) for w in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]:", "'/dm/name', 'r').read().rstrip() else: self.name = self.node self.data_dict = {} self.data_caps", "self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element): return \"%s [", "return \"%s [ %9.2f, %9.2f, %9.2f ]\" % ( element,", "self.node + '/dm/name', 'r').read().rstrip() else: self.name = self.node self.data_dict =", "logging.getLogger(DOMAIN) class DeviceDataCollector(object): # Moving average windows MA_WINDOW_SMA = 0", "self.data_dict = {} self.data_caps = {self.DATA_AWAIT: -1, self.DATA_IOPS: -1} self.timestamp", "if self.congestion_await_sustained == -1: return ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med", "ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set", "def update_data(self, ts, element, value): self.timestamp = ts # LOG.debug(\"%s:", "] %d\" % (self.node, ma_sma, ma_med, ma_lar, self.congestion_await_sustained)) return self.congestion_status", "-1, self.DATA_IOPS: -1} self.timestamp = None self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike", "== -1: return ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT,", "DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self): # Bail", "+ self.node + '/dm/name', 'r').read().rstrip() else: self.name = self.node self.data_dict", "\"%s [ %9.2f, %9.2f, %9.2f ]\" % ( element, self.get_average(element,", "[self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element): return", "return self.congestion_status def set_data_caps(self, element, cap): if element in self.data_caps:", "if window not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window", "self.timestamp) def get_congestion_status(self, debug=False): if debug: ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA)", "self.congestion_await_sustained = -1 for element in data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma,", "get_congestion_status(self, debug=False): if debug: ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med =", "[self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window requested = %s\" %", "self.congestion_await_sustained == -1: return ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med =", "(c) 2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0", "in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: LOG.error(\"WindowError: invalid window requested = %s\"", "ma_med, ma_lar, self.congestion_await_sustained)) return self.congestion_status def set_data_caps(self, element, cap): if", "for element in data_elements: self.data_dict.update({element: [ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True),", "Copyright (c) 2016 Wind River Systems, Inc. # # SPDX-License-Identifier:", "0 if element not in self.data_dict: LOG.error(\"Error: invalid element requested", "< self.congestion_await_sustained: self.congestion_status = self.STATUS_NORMAL if self.congestion_status is self.STATUS_CONGESTED: if", "self.data_caps: self.data_caps[element] = cap def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike =", "if debug: ma_sma = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED)", "await times.\" % (self.node, self.name)) elif ma_sma < self.congestion_await_sustained: self.congestion_status", "> self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING if self.congestion_status is self.STATUS_BUILDING: if", "ts): return not (ts == self.timestamp) def get_congestion_status(self, debug=False): if", "ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set the congestion status based", "\"await\" def __init__(self, device_node, data_elements, size_sma, size_med, size_lar): self.node =", "== self.timestamp) def get_congestion_status(self, debug=False): if debug: ma_sma = self.get_average(self.DATA_AWAIT,", "return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED), self.get_average(element, self.MA_WINDOW_LAR)] def get_element_windows_avg_string(self, element):", "%s\" % element) return 0 return self.data_dict[element][window].get_average() def is_data_stale(self, ts):", "self.congestion_status def set_data_caps(self, element, cap): if element in self.data_caps: self.data_caps[element]", "self.data_dict[element][window].get_average() def is_data_stale(self, ts): return not (ts == self.timestamp) def", "> self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node %s (%s) is experiencing", "+ '/dm/name'): self.name = open('/sys/block/' + self.node + '/dm/name', 'r').read().rstrip()", "shiftwidth=4 softtabstop=4 # # Copyright (c) 2016 Wind River Systems,", "open('/sys/block/' + self.node + '/dm/name', 'r').read().rstrip() else: self.name = self.node", "self.data_dict: LOG.error(\"Error: invalid element requested = %s\" % element) return", "element, cap): if element in self.data_caps: self.data_caps[element] = cap def", "DataCollectionWindow LOG = logging.getLogger(DOMAIN) class DeviceDataCollector(object): # Moving average windows", "set_data_caps(self, element, cap): if element in self.data_caps: self.data_caps[element] = cap", "= self.STATUS_BUILDING def update_data(self, ts, element, value): self.timestamp = ts", "return self.data_dict[element][self.MA_WINDOW_SMA].get_latest() def get_average(self, element, window): if window not in", "cap def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained =", "get_average(self, element, window): if window not in [self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]:", "stuck_data_override=True)]}) def update_congestion_status(self): # Bail if threshold is not set", "invalid window requested = %s\" % window) return 0 if", "= await_sustained_congestion def get_element_windows_avg_list(self, element): return [self.get_average(element, self.MA_WINDOW_SMA), self.get_average(element, self.MA_WINDOW_MED),", "if self.congestion_status is self.STATUS_BUILDING: if ma_lar > self.congestion_await_sustained: self.congestion_status =", "= self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f", "= -1 self.congestion_await_sustained = -1 for element in data_elements: self.data_dict.update({element:", "self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self, element): if element not", "is self.STATUS_BUILDING: if ma_lar > self.congestion_await_sustained: self.congestion_status = self.STATUS_CONGESTED LOG.warn(\"Node", "self.timestamp = None self.congestion_status = self.STATUS_NORMAL self.congestion_await_minimal_spike = -1 self.congestion_await_sustained", "get_element_windows_avg_string(self, element): return \"%s [ %9.2f, %9.2f, %9.2f ]\" %", "times.\" % (self.node, self.name)) elif ma_sma < self.congestion_await_sustained: self.congestion_status =", "self.node = device_node if os.path.exists('/sys/block/' + self.node + '/dm/name'): self.name", "def get_element_windows_avg_string(self, element): return \"%s [ %9.2f, %9.2f, %9.2f ]\"", "[ DataCollectionWindow(size_sma, stuck_data_override=True), DataCollectionWindow(size_med, stuck_data_override=True), DataCollectionWindow(size_lar, stuck_data_override=True)]}) def update_congestion_status(self): #", "= self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) # Set the congestion status based on", "%s\" % window) return 0 if element not in self.data_dict:", "self.get_average(self.DATA_AWAIT, self.MA_WINDOW_SMA) ma_med = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR)", "[self.MA_WINDOW_SMA, self.MA_WINDOW_MED, self.MA_WINDOW_LAR]: self.data_dict[element][w].update(value, self.data_caps[element]) def get_latest(self, element): if element", "os from io_monitor.constants import DOMAIN from io_monitor.utils.data_window import DataCollectionWindow LOG", "if self.congestion_status is self.STATUS_CONGESTED: if ma_med < self.congestion_await_sustained: self.congestion_status =", "self.get_average(self.DATA_AWAIT, self.MA_WINDOW_MED) ma_lar = self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f %6.2f", "window requested = %s\" % window) return 0 if element", "await moving average if self.congestion_status is self.STATUS_NORMAL: if ma_sma >", "else: self.name = self.node self.data_dict = {} self.data_caps = {self.DATA_AWAIT:", "+ '/dm/name', 'r').read().rstrip() else: self.name = self.node self.data_dict = {}", "% element) return 0 return self.data_dict[element][window].get_average() def is_data_stale(self, ts): return", "def is_data_stale(self, ts): return not (ts == self.timestamp) def get_congestion_status(self,", "DeviceDataCollector(object): # Moving average windows MA_WINDOW_SMA = 0 MA_WINDOW_MED =", "MA_WINDOW_LAR = 2 # Device status STATUS_NORMAL = \"N\" STATUS_BUILDING", "return not (ts == self.timestamp) def get_congestion_status(self, debug=False): if debug:", "DATA_AWAIT = \"await\" def __init__(self, device_node, data_elements, size_sma, size_med, size_lar):", "ma_sma > self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING if self.congestion_status is self.STATUS_BUILDING:", "= \"N\" STATUS_BUILDING = \"B\" STATUS_CONGESTED = \"L\" # Data", "not in self.data_dict: LOG.error(\"Error: invalid element requested = %s\" %", "self.STATUS_BUILDING def update_data(self, ts, element, value): self.timestamp = ts #", "= %s, v= %f\" % (self.node, element, value)) for w", "MA_WINDOW_MED = 1 MA_WINDOW_LAR = 2 # Device status STATUS_NORMAL", "self.get_average(self.DATA_AWAIT, self.MA_WINDOW_LAR) LOG.debug(\"%s [ %6.2f %6.2f %6.2f ] %d\" %", "self.congestion_await_sustained)) return self.congestion_status def set_data_caps(self, element, cap): if element in", "self.name = self.node self.data_dict = {} self.data_caps = {self.DATA_AWAIT: -1,", "self.STATUS_NORMAL: if ma_sma > self.congestion_await_sustained: self.congestion_status = self.STATUS_BUILDING if self.congestion_status", "0 MA_WINDOW_MED = 1 MA_WINDOW_LAR = 2 # Device status", "high await times.\" % (self.node, self.name)) elif ma_sma < self.congestion_await_sustained:", "self.node self.data_dict = {} self.data_caps = {self.DATA_AWAIT: -1, self.DATA_IOPS: -1}", "__init__(self, device_node, data_elements, size_sma, size_med, size_lar): self.node = device_node if", "average windows MA_WINDOW_SMA = 0 MA_WINDOW_MED = 1 MA_WINDOW_LAR =", "io_monitor.utils.data_window import DataCollectionWindow LOG = logging.getLogger(DOMAIN) class DeviceDataCollector(object): # Moving", "= cap def set_congestion_thresholds(self, await_minimal_spike, await_sustained_congestion): self.congestion_await_minimal_spike = await_minimal_spike self.congestion_await_sustained", "element not in self.data_dict: LOG.error(\"Error: invalid element requested = %s\"" ]
[ "default=False, metadata={ \"help\": \"Whether to force the addition of a", "\"pbt_transformers\", \"reinit\": True, \"allow_val_change\": True } } logger.info(config) scheduler =", "# Run eval after every epoch. # eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"])", "supported, but you can do it from another script, save", "2.0 (the \"License\"); # you may not use this file", "train_data_file: Optional[str] = field( default=None, metadata={\"help\": \"The input training data", "def evaluate(self, eval_dataset= None): eval_dataloader = self.get_eval_dataloader(eval_dataset) output = self.prediction_loop(", "checkpoint_dir: self.args.output_dir = checkpoint_dir # This is the directory name", "script. # We now keep distinct sets of args, for", "set_seed, ) import ray from ray import tune from transformers.file_utils", "}, ) model_type: Optional[str] = field( default=None, metadata={\"help\": \"If training", "may result in errors in the encoding step. Set the", "\"train_bs/gpu\", \"num_epochs\": \"num_epochs\" }, metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\" ])", "\"An optional input evaluation data file to evaluate the perplexity", "= ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path)", "return model_name # Get subdirectory used for Huggingface. subdirs =", "in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, ) else: logger.info(\"Training new model from", "args, for a cleaner separation of concerns. # parser =", "AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in", "= field( default=None, metadata={\"help\": \"The input training data file (a", "\"Optional input sequence length after tokenization.\" \"The training dataset will", "CLIReporter # if is_wandb_available(): # import wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True)", "= [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters = [ { \"params\": [p for", "block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, )", "num_labels=num_labels, # finetuning_task=task_name, # ) # model = AutoModelForSequenceClassification.from_pretrained( #", "\"num_epochs\": \"num_epochs\" }, metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\" ]) analysis", "import is_torch_tpu_available from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import PopulationBasedTraining", "of de-biasing head to be used\"} ) @dataclass class DataTrainingArguments:", "DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool = False, cache_dir: Optional[str] =", "import dataclass, field from typing import Optional import torch from", "s3\"} ) force_pad_token: bool = field( default=False, metadata={ \"help\": \"Whether", "model/config/tokenizer we are going to fine-tune, or train from scratch.", "an evaluation data file. Either supply a file to --eval_data_file", "[-1, 0] else logging.WARN, ) logger.warning( \"Process rank: %s, device:", "list: \" + \", \".join(MODEL_TYPES)}, ) config_name: Optional[str] = field(", "tokenizer has no padding token. This may result in errors", "plm_probability: float = field( default=1 / 6, metadata={ \"help\": \"Ratio", "length for permutation language modeling.\" }, ) max_span_length: int =", "models for language modeling on a text file (GPT, GPT-2,", "from another script, save it,\" \"and load it from here,", "int = field( default=-1, metadata={ \"help\": \"Optional input sequence length", "self.model.named_parameters() if any(nd in n for nd in no_decay)], \"weight_decay\":", "): file_path = args.eval_data_file if evaluate else args.train_data_file if args.line_by_line:", "can do it from another script, save it,\" \"and load", "the dataset are to be handled as distinct sequences.\"}, )", "License for the specific language governing permissions and # limitations", "%(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if training_args.local_rank in [-1, 0] else", "import ray from ray import tune from transformers.file_utils import is_torch_tpu_available", "} logger.info(config) scheduler = PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={", "Trainer, TrainingArguments, set_seed, ) import ray from ray import tune", "self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def", "exists and is not empty. Use --overwrite_output_dir to overcome.\" )", "run using the\" \"--mlm flag (masked language modeling).\" ) if", "and do checkpointing in evaluate instead # save_steps=0, # num_train_epochs=config[\"num_epochs\"],", "modeling (PLM) loss. \"\"\" import logging import math import os", "checkpointing in evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0,", "'eos_token': '<eos>', 'pad_token': '<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type", "instance from scratch.\") if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif", "%s\", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info(\"Training/evaluation", "= get_datasets(config) # # training_args = TrainingArguments( # output_dir=tune.get_trial_dir(), #", "config=config_in, cache_dir=model_args.cache_dir, ) else: logger.info(\"Training new model from scratch\") model", "a model type from the list: \" + \", \".join(MODEL_TYPES)},", "tokens to mask for masked language modeling loss\"} ) plm_probability:", "= DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else: data_collator = DataCollatorForLanguageModeling(", "= DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args = TrainingArguments( output_dir=tune.get_trial_dir(),", "1 subdir. assert len(subdirs) == 1, subdirs return subdirs[0] #", "model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in [\"bert\", \"roberta\", \"distilbert\", \"camembert\"] and not", "self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return self.current_optimizer, self.current_scheduler def evaluate(self, eval_dataset=", "-1, # We use num_epochs instead. \"wandb\": { \"project\": \"pbt_transformers\",", "# # training_args = TrainingArguments( # output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], #", "# We explicitly set save to 0, and do checkpointing", "learning_rate=config[\"learning_rate\"], # do_train=True, # do_eval=True, # evaluate_during_training=True, # # Run", "= { # These 3 configs below were defined earlier", "evaluate_during_training=True, # Run eval after every epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"])", "tokens for permutation language modeling.\"} ) block_size: int = field(", "\"\"\" train_data_file: Optional[str] = field( default=None, metadata={\"help\": \"The input training", "The .from_pretrained methods guarantee that only one local process can", "has no padding token. This may result in errors in", ") max_span_length: int = field( default=5, metadata={\"help\": \"Maximum length of", "if training_args.do_train: model_path = ( model_args.model_name_or_path if model_args.model_name_or_path is not", "}, config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\", name=\"tune_trans\") best_config", "in [\"bert\", \"roberta\", \"distilbert\", \"camembert\"] and not data_args.mlm: raise ValueError(", "from scratch. \"\"\" model_name_or_path: Optional[str] = field( default=None, metadata={ \"help\":", "file).\"} ) eval_data_file: Optional[str] = field( default=None, metadata={\"help\": \"An optional", "tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None): # See all possible arguments in", "These 3 configs below were defined earlier \"model_name\": model_args.model_name_or_path, \"task_name\":", "# ) # # # Use our modified TuneTransformerTrainer #", "field( default=-1, metadata={ \"help\": \"Optional input sequence length after tokenization.\"", "# do_train=True, # do_eval=True, # evaluate_during_training=True, # # Run eval", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) else None", "not the same as model_name\"} ) cache_dir: Optional[str] = field(", "AI Language Team Authors and The HuggingFace Inc. team. #", "modified TuneTransformerTrainer # tune_trainer = TuneTransformerTrainer( # model=model, # args=training_args,", "# # model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # # num_labels =", "to in writing, software # distributed under the License is", "guarantee that only one local process can concurrently # download", "for nd in no_decay)], \"weight_decay\": 0.0, }, ] self.optimizer =", "logging_dir=\"./logs\") # Initialize our Trainer tune_trainer = TuneTransformerTrainer( model=model, args=training_args,", "or agreed to in writing, software # distributed under the", "args=training_args, # train_dataset=train_dataset, # eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), # ) #", "pretrained model and tokenizer # # Distributed training: # The", "that only one local process can concurrently # download model", "permutation language modeling.\" }, ) max_span_length: int = field( default=5,", "None ) if config_in.model_type == \"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer,", "os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] # There should only be 1 subdir.", "is the directory name that Huggingface requires. output_dir = os.path.join(", "max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize our Trainer", "the addition of a padding token to tokenizer that does", "compliance with the License. # You may obtain a copy", "bool = field( default=False, metadata={\"help\": \"Train with masked-language modeling loss", "compute_metrics=utils.build_compute_metrics_fn(task_name), # ) # tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None): # See", "self.current_scheduler = self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir,", "de-biasing head to be used\"} ) @dataclass class DataTrainingArguments: \"\"\"", "any(nd in n for nd in no_decay)], \"weight_decay\": self.args.weight_decay, },", "\"Train with masked-language modeling loss instead of language modeling.\"} )", "if you want to train a model from scratch.\" },", "evaluation data file. Either supply a file to --eval_data_file \"", "AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, ) else: logger.info(\"Training", "+ # 1, # # We explicitly set save to", "not use this file except in compliance with the License.", "for permutation language modeling.\" }, ) max_span_length: int = field(", "as model_name\"} ) tokenizer_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained", "= field( default=None, metadata={ \"help\": \"The model checkpoint for weights", "masked language modeling loss\"} ) plm_probability: float = field( default=1", "have LM heads but masked LM heads. They must be", "our Trainer tune_trainer = TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset,", "you may not use this file except in compliance with", "file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps:", "\"BERT and RoBERTa-like models do not have LM heads but", "evaluate the perplexity on (a text file).\"}, ) line_by_line: bool", "field( default=False, metadata={\"help\": \"Overwrite the cached training and evaluation sets\"}", "load it from here, using --tokenizer_name\" ) if tokenizer.pad_token_id is", "p in self.model.named_parameters() if any(nd in n for nd in", "scheduler = PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda:", "= field( default=None, metadata={\"help\": \"The type of de-biasing head to", "attention mask is used to ignore this token # when", "Run eval after every epoch. # eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) +", "without an evaluation data file. Either supply a file to", "and not data_args.mlm: raise ValueError( \"BERT and RoBERTa-like models do", "\"LayerNorm.weight\"] optimizer_grouped_parameters = [ { \"params\": [p for n, p", "dataset will be truncated in block of this size for", "get_linear_schedule_with_warmup from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "what data we are going to input our model for", "os.path.isdir(model_args.model_name_or_path) else None ) tune_trainer.train(model_path=model_path) if __name__ == \"__main__\": parser", "HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # model_args, data_args, training_args = parser.parse_args_into_dataclasses() if", "torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None): if", "this script. # We now keep distinct sets of args,", "training_args = TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True, # Run", "get_datasets(config) # # training_args = TrainingArguments( # output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"],", "using --tokenizer_name\" ) if tokenizer.pad_token_id is None: if model_args.force_pad_token: #", "step. Set the --force_pad_token flag to fix this.\" ) model_name_or_path", "Use our modified TuneTransformerTrainer # tune_trainer = TuneTransformerTrainer( # model=model,", ") if training_args.do_train: model_path = ( model_args.model_name_or_path if model_args.model_name_or_path is", "from s3\"} ) force_pad_token: bool = field( default=False, metadata={ \"help\":", "modeling.\"} ) block_size: int = field( default=-1, metadata={ \"help\": \"Optional", "num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\", name=\"tune_trans\") best_config = analysis.get_best_config(metric=\"eval_loss\",", "transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import PopulationBasedTraining from ray.tune import", "cache_dir=model_args.cache_dir) else: config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating a new", ") import ray from ray import tune from transformers.file_utils import", "math import os from dataclasses import dataclass, field from typing", "evaluate_during_training=True, # # Run eval after every epoch. # eval_steps=(len(train_dataset)", "Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # #", "train_dataset=train_dataset, # eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), # ) # tune_trainer.train(model_name_or_path) def", "%(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if training_args.local_rank in [-1,", "the\" \"--mlm flag (masked language modeling).\" ) if data_args.block_size <=", "# model = AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, # config=config, # )", "AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, # config=config, # ) # # #", "None, ): file_path = args.eval_data_file if evaluate else args.train_data_file if", "possible arguments in src/transformers/training_args.py # or by passing the --help", "for weights initialization. Leave None if you want to train", "\"\"\" import logging import math import os from dataclasses import", "debiasing_head: Optional[str] = field( default=None, metadata={\"help\": \"The type of de-biasing", "option to force the addition of a pad token. The", "n for nd in no_decay)], \"weight_decay\": 0.0, }, ] self.optimizer", "f\"Output directory ({training_args.output_dir}) already exists and is not empty. Use", "Optional[str] = field( default=None, metadata={\"help\": \"If training from scratch, pass", "else logging.WARN, ) logger.warning( \"Process rank: %s, device: %s, n_gpu:", "the pretrained models downloaded from s3\"} ) force_pad_token: bool =", "size will be the max possible for the model else:", "data file. Either supply a file to --eval_data_file \" \"or", "Some tokenizers don't had pad tokens which causes errors at", "\"per_gpu_train_batch_size\": tune.choice([16, 32, 64]), \"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0, 0.3),", "tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None ) # print('train_dataset {}'.format(train_dataset.examples[0]))", ") cache_dir: Optional[str] = field( default=None, metadata={\"help\": \"Where do you", "this size for training.\" \"Default to the model max input", "\"Whether distinct lines of text in the dataset are to", "= recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\"", "# ) # tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None): # See all", "def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool = False,", "epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + 1, # We explicitly set", "Set the --force_pad_token flag to fix this.\" ) model_name_or_path =", "default=None, metadata={\"help\": \"An optional input evaluation data file to evaluate", "os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir is None or", "\"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\" }, metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\"", "default=-1, metadata={ \"help\": \"Optional input sequence length after tokenization.\" \"The", "PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import PopulationBasedTraining from ray.tune import CLIReporter #", ") block_size: int = field( default=-1, metadata={ \"help\": \"Optional input", "default=None, metadata={\"help\": \"If training from scratch, pass a model type", "class ModelArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are", "bool(training_args.local_rank != -1), training_args.fp16, ) logger.info(\"Training/evaluation parameters %s\", training_args) #", "data_args.block_size <= 0: data_args.block_size = tokenizer.max_len # Our input block", "len(tune_checkpoint_dir) == 0: return model_name # Get subdirectory used for", "not training_args.overwrite_output_dir ): raise ValueError( f\"Output directory ({training_args.output_dir}) already exists", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "supply a file to --eval_data_file \" \"or remove the --do_eval", "in n for nd in no_decay)], \"weight_decay\": self.args.weight_decay, }, {", "used to ignore this token # when feeding to the", "from ray.tune.schedulers import PopulationBasedTraining from ray.tune import CLIReporter # if", "bool = field( default=False, metadata={\"help\": \"Overwrite the cached training and", "are going to input our model for training and eval.", "from the list: \" + \", \".join(MODEL_TYPES)}, ) config_name: Optional[str]", "if tune_checkpoint_dir is None or len(tune_checkpoint_dir) == 0: return model_name", "DataTrainingArguments: \"\"\" Arguments pertaining to what data we are going", "logger.warning( \"Process rank: %s, device: %s, n_gpu: %s, distributed training:", "encoding step in the collate_fn. # We give here the", "already exists and is not empty. Use --overwrite_output_dir to overcome.\"", ") if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not", "default=None, metadata={\"help\": \"Where do you want to store the pretrained", "if self.optimizer is None: no_decay = [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters =", "file except in compliance with the License. # You may", "at the encoding step in the collate_fn. # We give", "you want to store the pretrained models downloaded from s3\"}", "\"The input training data file (a text file).\"} ) eval_data_file:", "default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not the", "\"and load it from here, using --tokenizer_name\" ) if tokenizer.pad_token_id", "config = { # These 3 configs below were defined", "# num_labels = glue_tasks_num_labels[config[\"task_name\"]] # # config = AutoConfig.from_pretrained( #", "& vocab. if model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path:", "%s\", training_args) # Set seed set_seed(training_args.seed) # Load pretrained model", "block of this size for training.\" \"Default to the model", "concerns. # parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # model_args, data_args,", "Get datasets train_dataset = ( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train", "file).\"}, ) line_by_line: bool = field( default=False, metadata={\"help\": \"Whether distinct", "ray from ray import tune from transformers.file_utils import is_torch_tpu_available from", "# # Use our modified TuneTransformerTrainer # tune_trainer = TuneTransformerTrainer(", "metadata={\"help\": \"An optional input evaluation data file to evaluate the", "mask for masked language modeling loss\"} ) plm_probability: float =", ") return self.current_optimizer, self.current_scheduler def evaluate(self, eval_dataset= None): eval_dataloader =", "modeling.\" }, ) max_span_length: int = field( default=5, metadata={\"help\": \"Maximum", "per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize our Trainer tune_trainer", "file_path=file_path, block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset(", "os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] # There should only be", "1, \"gpu\": 1 }, config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter,", "and eval. \"\"\" train_data_file: Optional[str] = field( default=None, metadata={\"help\": \"The", "if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] # There should only be 1", "a new config instance from scratch.\") if model_args.tokenizer_name: tokenizer =", "import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser,", "# model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # # num_labels = glue_tasks_num_labels[config[\"task_name\"]]", "for single sentence inputs (take into account special tokens).\" },", "dataset are to be handled as distinct sequences.\"}, ) mlm:", "library models for language modeling on a text file (GPT,", "tune.report(**output.metrics) return output.metrics def save_state(self): with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir", "we are going to input our model for training and", "# when feeding to the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning(", "evaluation data file to evaluate the perplexity on (a text", "KIND, either express or implied. # See the License for", "language modeling.\"} ) block_size: int = field( default=-1, metadata={ \"help\":", "it from here, using --tokenizer_name\" ) if tokenizer.pad_token_id is None:", "ModelArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are going", "= [ { \"params\": [p for n, p in self.model.named_parameters()", "to be used\"} ) @dataclass class DataTrainingArguments: \"\"\" Arguments pertaining", "CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels,", "training and eval. \"\"\" train_data_file: Optional[str] = field( default=None, metadata={\"help\":", "import tune from transformers.file_utils import is_torch_tpu_available from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR", "metadata={\"help\": \"Train with masked-language modeling loss instead of language modeling.\"}", "after tokenization.\" \"The training dataset will be truncated in block", "to tokenizer that does not already have one.\" }, )", "(the \"License\"); # you may not use this file except", "of tokens to mask for masked language modeling loss\"} )", "Set seed set_seed(training_args.seed) # Load pretrained model and tokenizer #", "\"The training dataset will be truncated in block of this", "\"Where do you want to store the pretrained models downloaded", "per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize our Trainer tune_trainer =", "field( default=None, metadata={\"help\": \"Where do you want to store the", "using the\" \"--mlm flag (masked language modeling).\" ) if data_args.block_size", "separation of concerns. # parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) #", "1 }, config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\", name=\"tune_trans\")", "train_transformer, resources_per_trial={ \"cpu\": 1, \"gpu\": 1 }, config=config, num_samples=3, scheduler=scheduler,", "Initialize our Trainer tune_trainer = TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset,", "pad tokens which causes errors at the encoding step in", "checkpoint_dir=None): # train_dataset, eval_dataset = get_datasets(config) # # training_args =", "tune from transformers.file_utils import is_torch_tpu_available from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from", "surrounding context length for permutation language modeling.\" }, ) max_span_length:", "32, 64]), \"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2,", "# # Unless required by applicable law or agreed to", "get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None ) # print('train_dataset", "\", \".join(MODEL_TYPES)}, ) config_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained", "import wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES =", ") force_pad_token: bool = field( default=False, metadata={ \"help\": \"Whether to", "p in self.model.named_parameters() if not any(nd in n for nd", "// config[\"per_gpu_train_batch_size\"]) + 1, # We explicitly set save to", "= [ os.path.join(tune_checkpoint_dir, name) for name in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir,", "'<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in [\"bert\", \"roberta\",", "of a span of masked tokens for permutation language modeling.\"}", "finetuning_task=task_name, # ) # model = AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, #", "do_train=True, do_eval=True, evaluate_during_training=True, # Run eval after every epoch. eval_steps=(len(train_dataset)", "# ) # model = AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, # config=config,", "data we are going to input our model for training", "metadata={ \"help\": \"Optional input sequence length after tokenization.\" \"The training", "training data file (a text file).\"} ) eval_data_file: Optional[str] =", "return output.metrics def save_state(self): with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir =", "implied. # See the License for the specific language governing", "elif model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in = CONFIG_MAPPING[model_args.model_type]()", "modeling (CLM) loss. BERT and RoBERTa are fine-tuned using a", "ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES", "to surrounding context length for permutation language modeling.\" }, )", "else args.train_data_file if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) # return", "# do_eval=True, # evaluate_during_training=True, # # Run eval after every", "See all possible arguments in src/transformers/training_args.py # or by passing", "Copyright 2018 The Google AI Language Team Authors and The", "padding token. This may result in errors in the encoding", "[\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters = [ { \"params\": [p for n,", "\"<pad>\"}) else: logger.warning( \"Attempting to train a model whose tokenizer", "the encoding step. Set the --force_pad_token flag to fix this.\"", "= field( default=False, metadata={\"help\": \"Train with masked-language modeling loss instead", "input sequence length after tokenization.\" \"The training dataset will be", "if not any(nd in n for nd in no_decay)], \"weight_decay\":", "single sentence inputs (take into account special tokens).\" }, )", "(MLM) loss. XLNet is fine-tuned using a permutation language modeling", "cache_dir=model_args.cache_dir) if training_args.do_eval else None ) if config_in.model_type == \"xlnet\":", "# download model & vocab. if model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name,", "# or by passing the --help flag to this script.", "- %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if training_args.local_rank in", "}) reporter = CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\":", "else: logger.warning( \"Attempting to train a model whose tokenizer has", "from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, ) else: logger.info(\"Training new model", "of this size for training.\" \"Default to the model max", "it,\" \"and load it from here, using --tokenizer_name\" ) if", "max possible for the model else: data_args.block_size = min(data_args.block_size, tokenizer.max_len)", "Unless required by applicable law or agreed to in writing,", "of length of a span of masked tokens to surrounding", "transformers.file_utils import is_torch_tpu_available from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import", "logger.warning(\"You are instantiating a new config instance from scratch.\") if", "self.log(output.metrics) self.save_state() tune.report(**output.metrics) return output.metrics def save_state(self): with tune.checkpoint_dir(step=self.global_step) as", ") if config_in.model_type == \"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability,", "if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) else None )", "the specific language governing permissions and # limitations under the", "}, metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\" ]) analysis = tune.run(", "model else: data_args.block_size = min(data_args.block_size, tokenizer.max_len) # Get datasets train_dataset", "DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed,", "ray import tune from transformers.file_utils import is_torch_tpu_available from transformers.trainer_utils import", "# args=training_args, # train_dataset=train_dataset, # eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), # )", "type of de-biasing head to be used\"} ) @dataclass class", "= TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics,", ") model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained(", "metadata={\"help\": \"Overwrite the cached training and evaluation sets\"} ) def", "# Distributed training: # The .from_pretrained methods guarantee that only", "which model/config/tokenizer we are going to fine-tune, or train from", "in n for nd in no_decay)], \"weight_decay\": 0.0, }, ]", "self.lr_scheduler is None: self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps )", "AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating a", "instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") #", "CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\"", "the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning( \"Attempting to train a", "\"Pretrained tokenizer name or path if not the same as", "os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f\"Output", "if tokenizer.pad_token_id is None: if model_args.force_pad_token: # See PR 3388.", "default=None, metadata={\"help\": \"The type of de-biasing head to be used\"}", "LM heads but masked LM heads. They must be run", "config[\"model_name\"]) if model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path),", "CTRL, BERT, RoBERTa, XLNet). GPT, GPT-2 and CTRL are fine-tuned", "metadata={\"help\": \"The input training data file (a text file).\"} )", "tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32, 64],", "name that Huggingface requires. output_dir = os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir)", "RoBERTa-like models do not have LM heads but masked LM", "a model from scratch.\" }, ) model_type: Optional[str] = field(", "model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path,", "\"wandb\": { \"project\": \"pbt_transformers\", \"reinit\": True, \"allow_val_change\": True } }", "tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning( \"Attempting to train a model whose", "\"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\" ]) analysis = tune.run( train_transformer, resources_per_trial={", "See PR 3388. Some tokenizers don't had pad tokens which", "TextDataset, Trainer, TrainingArguments, set_seed, ) import ray from ray import", "logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf in", "fine-tuned using a permutation language modeling (PLM) loss. \"\"\" import", "lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32, 64], }) reporter =", "save to 0, and do checkpointing in evaluate instead save_steps=0,", "name) for name in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] #", "input evaluation data file to evaluate the perplexity on (a", "tokens).\" }, ) overwrite_cache: bool = field( default=False, metadata={\"help\": \"Overwrite", "import logging import math import os from dataclasses import dataclass,", "{ # These 3 configs below were defined earlier \"model_name\":", "0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32, 64], })", "a span of masked tokens for permutation language modeling.\"} )", "\"Ratio of tokens to mask for masked language modeling loss\"}", "# logging_dir=\"./logs\", # ) # # model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"])", "Fine-tuning the library models for language modeling on a text", "AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise ValueError( \"You are instantiating a new", "XLNet). GPT, GPT-2 and CTRL are fine-tuned using a causal", "train a model whose tokenizer has no padding token. This", "distributed training: %s, 16-bits training: %s\", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank", "create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer is None: no_decay = [\"bias\",", "if data_args.block_size <= 0: data_args.block_size = tokenizer.max_len # Our input", "max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, # weight_decay=config[\"weight_decay\"], #", "process can concurrently # download model & vocab. if model_args.config_name:", "= ( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None )", "keep distinct sets of args, for a cleaner separation of", "in the collate_fn. # We give here the option to", ") # tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None): # See all possible", "recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in", "LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return", "subdirs[0] # def train_transformer(config, checkpoint_dir=None): # train_dataset, eval_dataset = get_datasets(config)", "parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses()", "config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)", "checkpoint for weights initialization. Leave None if you want to", "only be 1 subdir. assert len(subdirs) == 1, subdirs return", "eps=self.args.adam_epsilon, ) if self.lr_scheduler is None: self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer,", "train_dataset, eval_dataset = get_datasets(config) # # training_args = TrainingArguments( #", "AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise", "on a text file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet).", "DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() config = {", "the same as model_name\"} ) tokenizer_name: Optional[str] = field( default=None,", "You may obtain a copy of the License at #", "metadata={\"help\": \"Whether distinct lines of text in the dataset are", "PopulationBasedTraining from ray.tune import CLIReporter # if is_wandb_available(): # import", "# num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0,", "not None and os.path.isdir(model_args.model_name_or_path) else None ) tune_trainer.train(model_path=model_path) if __name__", "is_torch_tpu_available from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import PopulationBasedTraining from", "special tokens).\" }, ) overwrite_cache: bool = field( default=False, metadata={\"help\":", "# print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset = ( get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir)", "to overcome.\" ) # Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s", "tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in [\"bert\", \"roberta\", \"distilbert\", \"camembert\"] and", "mlm_probability: float = field( default=0.15, metadata={\"help\": \"Ratio of tokens to", "do checkpointing in evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"],", "# output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], # do_train=True, # do_eval=True, # evaluate_during_training=True,", "NVIDIA CORPORATION. All rights reserved. # # Licensed under the", "metadata={\"help\": \"The type of de-biasing head to be used\"} )", "the directory name that Huggingface requires. output_dir = os.path.join( self.args.output_dir,", "TrainingArguments)) # model_args, data_args, training_args = parser.parse_args_into_dataclasses() if data_args.eval_data_file is", "# Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s -", "TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics, )", "= AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else:", "\"roberta\", \"distilbert\", \"camembert\"] and not data_args.mlm: raise ValueError( \"BERT and", "if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "XLNet is fine-tuned using a permutation language modeling (PLM) loss.", "CTRL are fine-tuned using a causal language modeling (CLM) loss.", "# train_dataset=train_dataset, # eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), # ) # tune_trainer.train(model_name_or_path)", "# tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None): # See all possible arguments", "the --do_eval argument.\" ) if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and", "it from another script, save it,\" \"and load it from", "tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)", "perplexity on (a text file).\"}, ) line_by_line: bool = field(", "tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise ValueError( \"You are instantiating", "keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\", name=\"tune_trans\") best_config = analysis.get_best_config(metric=\"eval_loss\", mode=\"min\") print(best_config)", "2018 The Google AI Language Team Authors and The HuggingFace", "\"\"\" Arguments pertaining to which model/config/tokenizer we are going to", "from here, using --tokenizer_name\" ) if tokenizer.pad_token_id is None: if", "and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError(", "DataTrainingArguments, TrainingArguments)) # model_args, data_args, training_args = parser.parse_args_into_dataclasses() if data_args.eval_data_file", "a masked language modeling (MLM) loss. XLNet is fine-tuned using", "%s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training:", "eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + 1, # We explicitly set save", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "{ \"params\": [p for n, p in self.model.named_parameters() if not", "after every epoch. # eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + # 1,", "There should only be 1 subdir. assert len(subdirs) == 1,", "We now keep distinct sets of args, for a cleaner", "We use num_epochs instead. \"wandb\": { \"project\": \"pbt_transformers\", \"reinit\": True,", "model_args, data_args, training_args = parser.parse_args_into_dataclasses() config = { # These", "optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if self.lr_scheduler is None:", "def recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir is None or len(tune_checkpoint_dir) ==", "[p for n, p in self.model.named_parameters() if not any(nd in", "model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir,", "from transformers.file_utils import is_torch_tpu_available from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers", "tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2, 3, 4, 5]),", "min(data_args.block_size, tokenizer.max_len) # Get datasets train_dataset = ( get_dataset(data_args, tokenizer=tokenizer,", "\".join(MODEL_TYPES)}, ) config_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained config", "from dataclasses import dataclass, field from typing import Optional import", "--do_eval argument.\" ) if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train", "to mask for masked language modeling loss\"} ) plm_probability: float", "in evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"],", ") debiasing_head: Optional[str] = field( default=None, metadata={\"help\": \"The type of", "eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics) return output.metrics def save_state(self): with", "64], }) reporter = CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\",", "parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # model_args, data_args, training_args =", "nd in no_decay)], \"weight_decay\": self.args.weight_decay, }, { \"params\": [p for", "save_steps=0, # num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], #", "= AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if self.lr_scheduler", "Get subdirectory used for Huggingface. subdirs = [ os.path.join(tune_checkpoint_dir, name)", "1, # We explicitly set save to 0, and do", "warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize our Trainer tune_trainer = TuneTransformerTrainer(", "errors at the encoding step in the collate_fn. # We", "(CLM) loss. BERT and RoBERTa are fine-tuned using a masked", "LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache,", "self.save_state() tune.report(**output.metrics) return output.metrics def save_state(self): with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir:", "field( default=False, metadata={\"help\": \"Whether distinct lines of text in the", "AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token': '<bos>', 'eos_token': '<eos>', 'pad_token': '<pad>'} num_added_toks", "model_args, data_args, training_args = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and", "else None ) if config_in.model_type == \"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling(", "instantiating a new config instance from scratch.\") if model_args.tokenizer_name: tokenizer", "flag to this script. # We now keep distinct sets", "'<eos>', 'pad_token': '<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in", "overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps: int): if", "logging import math import os from dataclasses import dataclass, field", "warmup_steps=0, # weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", # ) # # model_name_or_path", "model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path,", "# save_steps=0, # num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"],", "field( default=None, metadata={\"help\": \"An optional input evaluation data file to", ") # # model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # # num_labels", "= AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, ) else:", "in errors in the encoding step. Set the --force_pad_token flag", "recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # # num_labels = glue_tasks_num_labels[config[\"task_name\"]] # # config", "ignore this token # when feeding to the model.x tokenizer.add_special_tokens({\"pad_token\":", "if model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in,", "num_training_steps=num_training_steps ) return self.current_optimizer, self.current_scheduler def evaluate(self, eval_dataset= None): eval_dataloader", "Optional[str] = None, ): file_path = args.eval_data_file if evaluate else", "in no_decay)], \"weight_decay\": self.args.weight_decay, }, { \"params\": [p for n,", "\"data_dir\": \"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16, 32, 64]), \"learning_rate\": tune.uniform(1e-5,", "and tokenizer # # Distributed training: # The .from_pretrained methods", "[\"bert\", \"roberta\", \"distilbert\", \"camembert\"] and not data_args.mlm: raise ValueError( \"BERT", "# eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), # ) # tune_trainer.train(model_name_or_path) def train_transformer(config,", "description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics) return output.metrics def save_state(self): with tune.checkpoint_dir(step=self.global_step)", "5]), \"max_steps\": -1, # We use num_epochs instead. \"wandb\": {", "the library models for language modeling on a text file", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"\"\" model_name_or_path: Optional[str] = field( default=None, metadata={ \"help\": \"The model", "\"gpu\": 1 }, config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\",", "+ \", \".join(MODEL_TYPES)}, ) config_name: Optional[str] = field( default=None, metadata={\"help\":", "__name__ == \"__main__\": parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args,", "lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32,", "# def train_transformer(config, checkpoint_dir=None): # train_dataset, eval_dataset = get_datasets(config) #", "get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return self.current_optimizer, self.current_scheduler def evaluate(self,", "this token # when feeding to the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"})", "required by applicable law or agreed to in writing, software", "type from the list: \" + \", \".join(MODEL_TYPES)}, ) config_name:", "span of masked tokens for permutation language modeling.\"} ) block_size:", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "input length for single sentence inputs (take into account special", "length of a span of masked tokens for permutation language", "list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class", "float = field( default=0.15, metadata={\"help\": \"Ratio of tokens to mask", "= self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))", "tune_checkpoint_dir is None or len(tune_checkpoint_dir) == 0: return model_name #", "to train a model from scratch.\" }, ) model_type: Optional[str]", "Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",", "agreed to in writing, software # distributed under the License", "We give here the option to force the addition of", "handled as distinct sequences.\"}, ) mlm: bool = field( default=False,", "distributed under the License is distributed on an \"AS IS\"", "= AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token': '<bos>', 'eos_token': '<eos>', 'pad_token': '<pad>'}", "else None ) # print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset = ( get_dataset(data_args,", "configs below were defined earlier \"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\":", "encoding step. Set the --force_pad_token flag to fix this.\" )", "eval. \"\"\" train_data_file: Optional[str] = field( default=None, metadata={\"help\": \"The input", "going to fine-tune, or train from scratch. \"\"\" model_name_or_path: Optional[str]", "using a permutation language modeling (PLM) loss. \"\"\" import logging", "in the dataset are to be handled as distinct sequences.\"},", "output.metrics def save_state(self): with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir", "--tokenizer_name\" ) if tokenizer.pad_token_id is None: if model_args.force_pad_token: # See", "step in the collate_fn. # We give here the option", "addition of a pad token. The attention mask is used", "and os.path.isdir(model_args.model_name_or_path) else None ) tune_trainer.train(model_path=model_path) if __name__ == \"__main__\":", "Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights", "every epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + 1, # We explicitly", ") # print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset = ( get_dataset(data_args, tokenizer=tokenizer, evaluate=True,", "new tokenizer from scratch. This is not supported, but you", "{'bos_token': '<bos>', 'eos_token': '<eos>', 'pad_token': '<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer))", "into account special tokens).\" }, ) overwrite_cache: bool = field(", "# return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path,", "not any(nd in n for nd in no_decay)], \"weight_decay\": self.args.weight_decay,", "training and evaluation sets\"} ) def get_dataset( args: DataTrainingArguments, tokenizer:", "} } logger.info(config) scheduler = PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2,", "logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\",", "Arguments pertaining to which model/config/tokenizer we are going to fine-tune,", "no padding token. This may result in errors in the", "block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps: int):", ") def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool =", "# Get subdirectory used for Huggingface. subdirs = [ os.path.join(tune_checkpoint_dir,", "do it from another script, save it,\" \"and load it", "below were defined earlier \"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\": \"\",", "optional input evaluation data file to evaluate the perplexity on", "weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize our Trainer tune_trainer = TuneTransformerTrainer( model=model,", "errors in the encoding step. Set the --force_pad_token flag to", "distinct lines of text in the dataset are to be", "in self.model.named_parameters() if not any(nd in n for nd in", "modeling loss instead of language modeling.\"} ) mlm_probability: float =", "] self.optimizer = AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, )", "config[\"model_name\"]) # # num_labels = glue_tasks_num_labels[config[\"task_name\"]] # # config =", "is not empty. Use --overwrite_output_dir to overcome.\" ) # Setup", "if __name__ == \"__main__\": parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args,", "and evaluation sets\"} ) def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer,", "from scratch\") model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token': '<bos>', 'eos_token':", "= None, ): file_path = args.eval_data_file if evaluate else args.train_data_file", "in no_decay)], \"weight_decay\": 0.0, }, ] self.optimizer = AdamW( optimizer_grouped_parameters,", "): raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is", "device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",", ") tune_trainer.train(model_path=model_path) if __name__ == \"__main__\": parser = HfArgumentParser((ModelArguments, DataTrainingArguments,", "sequences.\"}, ) mlm: bool = field( default=False, metadata={\"help\": \"Train with", "( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, #", "dataclass, field from typing import Optional import torch from transformers.optimization", "\"project\": \"pbt_transformers\", \"reinit\": True, \"allow_val_change\": True } } logger.info(config) scheduler", "are fine-tuned using a causal language modeling (CLM) loss. BERT", "instead. \"wandb\": { \"project\": \"pbt_transformers\", \"reinit\": True, \"allow_val_change\": True }", "OR CONDITIONS OF ANY KIND, either express or implied. #", "addition of a padding token to tokenizer that does not", "max_span_length=data_args.max_span_length, ) else: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability )", "the License is distributed on an \"AS IS\" BASIS, #", "from scratch.\" }, ) model_type: Optional[str] = field( default=None, metadata={\"help\":", "fine-tuned using a causal language modeling (CLM) loss. BERT and", "do_eval=True, evaluate_during_training=True, # Run eval after every epoch. eval_steps=(len(train_dataset) //", "AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if self.lr_scheduler is", "name)) ] # There should only be 1 subdir. assert", "span of masked tokens to surrounding context length for permutation", "models do not have LM heads but masked LM heads.", "n, p in self.model.named_parameters() if not any(nd in n for", "to fix this.\" ) model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path:", "\"per_gpu_train_batch_size\": [16, 32, 64], }) reporter = CLIReporter( parameter_columns={ \"weight_decay\":", "metadata={\"help\": \"Where do you want to store the pretrained models", "# We use num_epochs instead. \"wandb\": { \"project\": \"pbt_transformers\", \"reinit\":", "self.args.weight_decay, }, { \"params\": [p for n, p in self.model.named_parameters()", "self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics) return output.metrics def save_state(self):", "model_name\"} ) tokenizer_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained tokenizer", "token. The attention mask is used to ignore this token", "law or agreed to in writing, software # distributed under", "= self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics) return output.metrics def", "glue_tasks_num_labels[config[\"task_name\"]] # # config = AutoConfig.from_pretrained( # model_name_or_path, # num_labels=num_labels,", "License. \"\"\" Fine-tuning the library models for language modeling on", "language modeling on a text file (GPT, GPT-2, CTRL, BERT,", "evaluation without an evaluation data file. Either supply a file", "sentence inputs (take into account special tokens).\" }, ) overwrite_cache:", "# # # Use our modified TuneTransformerTrainer # tune_trainer =", "will be truncated in block of this size for training.\"", "another script, save it,\" \"and load it from here, using", "None: no_decay = [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters = [ { \"params\":", "data_args.block_size = min(data_args.block_size, tokenizer.max_len) # Get datasets train_dataset = (", "our modified TuneTransformerTrainer # tune_trainer = TuneTransformerTrainer( # model=model, #", "may obtain a copy of the License at # #", "format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO", "\"help\": \"Whether to force the addition of a padding token", "typing import Optional import torch from transformers.optimization import AdamW, get_linear_schedule_with_warmup", "[p for n, p in self.model.named_parameters() if any(nd in n", "\"params\": [p for n, p in self.model.named_parameters() if any(nd in", "of args, for a cleaner separation of concerns. # parser", "may not use this file except in compliance with the", "tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class ModelArguments: \"\"\" Arguments", "hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\":", "this file except in compliance with the License. # You", "config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are", "\"num_epochs\" }, metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\" ]) analysis =", "model from scratch\") model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token': '<bos>',", "and is not empty. Use --overwrite_output_dir to overcome.\" ) #", "GPT-2 and CTRL are fine-tuned using a causal language modeling", "2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under", "force_pad_token: bool = field( default=False, metadata={ \"help\": \"Whether to force", "epoch. # eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + # 1, # #", "training_args = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise", "model_name_or_path: Optional[str] = field( default=None, metadata={ \"help\": \"The model checkpoint", "# # Licensed under the Apache License, Version 2.0 (the", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "eval_dataset= None): eval_dataloader = self.get_eval_dataloader(eval_dataset) output = self.prediction_loop( eval_dataloader, description=\"Evaluation\")", "default=None, metadata={\"help\": \"Pretrained config name or path if not the", "self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return self.current_optimizer, self.current_scheduler", "CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating a new config instance from scratch.\")", "model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics, ) if", "= tokenizer.max_len # Our input block size will be the", "file to --eval_data_file \" \"or remove the --do_eval argument.\" )", "one.\" }, ) debiasing_head: Optional[str] = field( default=None, metadata={\"help\": \"The", "( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) else", "causes errors at the encoding step in the collate_fn. #", "here the option to force the addition of a pad", "mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args = TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True,", "import CLIReporter # if is_wandb_available(): # import wandb ray.shutdown() ray.init(log_to_driver=True,", "5e-5), \"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2, 3, 4, 5]), \"max_steps\":", "= self.get_eval_dataloader(eval_dataset) output = self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics)", "field( default=None, metadata={ \"help\": \"The model checkpoint for weights initialization.", "cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in =", "metadata={\"help\": \"Ratio of tokens to mask for masked language modeling", "from scratch. This is not supported, but you can do", ") if self.lr_scheduler is None: self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps,", "fine-tuned using a masked language modeling (MLM) loss. XLNet is", "optimizer_grouped_parameters = [ { \"params\": [p for n, p in", "1, subdirs return subdirs[0] # def train_transformer(config, checkpoint_dir=None): # train_dataset,", "for nd in no_decay)], \"weight_decay\": self.args.weight_decay, }, { \"params\": [p", "metadata={ \"help\": \"Whether to force the addition of a padding", "{}'.format(train_dataset.examples[0])) eval_dataset = ( get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval", "<= 0: data_args.block_size = tokenizer.max_len # Our input block size", "cached training and evaluation sets\"} ) def get_dataset( args: DataTrainingArguments,", "is None: no_decay = [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters = [ {", "model_type: Optional[str] = field( default=None, metadata={\"help\": \"If training from scratch,", "field( default=None, metadata={\"help\": \"The input training data file (a text", "analysis = tune.run( train_transformer, resources_per_trial={ \"cpu\": 1, \"gpu\": 1 },", "= field( default=None, metadata={\"help\": \"If training from scratch, pass a", "tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self,", "= CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\":", "= field( default=-1, metadata={ \"help\": \"Optional input sequence length after", "BERT, RoBERTa, XLNet). GPT, GPT-2 and CTRL are fine-tuned using", "or implied. # See the License for the specific language", "\"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\" }, metric_columns=[ \"eval_acc\", \"eval_loss\",", "masked language modeling (MLM) loss. XLNet is fine-tuned using a", "should only be 1 subdir. assert len(subdirs) == 1, subdirs", "fine-tune, or train from scratch. \"\"\" model_name_or_path: Optional[str] = field(", "whose tokenizer has no padding token. This may result in", "train_dataset = ( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None", "data_args.mlm: raise ValueError( \"BERT and RoBERTa-like models do not have", "team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.", "\"You are instantiating a new tokenizer from scratch. This is", "loss. \"\"\" import logging import math import os from dataclasses", "seed set_seed(training_args.seed) # Load pretrained model and tokenizer # #", "used for Huggingface. subdirs = [ os.path.join(tune_checkpoint_dir, name) for name", "to which model/config/tokenizer we are going to fine-tune, or train", "# Use our modified TuneTransformerTrainer # tune_trainer = TuneTransformerTrainer( #", "model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning( \"Attempting to train a model", "sequence length after tokenization.\" \"The training dataset will be truncated", "as checkpoint_dir: self.args.output_dir = checkpoint_dir # This is the directory", "0.0, }, ] self.optimizer = AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2),", "fix this.\" ) model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path: model", "flag (masked language modeling).\" ) if data_args.block_size <= 0: data_args.block_size", "explicitly set save to 0, and do checkpointing in evaluate", "PreTrainedTokenizer, evaluate: bool = False, cache_dir: Optional[str] = None, ):", ") else: logger.info(\"Training new model from scratch\") model = AutoModelWithLMHead.from_config(config_in)", "model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path) else None ) tune_trainer.train(model_path=model_path)", "model type from the list: \" + \", \".join(MODEL_TYPES)}, )", "block size will be the max possible for the model", "Huggingface requires. output_dir = os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler", "were defined earlier \"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\":", "( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None ) #", "train a model from scratch.\" }, ) model_type: Optional[str] =", "\"Cannot do evaluation without an evaluation data file. Either supply", "@dataclass class DataTrainingArguments: \"\"\" Arguments pertaining to what data we", "to force the addition of a padding token to tokenizer", "# Run eval after every epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) +", "with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir # This is", "field( default=5, metadata={\"help\": \"Maximum length of a span of masked", "the cached training and evaluation sets\"} ) def get_dataset( args:", "do not have LM heads but masked LM heads. They", "block_size: int = field( default=-1, metadata={ \"help\": \"Optional input sequence", "# per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, # weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\",", "using a masked language modeling (MLM) loss. XLNet is fine-tuned", "modeling.\"} ) mlm_probability: float = field( default=0.15, metadata={\"help\": \"Ratio of", "self.save_model(output_dir) self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))", "subdir. assert len(subdirs) == 1, subdirs return subdirs[0] # def", ") # # # Use our modified TuneTransformerTrainer # tune_trainer", "@dataclass class ModelArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we", "for masked language modeling loss\"} ) plm_probability: float = field(", "All rights reserved. # # Licensed under the Apache License,", "use num_epochs instead. \"wandb\": { \"project\": \"pbt_transformers\", \"reinit\": True, \"allow_val_change\":", "not data_args.mlm: raise ValueError( \"BERT and RoBERTa-like models do not", "evaluation sets\"} ) def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate:", "length for single sentence inputs (take into account special tokens).\"", "do_train=True, # do_eval=True, # evaluate_during_training=True, # # Run eval after", "to this script. # We now keep distinct sets of", "vocab. if model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in", "= AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise ValueError( \"You are instantiating a", "= TuneTransformerTrainer( # model=model, # args=training_args, # train_dataset=train_dataset, # eval_dataset=eval_dataset,", "the --help flag to this script. # We now keep", "= field( default=1 / 6, metadata={ \"help\": \"Ratio of length", "# eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + # 1, # # We", "directory name that Huggingface requires. output_dir = os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\")", "num_training_steps: int): if self.optimizer is None: no_decay = [\"bias\", \"LayerNorm.weight\"]", "num_labels = glue_tasks_num_labels[config[\"task_name\"]] # # config = AutoConfig.from_pretrained( # model_name_or_path,", "HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, )", "and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f\"Output directory", "for conf in MODEL_CONFIG_CLASSES) @dataclass class ModelArguments: \"\"\" Arguments pertaining", "loss. XLNet is fine-tuned using a permutation language modeling (PLM)", "resources_per_trial={ \"cpu\": 1, \"gpu\": 1 }, config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3,", "# limitations under the License. \"\"\" Fine-tuning the library models", "def save_state(self): with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir #", ".from_pretrained methods guarantee that only one local process can concurrently", ") # model = AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, # config=config, #", "Team Authors and The HuggingFace Inc. team. # Copyright (c)", "no_decay = [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters = [ { \"params\": [p", "if model_args.force_pad_token: # See PR 3388. Some tokenizers don't had", "n for nd in no_decay)], \"weight_decay\": self.args.weight_decay, }, { \"params\":", "parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\" },", "ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not empty.", "Use --overwrite_output_dir to overcome.\" ) # Setup logging logging.basicConfig( format=\"%(asctime)s", "in writing, software # distributed under the License is distributed", "as distinct sequences.\"}, ) mlm: bool = field( default=False, metadata={\"help\":", "all possible arguments in src/transformers/training_args.py # or by passing the", "AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer,", "and do checkpointing in evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"],", "(take into account special tokens).\" }, ) overwrite_cache: bool =", "True, \"allow_val_change\": True } } logger.info(config) scheduler = PopulationBasedTraining( time_attr=\"training_iteration\",", "field( default=False, metadata={\"help\": \"Train with masked-language modeling loss instead of", "}, ) max_span_length: int = field( default=5, metadata={\"help\": \"Maximum length", "tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval else None ) if config_in.model_type", "tokenizer.pad_token_id is None: if model_args.force_pad_token: # See PR 3388. Some", "text file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). GPT, GPT-2", "torch from transformers.optimization import AdamW, get_linear_schedule_with_warmup from transformers import (", "and CTRL are fine-tuned using a causal language modeling (CLM)", "field from typing import Optional import torch from transformers.optimization import", "lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if self.lr_scheduler is None: self.lr_scheduler", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5,", "License, Version 2.0 (the \"License\"); # you may not use", "Leave None if you want to train a model from", "= field( default=False, metadata={ \"help\": \"Whether to force the addition", "model = AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, # config=config, # ) #", "used\"} ) @dataclass class DataTrainingArguments: \"\"\" Arguments pertaining to what", "ValueError( \"BERT and RoBERTa-like models do not have LM heads", "eval_dataset = get_datasets(config) # # training_args = TrainingArguments( # output_dir=tune.get_trial_dir(),", "not the same as model_name\"} ) tokenizer_name: Optional[str] = field(", "Optional[str] = field( default=None, metadata={\"help\": \"The input training data file", "args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size)", "# There should only be 1 subdir. assert len(subdirs) ==", "# We now keep distinct sets of args, for a", "# finetuning_task=task_name, # ) # model = AutoModelForSequenceClassification.from_pretrained( # model_name_or_path,", "\"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16,", "\"params\": [p for n, p in self.model.named_parameters() if not any(nd", "\"num_epochs\": tune.choice([2, 3, 4, 5]), \"max_steps\": -1, # We use", "the License for the specific language governing permissions and #", "None ) tune_trainer.train(model_path=model_path) if __name__ == \"__main__\": parser = HfArgumentParser((ModelArguments,", "\"Whether to force the addition of a padding token to", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "heads but masked LM heads. They must be run using", ") mlm: bool = field( default=False, metadata={\"help\": \"Train with masked-language", "raise ValueError( \"Cannot do evaluation without an evaluation data file.", "self.args.adam_beta2), eps=self.args.adam_epsilon, ) if self.lr_scheduler is None: self.lr_scheduler = get_linear_schedule_with_warmup(", "token. This may result in errors in the encoding step.", ") plm_probability: float = field( default=1 / 6, metadata={ \"help\":", "for training.\" \"Default to the model max input length for", "same as model_name\"} ) cache_dir: Optional[str] = field( default=None, metadata={\"help\":", "time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\":", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "to force the addition of a pad token. The attention", "logging_dir=\"./logs\", # ) # # model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) #", "if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( \"Cannot do", "compute_metrics=compute_metrics, ) if training_args.do_train: model_path = ( model_args.model_name_or_path if model_args.model_name_or_path", "wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys())", "This is not supported, but you can do it from", "text file).\"} ) eval_data_file: Optional[str] = field( default=None, metadata={\"help\": \"An", "= field( default=None, metadata={\"help\": \"Pretrained tokenizer name or path if", "if is_wandb_available(): # import wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger =", "TuneTransformerTrainer( # model=model, # args=training_args, # train_dataset=train_dataset, # eval_dataset=eval_dataset, #", ") mlm_probability: float = field( default=0.15, metadata={\"help\": \"Ratio of tokens", "tokenizer.max_len) # Get datasets train_dataset = ( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir)", "evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\")", "save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize", "script, save it,\" \"and load it from here, using --tokenizer_name\"", "f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir,", "\"Pretrained config name or path if not the same as", "os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir", "self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None):", "= logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf", "= min(data_args.block_size, tokenizer.max_len) # Get datasets train_dataset = ( get_dataset(data_args,", "# distributed under the License is distributed on an \"AS", "be handled as distinct sequences.\"}, ) mlm: bool = field(", "language modeling loss\"} ) plm_probability: float = field( default=1 /", "# Unless required by applicable law or agreed to in", "that does not already have one.\" }, ) debiasing_head: Optional[str]", "possible for the model else: data_args.block_size = min(data_args.block_size, tokenizer.max_len) #", "+ 1, # We explicitly set save to 0, and", "of masked tokens for permutation language modeling.\"} ) block_size: int", "TrainingArguments( # output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], # do_train=True, # do_eval=True, #", "!= -1), training_args.fp16, ) logger.info(\"Training/evaluation parameters %s\", training_args) # Set", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "Authors and The HuggingFace Inc. team. # Copyright (c) 2018,", "language modeling.\" }, ) max_span_length: int = field( default=5, metadata={\"help\":", "n_gpu: %s, distributed training: %s, 16-bits training: %s\", training_args.local_rank, training_args.device,", "== 0: return model_name # Get subdirectory used for Huggingface.", "masked tokens for permutation language modeling.\"} ) block_size: int =", "if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer =", "tokenizer from scratch. This is not supported, but you can", "(a text file).\"}, ) line_by_line: bool = field( default=False, metadata={\"help\":", "for n, p in self.model.named_parameters() if not any(nd in n", "True } } logger.info(config) scheduler = PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\",", "the Apache License, Version 2.0 (the \"License\"); # you may", "with masked-language modeling loss instead of language modeling.\"} ) mlm_probability:", "num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"], per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], warmup_steps=0, weight_decay=config[\"weight_decay\"], logging_dir=\"./logs\") # Initialize our", "cache_dir: Optional[str] = field( default=None, metadata={\"help\": \"Where do you want", "DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments,", "training_args.do_train else None ) # print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset = (", "model for training and eval. \"\"\" train_data_file: Optional[str] = field(", "no_decay)], \"weight_decay\": self.args.weight_decay, }, { \"params\": [p for n, p", "token # when feeding to the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else:", "name or path if not the same as model_name\"} )", "\"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16, 32, 64]), \"learning_rate\":", "tune_trainer.train(model_path=model_path) if __name__ == \"__main__\": parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))", "evaluate else args.train_data_file if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) #", "eval after every epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + 1, #", "model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16, 32,", "else: logger.info(\"Training new model from scratch\") model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict", "have one.\" }, ) debiasing_head: Optional[str] = field( default=None, metadata={\"help\":", "training.\" \"Default to the model max input length for single", "nd in no_decay)], \"weight_decay\": 0.0, }, ] self.optimizer = AdamW(", "or len(tune_checkpoint_dir) == 0: return model_name # Get subdirectory used", "here, using --tokenizer_name\" ) if tokenizer.pad_token_id is None: if model_args.force_pad_token:", "PR 3388. Some tokenizers don't had pad tokens which causes", "Optional[str] = field( default=None, metadata={\"help\": \"Pretrained tokenizer name or path", "PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) import ray from ray", "\"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16,", "tokenizer: PreTrainedTokenizer, evaluate: bool = False, cache_dir: Optional[str] = None,", "is not None and os.path.isdir(model_args.model_name_or_path) else None ) tune_trainer.train(model_path=model_path) if", "self.optimizer is None: no_decay = [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters = [", "torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir is None", "= os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360) if", "or path if not the same as model_name\"} ) tokenizer_name:", "tokenizer_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained tokenizer name or", "os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise", "store the pretrained models downloaded from s3\"} ) force_pad_token: bool", "is_wandb_available(): # import wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger = logging.getLogger(__name__)", "(a text file).\"} ) eval_data_file: Optional[str] = field( default=None, metadata={\"help\":", "We explicitly set save to 0, and do checkpointing in", "and not training_args.overwrite_output_dir ): raise ValueError( f\"Output directory ({training_args.output_dir}) already", "under the License is distributed on an \"AS IS\" BASIS,", "if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir,", "from ray.tune import CLIReporter # if is_wandb_available(): # import wandb", "to fine-tune, or train from scratch. \"\"\" model_name_or_path: Optional[str] =", "import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import PopulationBasedTraining from ray.tune import CLIReporter", "model checkpoint for weights initialization. Leave None if you want", "# weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", # ) # # model_name_or_path =", "else: config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating a new config", "tokenizer.max_len # Our input block size will be the max", "already have one.\" }, ) debiasing_head: Optional[str] = field( default=None,", "if config_in.model_type in [\"bert\", \"roberta\", \"distilbert\", \"camembert\"] and not data_args.mlm:", "if training_args.do_train else None ) # print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset =", "return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size,", "you can do it from another script, save it,\" \"and", "\"camembert\"] and not data_args.mlm: raise ValueError( \"BERT and RoBERTa-like models", "model_name # Get subdirectory used for Huggingface. subdirs = [", "to the model max input length for single sentence inputs", "permissions and # limitations under the License. \"\"\" Fine-tuning the", "# warmup_steps=0, # weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", # ) # #", "# We give here the option to force the addition", "tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32, 64], }) reporter = CLIReporter(", "{ \"params\": [p for n, p in self.model.named_parameters() if any(nd", "a pad token. The attention mask is used to ignore", "DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer,", "'<bos>', 'eos_token': '<eos>', 'pad_token': '<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if", "class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer is None:", "= False, cache_dir: Optional[str] = None, ): file_path = args.eval_data_file", "metadata={\"help\": \"Pretrained tokenizer name or path if not the same", "6, metadata={ \"help\": \"Ratio of length of a span of", "num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in [\"bert\", \"roberta\", \"distilbert\",", "evaluate: bool = False, cache_dir: Optional[str] = None, ): file_path", "every epoch. # eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + # 1, #", "file (a text file).\"} ) eval_data_file: Optional[str] = field( default=None,", "ANY KIND, either express or implied. # See the License", "subdirs = [ os.path.join(tune_checkpoint_dir, name) for name in os.listdir(tune_checkpoint_dir) if", "the License. # You may obtain a copy of the", "our model for training and eval. \"\"\" train_data_file: Optional[str] =", "logger.info(\"Training new model from scratch\") model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict =", "tokenization.\" \"The training dataset will be truncated in block of", "size for training.\" \"Default to the model max input length", "# See the License for the specific language governing permissions", "# ) # # model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # #", "== 1, subdirs return subdirs[0] # def train_transformer(config, checkpoint_dir=None): #", "= field( default=5, metadata={\"help\": \"Maximum length of a span of", "if any(nd in n for nd in no_decay)], \"weight_decay\": 0.0,", "be run using the\" \"--mlm flag (masked language modeling).\" )", "(c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed", "# LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) import", "config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\", name=\"tune_trans\") best_config =", "3 configs below were defined earlier \"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\",", "# # Run eval after every epoch. # eval_steps=(len(train_dataset) //", "\"allow_val_change\": True } } logger.info(config) scheduler = PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\",", "# model=model, # args=training_args, # train_dataset=train_dataset, # eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name),", "to 0, and do checkpointing in evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"],", "self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(),", "\"The type of de-biasing head to be used\"} ) @dataclass", "eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), # ) # tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None):", "Optional[str] = field( default=None, metadata={\"help\": \"Where do you want to", "# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. #", "num_epochs instead. \"wandb\": { \"project\": \"pbt_transformers\", \"reinit\": True, \"allow_val_change\": True", "remove the --do_eval argument.\" ) if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir)", "one local process can concurrently # download model & vocab.", "else: data_args.block_size = min(data_args.block_size, tokenizer.max_len) # Get datasets train_dataset =", "\"Ratio of length of a span of masked tokens to", "eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics, ) if training_args.do_train: model_path = (", "not empty. Use --overwrite_output_dir to overcome.\" ) # Setup logging", "DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args = TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"],", "for n, p in self.model.named_parameters() if any(nd in n for", "None and training_args.do_eval: raise ValueError( \"Cannot do evaluation without an", "Distributed training: # The .from_pretrained methods guarantee that only one", "PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None),", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "writing, software # distributed under the License is distributed on", "from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling,", "file to evaluate the perplexity on (a text file).\"}, )", "(masked language modeling).\" ) if data_args.block_size <= 0: data_args.block_size =", "set save to 0, and do checkpointing in evaluate instead", "but masked LM heads. They must be run using the\"", "tokenizer # # Distributed training: # The .from_pretrained methods guarantee", "= args.eval_data_file if evaluate else args.train_data_file if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer,", "are instantiating a new tokenizer from scratch. This is not", "self.get_eval_dataloader(eval_dataset) output = self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics) return", "training_args.do_eval else None ) if config_in.model_type == \"xlnet\": data_collator =", "config_in.model_type in [\"bert\", \"roberta\", \"distilbert\", \"camembert\"] and not data_args.mlm: raise", "earlier \"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\":", "\" \"or remove the --do_eval argument.\" ) if ( os.path.exists(training_args.output_dir)", "to ignore this token # when feeding to the model.x", "== \"__main__\": parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args", "# See PR 3388. Some tokenizers don't had pad tokens", "(GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). GPT, GPT-2 and CTRL", "MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class ModelArguments:", "max input length for single sentence inputs (take into account", "GPT-2, CTRL, BERT, RoBERTa, XLNet). GPT, GPT-2 and CTRL are", "\"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32, 64], }) reporter", "token to tokenizer that does not already have one.\" },", "the max possible for the model else: data_args.block_size = min(data_args.block_size,", "\"--mlm flag (masked language modeling).\" ) if data_args.block_size <= 0:", "training_args = parser.parse_args_into_dataclasses() config = { # These 3 configs", "to 0, and do checkpointing in evaluate instead # save_steps=0,", "you want to train a model from scratch.\" }, )", "tune_trainer = TuneTransformerTrainer( # model=model, # args=training_args, # train_dataset=train_dataset, #", "LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) import ray", "scratch. \"\"\" model_name_or_path: Optional[str] = field( default=None, metadata={ \"help\": \"The", "language modeling (PLM) loss. \"\"\" import logging import math import", "# Our input block size will be the max possible", "self.args.output_dir = checkpoint_dir # This is the directory name that", "TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True, # Run eval after", "modeling (MLM) loss. XLNet is fine-tuned using a permutation language", "ignore_reinit_error=True) logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type", "= field( default=False, metadata={\"help\": \"Overwrite the cached training and evaluation", "# Get datasets train_dataset = ( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if", "= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # model_args, data_args, training_args = parser.parse_args_into_dataclasses()", "must be run using the\" \"--mlm flag (masked language modeling).\"", "language governing permissions and # limitations under the License. \"\"\"", "modeling on a text file (GPT, GPT-2, CTRL, BERT, RoBERTa,", "\"weight_decay\": 0.0, }, ] self.optimizer = AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1,", "[ { \"params\": [p for n, p in self.model.named_parameters() if", "self.model.named_parameters() if not any(nd in n for nd in no_decay)],", "MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)", "or train from scratch. \"\"\" model_name_or_path: Optional[str] = field( default=None,", "--help flag to this script. # We now keep distinct", "path if not the same as model_name\"} ) tokenizer_name: Optional[str]", ") tokenizer_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained tokenizer name", "bool = field( default=False, metadata={ \"help\": \"Whether to force the", "pertaining to what data we are going to input our", "\"\"\" Fine-tuning the library models for language modeling on a", "ValueError( \"You are instantiating a new tokenizer from scratch. This", "This is the directory name that Huggingface requires. output_dir =", "\"optimizer.pt\")) torch.save(self.current_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir is", "\" + \", \".join(MODEL_TYPES)}, ) config_name: Optional[str] = field( default=None,", "def create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer is None: no_decay =", "directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir", "}, ) overwrite_cache: bool = field( default=False, metadata={\"help\": \"Overwrite the", "tokens to surrounding context length for permutation language modeling.\" },", "arguments in src/transformers/training_args.py # or by passing the --help flag", "Optional[str] = field( default=None, metadata={\"help\": \"Pretrained config name or path", "training_args = TrainingArguments( # output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], # do_train=True, #", "weights initialization. Leave None if you want to train a", "else None ) tune_trainer.train(model_path=model_path) if __name__ == \"__main__\": parser =", ") eval_data_file: Optional[str] = field( default=None, metadata={\"help\": \"An optional input", "bool = False, cache_dir: Optional[str] = None, ): file_path =", "field( default=0.15, metadata={\"help\": \"Ratio of tokens to mask for masked", "length of a span of masked tokens to surrounding context", "from typing import Optional import torch from transformers.optimization import AdamW,", "else: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args =", "self.current_scheduler def evaluate(self, eval_dataset= None): eval_dataloader = self.get_eval_dataloader(eval_dataset) output =", "the same as model_name\"} ) cache_dir: Optional[str] = field( default=None,", "for the model else: data_args.block_size = min(data_args.block_size, tokenizer.max_len) # Get", "# See all possible arguments in src/transformers/training_args.py # or by", "model whose tokenizer has no padding token. This may result", "tune.choice([2, 3, 4, 5]), \"max_steps\": -1, # We use num_epochs", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "model_path = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and", "cache_dir=model_args.cache_dir) if training_args.do_train else None ) # print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset", "def train_transformer(config, checkpoint_dir=None): # train_dataset, eval_dataset = get_datasets(config) # #", "line_by_line: bool = field( default=False, metadata={\"help\": \"Whether distinct lines of", "length after tokenization.\" \"The training dataset will be truncated in", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "MODEL_CONFIG_CLASSES) @dataclass class ModelArguments: \"\"\" Arguments pertaining to which model/config/tokenizer", "\"scheduler.pt\")) def recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir is None or len(tune_checkpoint_dir)", "import math import os from dataclasses import dataclass, field from", "coding=utf-8 # Copyright 2018 The Google AI Language Team Authors", "checkpoint_dir=None): # See all possible arguments in src/transformers/training_args.py # or", "mlm_probability=data_args.mlm_probability ) training_args = TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True,", "= recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # # num_labels = glue_tasks_num_labels[config[\"task_name\"]] # #", "MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset,", "cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise ValueError(", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "args.train_data_file if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer,", "no_decay)], \"weight_decay\": 0.0, }, ] self.optimizer = AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate,", "set_seed(training_args.seed) # Load pretrained model and tokenizer # # Distributed", "if self.lr_scheduler is None: self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps", "training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( \"Process rank:", "default=5, metadata={\"help\": \"Maximum length of a span of masked tokens", "eval after every epoch. # eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + #", "rights reserved. # # Licensed under the Apache License, Version", "limitations under the License. \"\"\" Fine-tuning the library models for", "and RoBERTa-like models do not have LM heads but masked", "%s, 16-bits training: %s\", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1),", "# compute_metrics=compute_metrics, ) if training_args.do_train: model_path = ( model_args.model_name_or_path if", "transformers.optimization import AdamW, get_linear_schedule_with_warmup from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING,", "learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True, # Run eval after every epoch.", "dataclasses import dataclass, field from typing import Optional import torch", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "to the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning( \"Attempting to train", "\"If training from scratch, pass a model type from the", "AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer, TextDataset,", "int = field( default=5, metadata={\"help\": \"Maximum length of a span", "= field( default=False, metadata={\"help\": \"Whether distinct lines of text in", "os from dataclasses import dataclass, field from typing import Optional", "Optional[str] = field( default=None, metadata={\"help\": \"An optional input evaluation data", "- %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if training_args.local_rank in [-1, 0]", "force the addition of a pad token. The attention mask", "field( default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not", "5e-5).func(None), \"per_gpu_train_batch_size\": [16, 32, 64], }) reporter = CLIReporter( parameter_columns={", "specific language governing permissions and # limitations under the License.", ") model_type: Optional[str] = field( default=None, metadata={\"help\": \"If training from", "language modeling).\" ) if data_args.block_size <= 0: data_args.block_size = tokenizer.max_len", "mlm: bool = field( default=False, metadata={\"help\": \"Train with masked-language modeling", "this.\" ) model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path: model =", "# # We explicitly set save to 0, and do", ") @dataclass class DataTrainingArguments: \"\"\" Arguments pertaining to what data", "language modeling.\"} ) mlm_probability: float = field( default=0.15, metadata={\"help\": \"Ratio", "had pad tokens which causes errors at the encoding step", "# you may not use this file except in compliance", "Optional[str] = field( default=None, metadata={ \"help\": \"The model checkpoint for", "model max input length for single sentence inputs (take into", "(PLM) loss. \"\"\" import logging import math import os from", "Optional import torch from transformers.optimization import AdamW, get_linear_schedule_with_warmup from transformers", ") logger.info(\"Training/evaluation parameters %s\", training_args) # Set seed set_seed(training_args.seed) #", "rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits", "and # limitations under the License. \"\"\" Fine-tuning the library", "if evaluate else args.train_data_file if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size)", "modeling loss\"} ) plm_probability: float = field( default=1 / 6,", "for Huggingface. subdirs = [ os.path.join(tune_checkpoint_dir, name) for name in", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool = False, cache_dir: Optional[str]", "tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm,", "# Load pretrained model and tokenizer # # Distributed training:", "None ) # print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset = ( get_dataset(data_args, tokenizer=tokenizer,", "a new tokenizer from scratch. This is not supported, but", "are going to fine-tune, or train from scratch. \"\"\" model_name_or_path:", "\"Attempting to train a model whose tokenizer has no padding", "== \"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else:", "if config_in.model_type == \"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length,", "loss. BERT and RoBERTa are fine-tuned using a masked language", "in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] # There should only", "under the Apache License, Version 2.0 (the \"License\"); # you", "concurrently # download model & vocab. if model_args.config_name: config_in =", "model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, ) else: logger.info(\"Training new model from scratch\")", "perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda: tune.uniform(1e-5, 5e-5).func(None),", "default=False, metadata={\"help\": \"Train with masked-language modeling loss instead of language", "None): eval_dataloader = self.get_eval_dataloader(eval_dataset) output = self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics)", "Language Team Authors and The HuggingFace Inc. team. # Copyright", "a file to --eval_data_file \" \"or remove the --do_eval argument.\"", "are to be handled as distinct sequences.\"}, ) mlm: bool", "of a pad token. The attention mask is used to", "# max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, # weight_decay=config[\"weight_decay\"],", "overwrite_cache: bool = field( default=False, metadata={\"help\": \"Overwrite the cached training", "field( default=None, metadata={\"help\": \"Pretrained config name or path if not", "logging.WARN, ) logger.warning( \"Process rank: %s, device: %s, n_gpu: %s,", "is fine-tuned using a permutation language modeling (PLM) loss. \"\"\"", "loss instead of language modeling.\"} ) mlm_probability: float = field(", "config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating a new config instance", "TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer): def", "pertaining to which model/config/tokenizer we are going to fine-tune, or", "64]), \"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2, 3,", "<filename>examples/language-modeling/debias_lm_hps_tune.py # coding=utf-8 # Copyright 2018 The Google AI Language", "= field( default=None, metadata={\"help\": \"An optional input evaluation data file", "print('train_dataset {}'.format(train_dataset.examples[0])) eval_dataset = ( get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if", "lines of text in the dataset are to be handled", "\"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s,", "argument.\" ) if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "collate_fn. # We give here the option to force the", "default=None, metadata={ \"help\": \"The model checkpoint for weights initialization. Leave", "of a padding token to tokenizer that does not already", "per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, # weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", #", "betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if self.lr_scheduler is None: self.lr_scheduler =", "- %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if", "the encoding step in the collate_fn. # We give here", "cache_dir: Optional[str] = None, ): file_path = args.eval_data_file if evaluate", "a span of masked tokens to surrounding context length for", "0, and do checkpointing in evaluate instead # save_steps=0, #", "do you want to store the pretrained models downloaded from", ") if tokenizer.pad_token_id is None: if model_args.force_pad_token: # See PR", "model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if model_args.model_name_or_path: model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path,", "--eval_data_file \" \"or remove the --do_eval argument.\" ) if (", "models downloaded from s3\"} ) force_pad_token: bool = field( default=False,", "self.optimizer = AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if", "model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token': '<bos>', 'eos_token': '<eos>', 'pad_token':", "tokenizer name or path if not the same as model_name\"}", "don't had pad tokens which causes errors at the encoding", "= TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True, # Run eval", "HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All", "save_state(self): with tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir # This", "The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION.", "\"\"\" Arguments pertaining to what data we are going to", "do checkpointing in evaluate instead # save_steps=0, # num_train_epochs=config[\"num_epochs\"], #", "the addition of a pad token. The attention mask is", "scratch.\" }, ) model_type: Optional[str] = field( default=None, metadata={\"help\": \"If", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "scratch, pass a model type from the list: \" +", "text file).\"}, ) line_by_line: bool = field( default=False, metadata={\"help\": \"Whether", "data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args = TrainingArguments(", "are instantiating a new config instance from scratch.\") if model_args.tokenizer_name:", "permutation language modeling.\"} ) block_size: int = field( default=-1, metadata={", "mask is used to ignore this token # when feeding", "HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() config =", "CORPORATION. All rights reserved. # # Licensed under the Apache", "training dataset will be truncated in block of this size", "metadata={ \"help\": \"Ratio of length of a span of masked", "to evaluate the perplexity on (a text file).\"}, ) line_by_line:", "path if not the same as model_name\"} ) cache_dir: Optional[str]", "Apache License, Version 2.0 (the \"License\"); # you may not", "model=model, # args=training_args, # train_dataset=train_dataset, # eval_dataset=eval_dataset, # compute_metrics=utils.build_compute_metrics_fn(task_name), #", "either express or implied. # See the License for the", "from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from ray.tune.schedulers import PopulationBasedTraining from ray.tune", "# Initialize our Trainer tune_trainer = TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator,", "training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info(\"Training/evaluation parameters", "] # There should only be 1 subdir. assert len(subdirs)", "16-bits training: %s\", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16,", "3388. Some tokenizers don't had pad tokens which causes errors", "logger.info(config) scheduler = PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\":", "parameters %s\", training_args) # Set seed set_seed(training_args.seed) # Load pretrained", "special_tokens_dict = {'bos_token': '<bos>', 'eos_token': '<eos>', 'pad_token': '<pad>'} num_added_toks =", "do evaluation without an evaluation data file. Either supply a", "the model max input length for single sentence inputs (take", "return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer):", "is None and training_args.do_eval: raise ValueError( \"Cannot do evaluation without", "be truncated in block of this size for training.\" \"Default", "tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2, 3, 4, 5]), \"max_steps\": -1, #", "using a causal language modeling (CLM) loss. BERT and RoBERTa", "# learning_rate=config[\"learning_rate\"], # do_train=True, # do_eval=True, # evaluate_during_training=True, # #", "input training data file (a text file).\"} ) eval_data_file: Optional[str]", "AutoConfig.from_pretrained( # model_name_or_path, # num_labels=num_labels, # finetuning_task=task_name, # ) #", "Google AI Language Team Authors and The HuggingFace Inc. team.", "n, p in self.model.named_parameters() if any(nd in n for nd", "%s, distributed training: %s, 16-bits training: %s\", training_args.local_rank, training_args.device, training_args.n_gpu,", "be 1 subdir. assert len(subdirs) == 1, subdirs return subdirs[0]", "pass a model type from the list: \" + \",", "LineByLineTextDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) import ray from", "want to train a model from scratch.\" }, ) model_type:", "model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) # # num_labels = glue_tasks_num_labels[config[\"task_name\"]] #", "None and os.path.isdir(model_args.model_name_or_path) else None ) tune_trainer.train(model_path=model_path) if __name__ ==", "in [-1, 0] else logging.WARN, ) logger.warning( \"Process rank: %s,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "class DataTrainingArguments: \"\"\" Arguments pertaining to what data we are", "0] else logging.WARN, ) logger.warning( \"Process rank: %s, device: %s,", "training: %s\", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, )", "from transformers.optimization import AdamW, get_linear_schedule_with_warmup from transformers import ( CONFIG_MAPPING,", "# parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # model_args, data_args, training_args", "TrainingArguments, set_seed, ) import ray from ray import tune from", "else: raise ValueError( \"You are instantiating a new tokenizer from", "\"help\": \"Optional input sequence length after tokenization.\" \"The training dataset", "inputs (take into account special tokens).\" }, ) overwrite_cache: bool", "give here the option to force the addition of a", "data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics, ) if training_args.do_train: model_path", "{ \"project\": \"pbt_transformers\", \"reinit\": True, \"allow_val_change\": True } } logger.info(config)", "= AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating", "subdirs return subdirs[0] # def train_transformer(config, checkpoint_dir=None): # train_dataset, eval_dataset", "src/transformers/training_args.py # or by passing the --help flag to this", "def train_transformer(config, checkpoint_dir=None): # See all possible arguments in src/transformers/training_args.py", "Arguments pertaining to what data we are going to input", "= parser.parse_args_into_dataclasses() config = { # These 3 configs below", "\"Maximum length of a span of masked tokens for permutation", "# model_name_or_path, # config=config, # ) # # # Use", "training_args) # Set seed set_seed(training_args.seed) # Load pretrained model and", "import Optional import torch from transformers.optimization import AdamW, get_linear_schedule_with_warmup from", "evaluate instead # save_steps=0, # num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"],", "training_args.do_eval: raise ValueError( \"Cannot do evaluation without an evaluation data", "eval_dataset = ( get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval else", "in src/transformers/training_args.py # or by passing the --help flag to", "GPT, GPT-2 and CTRL are fine-tuned using a causal language", "is used to ignore this token # when feeding to", "will be the max possible for the model else: data_args.block_size", "or by passing the --help flag to this script. #", "requires. output_dir = os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler =", "governing permissions and # limitations under the License. \"\"\" Fine-tuning", "\"cpu\": 1, \"gpu\": 1 }, config=config, num_samples=3, scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\",", "= field( default=None, metadata={\"help\": \"Pretrained config name or path if", "\"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16, 32, 64]), \"learning_rate\": tune.uniform(1e-5, 5e-5),", "data file (a text file).\"} ) eval_data_file: Optional[str] = field(", "if not the same as model_name\"} ) cache_dir: Optional[str] =", "default=False, metadata={\"help\": \"Whether distinct lines of text in the dataset", "for permutation language modeling.\"} ) block_size: int = field( default=-1,", "# num_labels=num_labels, # finetuning_task=task_name, # ) # model = AutoModelForSequenceClassification.from_pretrained(", "import AdamW, get_linear_schedule_with_warmup from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig,", "to input our model for training and eval. \"\"\" train_data_file:", "# These 3 configs below were defined earlier \"model_name\": model_args.model_name_or_path,", "of a span of masked tokens to surrounding context length", "file. Either supply a file to --eval_data_file \" \"or remove", "language modeling (CLM) loss. BERT and RoBERTa are fine-tuned using", "distinct sets of args, for a cleaner separation of concerns.", "heads. They must be run using the\" \"--mlm flag (masked", "None if you want to train a model from scratch.\"", "training_args.overwrite_output_dir ): raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and", "tune_trainer = TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, #", "use this file except in compliance with the License. #", "we are going to fine-tune, or train from scratch. \"\"\"", "# # config = AutoConfig.from_pretrained( # model_name_or_path, # num_labels=num_labels, #", "32, \"per_gpu_train_batch_size\": tune.choice([16, 32, 64]), \"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0,", "instantiating a new tokenizer from scratch. This is not supported,", "file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). GPT, GPT-2 and", "reserved. # # Licensed under the Apache License, Version 2.0", "model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise ValueError( \"You are", "after every epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + 1, # We", "be used\"} ) @dataclass class DataTrainingArguments: \"\"\" Arguments pertaining to", "3, 4, 5]), \"max_steps\": -1, # We use num_epochs instead.", "overcome.\" ) # Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s -", "for language modeling on a text file (GPT, GPT-2, CTRL,", "# coding=utf-8 # Copyright 2018 The Google AI Language Team", "= tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class ModelArguments: \"\"\"", "# per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, # weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", # )", "# train_dataset, eval_dataset = get_datasets(config) # # training_args = TrainingArguments(", "name in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] # There should", "]) analysis = tune.run( train_transformer, resources_per_trial={ \"cpu\": 1, \"gpu\": 1", "= TrainingArguments( # output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], # do_train=True, # do_eval=True,", "Optional[str] = field( default=None, metadata={\"help\": \"The type of de-biasing head", "Load pretrained model and tokenizer # # Distributed training: #", "= field( default=None, metadata={\"help\": \"Where do you want to store", "training_args.fp16, ) logger.info(\"Training/evaluation parameters %s\", training_args) # Set seed set_seed(training_args.seed)", "max_span_length: int = field( default=5, metadata={\"help\": \"Maximum length of a", "the option to force the addition of a pad token.", "They must be run using the\" \"--mlm flag (masked language", "\"or remove the --do_eval argument.\" ) if ( os.path.exists(training_args.output_dir) and", "# 1, # # We explicitly set save to 0,", "default=1 / 6, metadata={ \"help\": \"Ratio of length of a", "model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, ) else: logger.info(\"Training new", "cache_dir=model_args.cache_dir, ) else: logger.info(\"Training new model from scratch\") model =", "= tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in [\"bert\", \"roberta\", \"distilbert\", \"camembert\"]", "recover_checkpoint(tune_checkpoint_dir, model_name=None): if tune_checkpoint_dir is None or len(tune_checkpoint_dir) == 0:", "to --eval_data_file \" \"or remove the --do_eval argument.\" ) if", "tokenizers don't had pad tokens which causes errors at the", "raise ValueError( f\"Output directory ({training_args.output_dir}) already exists and is not", "in compliance with the License. # You may obtain a", "of concerns. # parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) # model_args,", "software # distributed under the License is distributed on an", "when feeding to the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning( \"Attempting", "= CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You are instantiating a new config instance from", "if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path,", "new config instance from scratch.\") if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name,", "a permutation language modeling (PLM) loss. \"\"\" import logging import", "default=0.15, metadata={\"help\": \"Ratio of tokens to mask for masked language", "get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool = False, cache_dir:", "os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360) if self.is_world_master():", "a padding token to tokenizer that does not already have", "[ os.path.join(tune_checkpoint_dir, name) for name in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name))", "pad token. The attention mask is used to ignore this", "parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( \"Cannot", "config=config, # ) # # # Use our modified TuneTransformerTrainer", ") # Setup logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s", "the License. \"\"\" Fine-tuning the library models for language modeling", "in evaluate instead # save_steps=0, # num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], #", "of masked tokens to surrounding context length for permutation language", "a causal language modeling (CLM) loss. BERT and RoBERTa are", "self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360) if self.is_world_master(): torch.save(self.current_optimizer.state_dict(),", "( get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval else None )", "scratch\") model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token': '<bos>', 'eos_token': '<eos>',", "\"training_iteration\" ]) analysis = tune.run( train_transformer, resources_per_trial={ \"cpu\": 1, \"gpu\":", "train_transformer(config, checkpoint_dir=None): # train_dataset, eval_dataset = get_datasets(config) # # training_args", "os.path.join(tune_checkpoint_dir, name) for name in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ]", "head to be used\"} ) @dataclass class DataTrainingArguments: \"\"\" Arguments", "TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer is None: no_decay", "None: if model_args.force_pad_token: # See PR 3388. Some tokenizers don't", "cache_dir=model_args.cache_dir) else: raise ValueError( \"You are instantiating a new tokenizer", ") overwrite_cache: bool = field( default=False, metadata={\"help\": \"Overwrite the cached", "not have LM heads but masked LM heads. They must", "want to store the pretrained models downloaded from s3\"} )", "data_args.eval_data_file is None and training_args.do_eval: raise ValueError( \"Cannot do evaluation", "= tune.run( train_transformer, resources_per_trial={ \"cpu\": 1, \"gpu\": 1 }, config=config,", "to store the pretrained models downloaded from s3\"} ) force_pad_token:", "a cleaner separation of concerns. # parser = HfArgumentParser((ModelArguments, DataTrainingArguments,", "save it,\" \"and load it from here, using --tokenizer_name\" )", "with the License. # You may obtain a copy of", "\"eval_loss\", \"epoch\", \"training_iteration\" ]) analysis = tune.run( train_transformer, resources_per_trial={ \"cpu\":", "a model whose tokenizer has no padding token. This may", "0: data_args.block_size = tokenizer.max_len # Our input block size will", "from scratch.\") if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path:", "False, cache_dir: Optional[str] = None, ): file_path = args.eval_data_file if", "level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning(", "output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], # do_train=True, # do_eval=True, # evaluate_during_training=True, #", "training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info(\"Training/evaluation parameters %s\", training_args)", "\"The model checkpoint for weights initialization. Leave None if you", "# # num_labels = glue_tasks_num_labels[config[\"task_name\"]] # # config = AutoConfig.from_pretrained(", "metadata={\"help\": \"Maximum length of a span of masked tokens for", "32, 64], }) reporter = CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\":", "model_name=None): if tune_checkpoint_dir is None or len(tune_checkpoint_dir) == 0: return", "\"max_steps\": -1, # We use num_epochs instead. \"wandb\": { \"project\":", "on (a text file).\"}, ) line_by_line: bool = field( default=False,", "cache_dir=cache_dir, ) class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer", "permutation language modeling (PLM) loss. \"\"\" import logging import math", "self.current_optimizer, self.current_scheduler def evaluate(self, eval_dataset= None): eval_dataloader = self.get_eval_dataloader(eval_dataset) output", "return subdirs[0] # def train_transformer(config, checkpoint_dir=None): # train_dataset, eval_dataset =", "# model_args, data_args, training_args = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None", "weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", # ) # # model_name_or_path = recover_checkpoint(checkpoint_dir,", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "%s, n_gpu: %s, distributed training: %s, 16-bits training: %s\", training_args.local_rank,", "of language modeling.\"} ) mlm_probability: float = field( default=0.15, metadata={\"help\":", "The attention mask is used to ignore this token #", "get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval else None ) if", "masked LM heads. They must be run using the\" \"--mlm", "from scratch, pass a model type from the list: \"", "TuneTransformerTrainer # tune_trainer = TuneTransformerTrainer( # model=model, # args=training_args, #", "causal language modeling (CLM) loss. BERT and RoBERTa are fine-tuned", "only one local process can concurrently # download model &", "\"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\" }, metric_columns=[", "config instance from scratch.\") if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir)", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "# Copyright 2018 The Google AI Language Team Authors and", "model and tokenizer # # Distributed training: # The .from_pretrained", "# The .from_pretrained methods guarantee that only one local process", "force the addition of a padding token to tokenizer that", "metadata={\"help\": \"Pretrained config name or path if not the same", "scratch. This is not supported, but you can do it", "data file to evaluate the perplexity on (a text file).\"},", "CONDITIONS OF ANY KIND, either express or implied. # See", "file_path = args.eval_data_file if evaluate else args.train_data_file if args.line_by_line: return", "The Google AI Language Team Authors and The HuggingFace Inc.", "initialization. Leave None if you want to train a model", "sets\"} ) def get_dataset( args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate: bool", "raise ValueError( \"BERT and RoBERTa-like models do not have LM", "instead # save_steps=0, # num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], #", "/ 6, metadata={ \"help\": \"Ratio of length of a span", "the --force_pad_token flag to fix this.\" ) model_name_or_path = recover_checkpoint(checkpoint_dir,", "now keep distinct sets of args, for a cleaner separation", "but you can do it from another script, save it,\"", "Run eval after every epoch. eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + 1,", "save to 0, and do checkpointing in evaluate instead #", "field( default=None, metadata={\"help\": \"If training from scratch, pass a model", "= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() config", "are fine-tuned using a masked language modeling (MLM) loss. XLNet", "config_in.model_type == \"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, )", "padding token to tokenizer that does not already have one.\"", "plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability", "metadata={ \"help\": \"The model checkpoint for weights initialization. Leave None", "Our input block size will be the max possible for", "\"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16, 32, 64]), \"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\":", ") if data_args.block_size <= 0: data_args.block_size = tokenizer.max_len # Our", "train from scratch. \"\"\" model_name_or_path: Optional[str] = field( default=None, metadata={", "data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else: data_collator =", "eval_dataloader = self.get_eval_dataloader(eval_dataset) output = self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state()", "the perplexity on (a text file).\"}, ) line_by_line: bool =", "config[\"per_gpu_train_batch_size\"]) + # 1, # # We explicitly set save", "for a cleaner separation of concerns. # parser = HfArgumentParser((ModelArguments,", "account special tokens).\" }, ) overwrite_cache: bool = field( default=False,", "parser.parse_args_into_dataclasses() config = { # These 3 configs below were", "config_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained config name or", "empty. Use --overwrite_output_dir to overcome.\" ) # Setup logging logging.basicConfig(", "evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval else None ) if config_in.model_type ==", "pretrained models downloaded from s3\"} ) force_pad_token: bool = field(", "Trainer tune_trainer = TuneTransformerTrainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True,", "logger.info(\"Training/evaluation parameters %s\", training_args) # Set seed set_seed(training_args.seed) # Load", "RoBERTa, XLNet). GPT, GPT-2 and CTRL are fine-tuned using a", "the model else: data_args.block_size = min(data_args.block_size, tokenizer.max_len) # Get datasets", "# config = AutoConfig.from_pretrained( # model_name_or_path, # num_labels=num_labels, # finetuning_task=task_name,", "model from scratch.\" }, ) model_type: Optional[str] = field( default=None,", "# compute_metrics=utils.build_compute_metrics_fn(task_name), # ) # tune_trainer.train(model_name_or_path) def train_transformer(config, checkpoint_dir=None): #", "field( default=1 / 6, metadata={ \"help\": \"Ratio of length of", "1, # # We explicitly set save to 0, and", "None: self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return self.current_optimizer,", "to train a model whose tokenizer has no padding token.", "# # Distributed training: # The .from_pretrained methods guarantee that", "-1), training_args.fp16, ) logger.info(\"Training/evaluation parameters %s\", training_args) # Set seed", "as model_name\"} ) cache_dir: Optional[str] = field( default=None, metadata={\"help\": \"Where", "import os from dataclasses import dataclass, field from typing import", "default=False, metadata={\"help\": \"Overwrite the cached training and evaluation sets\"} )", "tokens which causes errors at the encoding step in the", "tune.checkpoint_dir(step=self.global_step) as checkpoint_dir: self.args.output_dir = checkpoint_dir # This is the", "flag to fix this.\" ) model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"]) if", "from ray import tune from transformers.file_utils import is_torch_tpu_available from transformers.trainer_utils", "loss\"} ) plm_probability: float = field( default=1 / 6, metadata={", "ray.init(log_to_driver=True, ignore_reinit_error=True) logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES =", "({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to", "[16, 32, 64], }) reporter = CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\",", "is None: self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return", "assert len(subdirs) == 1, subdirs return subdirs[0] # def train_transformer(config,", "--overwrite_output_dir to overcome.\" ) # Setup logging logging.basicConfig( format=\"%(asctime)s -", "truncated in block of this size for training.\" \"Default to", "logger.warning( \"Attempting to train a model whose tokenizer has no", "if model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: config_in =", "can concurrently # download model & vocab. if model_args.config_name: config_in", "training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f\"Output directory ({training_args.output_dir})", "'pad_token': '<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if config_in.model_type in [\"bert\",", "config = AutoConfig.from_pretrained( # model_name_or_path, # num_labels=num_labels, # finetuning_task=task_name, #", "for name in os.listdir(tune_checkpoint_dir) if os.path.isdir(os.path.join(tune_checkpoint_dir, name)) ] # There", "}, ] self.optimizer = AdamW( optimizer_grouped_parameters, lr=self.args.learning_rate, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon,", "tokenizer that does not already have one.\" }, ) debiasing_head:", "LM heads. They must be run using the\" \"--mlm flag", "scratch.\") if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer", "and training_args.do_eval: raise ValueError( \"Cannot do evaluation without an evaluation", "= parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError(", "bool = field( default=False, metadata={\"help\": \"Whether distinct lines of text", "\"xlnet\": data_collator = DataCollatorForPermutationLanguageModeling( tokenizer=tokenizer, plm_probability=data_args.plm_probability, max_span_length=data_args.max_span_length, ) else: data_collator", "4, 5]), \"max_steps\": -1, # We use num_epochs instead. \"wandb\":", "metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0, 0.3).func(None), \"learning_rate\": lambda:", "per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, # weight_decay=config[\"weight_decay\"], # logging_dir=\"./logs\", # ) #", "logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for", "not supported, but you can do it from another script,", "AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, HfArgumentParser, # LineByLineTextDatasetLabels, LineByLineTextDataset, PreTrainedTokenizer,", "model_name_or_path, # num_labels=num_labels, # finetuning_task=task_name, # ) # model =", "any(nd in n for nd in no_decay)], \"weight_decay\": 0.0, },", "training from scratch, pass a model type from the list:", "import PopulationBasedTraining from ray.tune import CLIReporter # if is_wandb_available(): #", "masked-language modeling loss instead of language modeling.\"} ) mlm_probability: float", "subdirectory used for Huggingface. subdirs = [ os.path.join(tune_checkpoint_dir, name) for", "be the max possible for the model else: data_args.block_size =", "RoBERTa are fine-tuned using a masked language modeling (MLM) loss.", "language modeling (MLM) loss. XLNet is fine-tuned using a permutation", "= AutoModelForSequenceClassification.from_pretrained( # model_name_or_path, # config=config, # ) # #", ") line_by_line: bool = field( default=False, metadata={\"help\": \"Whether distinct lines", "\"help\": \"Ratio of length of a span of masked tokens", "return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else:", "a text file (GPT, GPT-2, CTRL, BERT, RoBERTa, XLNet). GPT,", "downloaded from s3\"} ) force_pad_token: bool = field( default=False, metadata={", "0: return model_name # Get subdirectory used for Huggingface. subdirs", "and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA", "training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info(\"Training/evaluation parameters %s\",", "data_args, training_args = parser.parse_args_into_dataclasses() config = { # These 3", "Either supply a file to --eval_data_file \" \"or remove the", "= {'bos_token': '<bos>', 'eos_token': '<eos>', 'pad_token': '<pad>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)", "masked tokens to surrounding context length for permutation language modeling.\"", "\"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\" }, metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\",", "model_name_or_path, # config=config, # ) # # # Use our", "# evaluate_during_training=True, # # Run eval after every epoch. #", "\"task_name\": \"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\": 32, \"per_gpu_train_batch_size\": tune.choice([16, 32, 64]),", "going to input our model for training and eval. \"\"\"", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "by passing the --help flag to this script. # We", "output = self.prediction_loop( eval_dataloader, description=\"Evaluation\") self.log(output.metrics) self.save_state() tune.report(**output.metrics) return output.metrics", "data_args, training_args = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval:", "is None: if model_args.force_pad_token: # See PR 3388. Some tokenizers", "and RoBERTa are fine-tuned using a masked language modeling (MLM)", "# import wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger = logging.getLogger(__name__) MODEL_CONFIG_CLASSES", "= list(MODEL_WITH_LM_HEAD_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass", "default=None, metadata={\"help\": \"The input training data file (a text file).\"}", "# tune_trainer = TuneTransformerTrainer( # model=model, # args=training_args, # train_dataset=train_dataset,", "is None or len(tune_checkpoint_dir) == 0: return model_name # Get", "if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( \"Process", "len(subdirs) == 1, subdirs return subdirs[0] # def train_transformer(config, checkpoint_dir=None):", "in self.model.named_parameters() if any(nd in n for nd in no_decay)],", "# training_args = TrainingArguments( # output_dir=tune.get_trial_dir(), # learning_rate=config[\"learning_rate\"], # do_train=True,", "TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() config = { #", "metric_columns=[ \"eval_acc\", \"eval_loss\", \"epoch\", \"training_iteration\" ]) analysis = tune.run( train_transformer,", "block_size=args.block_size) # return LineByLineTextDatasetLabels(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer,", "= get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return self.current_optimizer, self.current_scheduler def", "\"__main__\": parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args =", "\"help\": \"The model checkpoint for weights initialization. Leave None if", "\"Default to the model max input length for single sentence", "= field( default=0.15, metadata={\"help\": \"Ratio of tokens to mask for", "Version 2.0 (the \"License\"); # you may not use this", "which causes errors at the encoding step in the collate_fn.", "prediction_loss_only=True, # compute_metrics=compute_metrics, ) if training_args.do_train: model_path = ( model_args.model_name_or_path", "config name or path if not the same as model_name\"}", "= AutoConfig.from_pretrained( # model_name_or_path, # num_labels=num_labels, # finetuning_task=task_name, # )", "checkpoint_dir # This is the directory name that Huggingface requires.", "instead of language modeling.\"} ) mlm_probability: float = field( default=0.15,", "for training and eval. \"\"\" train_data_file: Optional[str] = field( default=None,", "data_args.block_size = tokenizer.max_len # Our input block size will be", "if not the same as model_name\"} ) tokenizer_name: Optional[str] =", "// config[\"per_gpu_train_batch_size\"]) + # 1, # # We explicitly set", ") else: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args", "modeling).\" ) if data_args.block_size <= 0: data_args.block_size = tokenizer.max_len #", "ValueError( \"Cannot do evaluation without an evaluation data file. Either", "\"epoch\", \"training_iteration\" ]) analysis = tune.run( train_transformer, resources_per_trial={ \"cpu\": 1,", "= checkpoint_dir # This is the directory name that Huggingface", "elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: raise ValueError( \"You", "tune.run( train_transformer, resources_per_trial={ \"cpu\": 1, \"gpu\": 1 }, config=config, num_samples=3,", "by applicable law or agreed to in writing, software #", "# model_name_or_path, # num_labels=num_labels, # finetuning_task=task_name, # ) # model", "model & vocab. if model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir) elif", "# This is the directory name that Huggingface requires. output_dir", "distinct sequences.\"}, ) mlm: bool = field( default=False, metadata={\"help\": \"Train", "if training_args.do_eval else None ) if config_in.model_type == \"xlnet\": data_collator", "file_path=file_path, block_size=args.block_size) else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir,", "download model & vocab. if model_args.config_name: config_in = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)", "in block of this size for training.\" \"Default to the", "= AutoTokenizer.from_pretrained(model_args.tokenizer_name, cache_dir=model_args.cache_dir) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else:", "\"weight_decay\": self.args.weight_decay, }, { \"params\": [p for n, p in", "model_args.model_name_or_path: config_in = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir) else: config_in = CONFIG_MAPPING[model_args.model_type]() logger.warning(\"You", "transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling,", "model = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path, from_tf=bool(\".ckpt\" in model_args.model_name_or_path), config=config_in, cache_dir=model_args.cache_dir, )", ") logger.warning( \"Process rank: %s, device: %s, n_gpu: %s, distributed", "methods guarantee that only one local process can concurrently #", "the collate_fn. # We give here the option to force", "is not supported, but you can do it from another", "0, and do checkpointing in evaluate instead save_steps=0, num_train_epochs=config[\"num_epochs\"], max_steps=config[\"max_steps\"],", "# Set seed set_seed(training_args.seed) # Load pretrained model and tokenizer", "to what data we are going to input our model", "# config=config, # ) # # # Use our modified", "context length for permutation language modeling.\" }, ) max_span_length: int", "Huggingface. subdirs = [ os.path.join(tune_checkpoint_dir, name) for name in os.listdir(tune_checkpoint_dir)", "input block size will be the max possible for the", "local process can concurrently # download model & vocab. if", "in MODEL_CONFIG_CLASSES) @dataclass class ModelArguments: \"\"\" Arguments pertaining to which", "checkpointing in evaluate instead # save_steps=0, # num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"],", "= glue_tasks_num_labels[config[\"task_name\"]] # # config = AutoConfig.from_pretrained( # model_name_or_path, #", "num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) return self.current_optimizer, self.current_scheduler def evaluate(self, eval_dataset= None):", "applicable law or agreed to in writing, software # distributed", "sets of args, for a cleaner separation of concerns. #", "}, ) debiasing_head: Optional[str] = field( default=None, metadata={\"help\": \"The type", "None or len(tune_checkpoint_dir) == 0: return model_name # Get subdirectory", "evaluate(self, eval_dataset= None): eval_dataloader = self.get_eval_dataloader(eval_dataset) output = self.prediction_loop( eval_dataloader,", "training: # The .from_pretrained methods guarantee that only one local", "output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True, # Run eval after every", "cleaner separation of concerns. # parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))", "under the License. \"\"\" Fine-tuning the library models for language", "# if is_wandb_available(): # import wandb ray.shutdown() ray.init(log_to_driver=True, ignore_reinit_error=True) logger", "eval_data_file: Optional[str] = field( default=None, metadata={\"help\": \"An optional input evaluation", "text in the dataset are to be handled as distinct", "metadata={\"help\": \"If training from scratch, pass a model type from", "train_transformer(config, checkpoint_dir=None): # See all possible arguments in src/transformers/training_args.py #", "\"distilbert\", \"camembert\"] and not data_args.mlm: raise ValueError( \"BERT and RoBERTa-like", "# You may obtain a copy of the License at", "the list: \" + \", \".join(MODEL_TYPES)}, ) config_name: Optional[str] =", "in the encoding step. Set the --force_pad_token flag to fix", "or path if not the same as model_name\"} ) cache_dir:", "scheduler=scheduler, keep_checkpoints_num=3, checkpoint_score_attr=\"training_iteration\", progress_reporter=reporter, local_dir=\"./ray_results/\", name=\"tune_trans\") best_config = analysis.get_best_config(metric=\"eval_loss\", mode=\"min\")", "\"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\", \"num_epochs\": \"num_epochs\" }, metric_columns=[ \"eval_acc\",", "import torch from transformers.optimization import AdamW, get_linear_schedule_with_warmup from transformers import", "= ( get_dataset(data_args, tokenizer=tokenizer, evaluate=True, cache_dir=model_args.cache_dir) if training_args.do_eval else None", "tune.choice([16, 32, 64]), \"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\":", "ray.tune.schedulers import PopulationBasedTraining from ray.tune import CLIReporter # if is_wandb_available():", "field( default=None, metadata={\"help\": \"The type of de-biasing head to be", "does not already have one.\" }, ) debiasing_head: Optional[str] =", "passing the --help flag to this script. # We now", "not already have one.\" }, ) debiasing_head: Optional[str] = field(", "same as model_name\"} ) tokenizer_name: Optional[str] = field( default=None, metadata={\"help\":", "to be handled as distinct sequences.\"}, ) mlm: bool =", "that Huggingface requires. output_dir = os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer,", "config[\"per_gpu_train_batch_size\"]) + 1, # We explicitly set save to 0,", "field( default=False, metadata={ \"help\": \"Whether to force the addition of", "\"Overwrite the cached training and evaluation sets\"} ) def get_dataset(", "output_dir = os.path.join( self.args.output_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.global_step}\") self.save_model(output_dir) self.current_optimizer, self.current_scheduler = self.create_optimizer_and_scheduler(360)", "datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,", "args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics, ) if training_args.do_train:", "feeding to the model.x tokenizer.add_special_tokens({\"pad_token\": \"<pad>\"}) else: logger.warning( \"Attempting to", "raise ValueError( \"You are instantiating a new tokenizer from scratch.", "training_args.do_train: model_path = ( model_args.model_name_or_path if model_args.model_name_or_path is not None", ") training_args = TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True, do_eval=True, evaluate_during_training=True, #", "defined earlier \"model_name\": model_args.model_name_or_path, \"task_name\": \"CLM\", \"data_dir\": \"\", \"per_gpu_val_batch_size\": 32,", "tokenizer=tokenizer, mlm=data_args.mlm, mlm_probability=data_args.mlm_probability ) training_args = TrainingArguments( output_dir=tune.get_trial_dir(), learning_rate=config[\"learning_rate\"], do_train=True,", "( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ):", "new model from scratch\") model = AutoModelWithLMHead.from_config(config_in) special_tokens_dict = {'bos_token':", ") class TuneTransformerTrainer(Trainer): def create_optimizer_and_scheduler(self, num_training_steps: int): if self.optimizer is", "train_dataset=train_dataset, eval_dataset=eval_dataset, prediction_loss_only=True, # compute_metrics=compute_metrics, ) if training_args.do_train: model_path =", "\"License\"); # you may not use this file except in", "ray.tune import CLIReporter # if is_wandb_available(): # import wandb ray.shutdown()", "args.eval_data_file if evaluate else args.train_data_file if args.line_by_line: return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path,", "num_train_epochs=config[\"num_epochs\"], # max_steps=config[\"max_steps\"], # per_device_train_batch_size=config[\"per_gpu_train_batch_size\"], # per_device_eval_batch_size=config[\"per_gpu_val_batch_size\"], # warmup_steps=0, #", "conf in MODEL_CONFIG_CLASSES) @dataclass class ModelArguments: \"\"\" Arguments pertaining to", "datasets train_dataset = ( get_dataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else", "int): if self.optimizer is None: no_decay = [\"bias\", \"LayerNorm.weight\"] optimizer_grouped_parameters", "model_name\"} ) cache_dir: Optional[str] = field( default=None, metadata={\"help\": \"Where do", "reporter = CLIReporter( parameter_columns={ \"weight_decay\": \"w_decay\", \"learning_rate\": \"lr\", \"per_gpu_train_batch_size\": \"train_bs/gpu\",", "\"reinit\": True, \"allow_val_change\": True } } logger.info(config) scheduler = PopulationBasedTraining(", "else: return TextDataset( tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, overwrite_cache=args.overwrite_cache, cache_dir=cache_dir, ) class", "return self.current_optimizer, self.current_scheduler def evaluate(self, eval_dataset= None): eval_dataloader = self.get_eval_dataloader(eval_dataset)", "BERT and RoBERTa are fine-tuned using a masked language modeling", "This may result in errors in the encoding step. Set", "do_eval=True, # evaluate_during_training=True, # # Run eval after every epoch.", "= PopulationBasedTraining( time_attr=\"training_iteration\", metric=\"eval_loss\", mode=\"min\", perturbation_interval=2, hyperparam_mutations={ \"weight_decay\": lambda: tune.uniform(0.0,", "input our model for training and eval. \"\"\" train_data_file: Optional[str]", "%H:%M:%S\", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, )", "\"learning_rate\": tune.uniform(1e-5, 5e-5), \"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2, 3, 4,", "%(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y %H:%M:%S\", level=logging.INFO if training_args.local_rank", "\"weight_decay\": tune.uniform(0.0, 0.3), \"num_epochs\": tune.choice([2, 3, 4, 5]), \"max_steps\": -1,", "eval_steps=(len(train_dataset) // config[\"per_gpu_train_batch_size\"]) + # 1, # # We explicitly", "training: %s, 16-bits training: %s\", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank !=", "--force_pad_token flag to fix this.\" ) model_name_or_path = recover_checkpoint(checkpoint_dir, config[\"model_name\"])", "result in errors in the encoding step. Set the --force_pad_token", "0.3), \"num_epochs\": tune.choice([2, 3, 4, 5]), \"max_steps\": -1, # We", ") config_name: Optional[str] = field( default=None, metadata={\"help\": \"Pretrained config name", "model_args.force_pad_token: # See PR 3388. Some tokenizers don't had pad", "float = field( default=1 / 6, metadata={ \"help\": \"Ratio of", "of text in the dataset are to be handled as", "}, { \"params\": [p for n, p in self.model.named_parameters() if", "AdamW, get_linear_schedule_with_warmup from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead,", "logging logging.basicConfig( format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", datefmt=\"%m/%d/%Y" ]
[ "path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH request # sock.sendall(bytearray(b'\\x01')) #", "OK or \\xFF ERROR if resp != b'\\x00': print(\"Error byte", "0) + (8 if ignoreEmptyDirs else 0))]) if __name__ ==", "b'\\x00': print(\"Error byte received, errno is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) #", "= encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH request # sock.sendall(bytearray(b'\\x01')) # choose", "resp = sock.recv(1) # response first byte: \\x00 OK or", "# choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts byte (unused", "algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts byte (unused for regular files)", "first byte: \\x00 OK or \\xFF ERROR if resp !=", "= get_connected_local_socket() path = encodeString('/dev/shm/exampleDir') # path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A'))", "# sock.sendall(bytearray(b'\\x01')) # choose MD5 algorithm sock.sendall(bytearray(b'\\x06')) # choose SHA3-224", "(4 if ignoreUnixHiddenFiles else 0) + (8 if ignoreEmptyDirs else", "withNames else 0) + (2 if ignoreThumbsFiles else 0) +", "net_common import * import struct import sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True,", "import struct import sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return", "else 0) + (4 if ignoreUnixHiddenFiles else 0) + (8", "size print(toHex(sock.recv(28))) # 224 bit (28 byte) sha3-224 digest size", "struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16))) # 128 bit (16 byte)", "ignoreUnixHiddenFiles else 0) + (8 if ignoreEmptyDirs else 0))]) if", "ignoreEmptyDirs=True): return bytearray([((1 if withNames else 0) + (2 if", "# len of path as unsigned short sock.sendall(path) resp =", "return bytearray([((1 if withNames else 0) + (2 if ignoreThumbsFiles", "received, errno is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16))) # 128", "if resp != b'\\x00': print(\"Error byte received, errno is:\", struct.unpack(\"@i\",", "len of path as unsigned short sock.sendall(path) resp = sock.recv(1)", "short sock.sendall(path) resp = sock.recv(1) # response first byte: \\x00", "else 0) + (2 if ignoreThumbsFiles else 0) + (4", "path = encodeString('/dev/shm/exampleDir') # path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH", "+ (4 if ignoreUnixHiddenFiles else 0) + (8 if ignoreEmptyDirs", "ERROR if resp != b'\\x00': print(\"Error byte received, errno is:\",", "if ignoreUnixHiddenFiles else 0) + (8 if ignoreEmptyDirs else 0))])", "if withNames else 0) + (2 if ignoreThumbsFiles else 0)", "* import struct import sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True):", "== \"__main__\": sock = get_connected_local_socket() path = encodeString('/dev/shm/exampleDir') # path", "response first byte: \\x00 OK or \\xFF ERROR if resp", "sock.sendall(path) resp = sock.recv(1) # response first byte: \\x00 OK", "128 bit (16 byte) md5 digest size print(toHex(sock.recv(28))) # 224", "bytearray([((1 if withNames else 0) + (2 if ignoreThumbsFiles else", "if ignoreThumbsFiles else 0) + (4 if ignoreUnixHiddenFiles else 0)", "if ignoreEmptyDirs else 0))]) if __name__ == \"__main__\": sock =", "sock.recv(1) # response first byte: \\x00 OK or \\xFF ERROR", "resp != b'\\x00': print(\"Error byte received, errno is:\", struct.unpack(\"@i\", sock.recv(4))[0])", "dirHashOpts byte (unused for regular files) sock.sendall(struct.pack(\"@H\", len(path))) # len", "of path as unsigned short sock.sendall(path) resp = sock.recv(1) #", "digest size print(toHex(sock.recv(28))) # 224 bit (28 byte) sha3-224 digest", "sock.sendall(bytearray(b'\\x01')) # choose MD5 algorithm sock.sendall(bytearray(b'\\x06')) # choose SHA3-224 algorithm", "0) + (4 if ignoreUnixHiddenFiles else 0) + (8 if", "(unused for regular files) sock.sendall(struct.pack(\"@H\", len(path))) # len of path", "ignoreThumbsFiles else 0) + (4 if ignoreUnixHiddenFiles else 0) +", "print(toHex(sock.recv(28))) # 224 bit (28 byte) sha3-224 digest size sock.close()", "import sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1 if", "\\x00 OK or \\xFF ERROR if resp != b'\\x00': print(\"Error", "# print(toHex(sock.recv(16))) # 128 bit (16 byte) md5 digest size", "(16 byte) md5 digest size print(toHex(sock.recv(28))) # 224 bit (28", "ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1 if withNames else 0) +", "print(\"Error byte received, errno is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16)))", "ignoreEmptyDirs else 0))]) if __name__ == \"__main__\": sock = get_connected_local_socket()", "(8 if ignoreEmptyDirs else 0))]) if __name__ == \"__main__\": sock", "HASH request # sock.sendall(bytearray(b'\\x01')) # choose MD5 algorithm sock.sendall(bytearray(b'\\x06')) #", "+ (2 if ignoreThumbsFiles else 0) + (4 if ignoreUnixHiddenFiles", "files) sock.sendall(struct.pack(\"@H\", len(path))) # len of path as unsigned short", "request # sock.sendall(bytearray(b'\\x01')) # choose MD5 algorithm sock.sendall(bytearray(b'\\x06')) # choose", "def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1 if withNames else", "get_connected_local_socket() path = encodeString('/dev/shm/exampleDir') # path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) #", "!= b'\\x00': print(\"Error byte received, errno is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0)", "byte received, errno is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16))) #", "# send dirHashOpts byte (unused for regular files) sock.sendall(struct.pack(\"@H\", len(path)))", "0))]) if __name__ == \"__main__\": sock = get_connected_local_socket() path =", "as unsigned short sock.sendall(path) resp = sock.recv(1) # response first", "or \\xFF ERROR if resp != b'\\x00': print(\"Error byte received,", "else 0) + (8 if ignoreEmptyDirs else 0))]) if __name__", "\\xFF ERROR if resp != b'\\x00': print(\"Error byte received, errno", "sock.sendall(bytearray(b'\\x06')) # choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts byte", "md5 digest size print(toHex(sock.recv(28))) # 224 bit (28 byte) sha3-224", "struct import sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1", "# choose MD5 algorithm sock.sendall(bytearray(b'\\x06')) # choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False))", "byte (unused for regular files) sock.sendall(struct.pack(\"@H\", len(path))) # len of", "0) + (2 if ignoreThumbsFiles else 0) + (4 if", "choose MD5 algorithm sock.sendall(bytearray(b'\\x06')) # choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) #", "import * import struct import sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True,", "errno is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16))) # 128 bit", "send dirHashOpts byte (unused for regular files) sock.sendall(struct.pack(\"@H\", len(path))) #", "(2 if ignoreThumbsFiles else 0) + (4 if ignoreUnixHiddenFiles else", "byte: \\x00 OK or \\xFF ERROR if resp != b'\\x00':", "algorithm sock.sendall(bytearray(b'\\x06')) # choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts", "unsigned short sock.sendall(path) resp = sock.recv(1) # response first byte:", "\"__main__\": sock = get_connected_local_socket() path = encodeString('/dev/shm/exampleDir') # path =", "sock.sendall(bytearray(b'\\x0A')) # HASH request # sock.sendall(bytearray(b'\\x01')) # choose MD5 algorithm", "encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH request # sock.sendall(bytearray(b'\\x01')) # choose MD5", "encodeString('/dev/shm/exampleDir') # path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH request #", "= encodeString('/dev/shm/exampleDir') # path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH request", "print(toHex(sock.recv(16))) # 128 bit (16 byte) md5 digest size print(toHex(sock.recv(28)))", "for regular files) sock.sendall(struct.pack(\"@H\", len(path))) # len of path as", "# response first byte: \\x00 OK or \\xFF ERROR if", "sys.exit(0) # print(toHex(sock.recv(16))) # 128 bit (16 byte) md5 digest", "# 128 bit (16 byte) md5 digest size print(toHex(sock.recv(28))) #", "sock.sendall(struct.pack(\"@H\", len(path))) # len of path as unsigned short sock.sendall(path)", "path as unsigned short sock.sendall(path) resp = sock.recv(1) # response", "__name__ == \"__main__\": sock = get_connected_local_socket() path = encodeString('/dev/shm/exampleDir') #", "from net_common import * import struct import sys def getDirHashOpts(withNames=False,", "getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1 if withNames else 0)", "sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16))) # 128 bit (16 byte) md5", "if __name__ == \"__main__\": sock = get_connected_local_socket() path = encodeString('/dev/shm/exampleDir')", "sock = get_connected_local_socket() path = encodeString('/dev/shm/exampleDir') # path = encodeString('/dev/null')", "ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1 if withNames else 0) + (2", "regular files) sock.sendall(struct.pack(\"@H\", len(path))) # len of path as unsigned", "byte) md5 digest size print(toHex(sock.recv(28))) # 224 bit (28 byte)", "# HASH request # sock.sendall(bytearray(b'\\x01')) # choose MD5 algorithm sock.sendall(bytearray(b'\\x06'))", "else 0))]) if __name__ == \"__main__\": sock = get_connected_local_socket() path", "SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts byte (unused for regular", "choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts byte (unused for", "is:\", struct.unpack(\"@i\", sock.recv(4))[0]) sys.exit(0) # print(toHex(sock.recv(16))) # 128 bit (16", "sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send dirHashOpts byte (unused for regular files) sock.sendall(struct.pack(\"@H\",", "bit (16 byte) md5 digest size print(toHex(sock.recv(28))) # 224 bit", "# path = encodeString('/dev/null') sock.sendall(bytearray(b'\\x0A')) # HASH request # sock.sendall(bytearray(b'\\x01'))", "MD5 algorithm sock.sendall(bytearray(b'\\x06')) # choose SHA3-224 algorithm sock.sendall(getDirHashOpts(withNames=True,ignoreUnixHiddenFiles=False)) # send", "len(path))) # len of path as unsigned short sock.sendall(path) resp", "+ (8 if ignoreEmptyDirs else 0))]) if __name__ == \"__main__\":", "sys def getDirHashOpts(withNames=False, ignoreThumbsFiles=True, ignoreUnixHiddenFiles=True, ignoreEmptyDirs=True): return bytearray([((1 if withNames", "= sock.recv(1) # response first byte: \\x00 OK or \\xFF" ]
[ "name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for website (used for tracking)', max_length=255),", "-*- # Generated by Django 1.11.13 on 2018-09-11 10:05 from", "config.s3 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "models class Migration(migrations.Migration): dependencies = [ ('investment_report', '0019_auto_20180820_1304'), ] operations", "10:05 from __future__ import unicode_literals import config.s3 from django.db import", "coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-09-11", "from __future__ import unicode_literals import config.s3 from django.db import migrations,", "migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for website (used for", "import unicode_literals import config.s3 from django.db import migrations, models class", "-*- coding: utf-8 -*- # Generated by Django 1.11.13 on", "field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for website (used for tracking)', max_length=255), preserve_default=False,", "__future__ import unicode_literals import config.s3 from django.db import migrations, models", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('investment_report',", "= [ migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for website", "on 2018-09-11 10:05 from __future__ import unicode_literals import config.s3 from", "# -*- coding: utf-8 -*- # Generated by Django 1.11.13", "operations = [ migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('investment_report', '0019_auto_20180820_1304'),", "help_text='Custom link for website (used for tracking)', max_length=255), preserve_default=False, )", "1.11.13 on 2018-09-11 10:05 from __future__ import unicode_literals import config.s3", "Generated by Django 1.11.13 on 2018-09-11 10:05 from __future__ import", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "'0019_auto_20180820_1304'), ] operations = [ migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom", "utf-8 -*- # Generated by Django 1.11.13 on 2018-09-11 10:05", "dependencies = [ ('investment_report', '0019_auto_20180820_1304'), ] operations = [ migrations.AddField(", "[ migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for website (used", "] operations = [ migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link", "Migration(migrations.Migration): dependencies = [ ('investment_report', '0019_auto_20180820_1304'), ] operations = [", "model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/', help_text='Custom link for website (used for tracking)',", "('investment_report', '0019_auto_20180820_1304'), ] operations = [ migrations.AddField( model_name='contact', name='website_href', field=models.URLField(default='https://invest.great.gov.uk/contact/',", "unicode_literals import config.s3 from django.db import migrations, models class Migration(migrations.Migration):", "<filename>investment_report/migrations/0020_auto_20180911_1005.py # -*- coding: utf-8 -*- # Generated by Django", "# Generated by Django 1.11.13 on 2018-09-11 10:05 from __future__", "import config.s3 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "migrations, models class Migration(migrations.Migration): dependencies = [ ('investment_report', '0019_auto_20180820_1304'), ]", "by Django 1.11.13 on 2018-09-11 10:05 from __future__ import unicode_literals", "link for website (used for tracking)', max_length=255), preserve_default=False, ) ]", "[ ('investment_report', '0019_auto_20180820_1304'), ] operations = [ migrations.AddField( model_name='contact', name='website_href',", "= [ ('investment_report', '0019_auto_20180820_1304'), ] operations = [ migrations.AddField( model_name='contact',", "class Migration(migrations.Migration): dependencies = [ ('investment_report', '0019_auto_20180820_1304'), ] operations =", "2018-09-11 10:05 from __future__ import unicode_literals import config.s3 from django.db", "Django 1.11.13 on 2018-09-11 10:05 from __future__ import unicode_literals import" ]
[ "of threads in thread pools is set to 1.\"\"\" import", "<gh_stars>100-1000 \"\"\"Validate that number of threads in thread pools is", "threadpoolctl # APIs that return previous number of threads: assert", "import blosc import threadpoolctl # APIs that return previous number", "that return previous number of threads: assert numexpr.set_num_threads(2) == 1", "return previous number of threads: assert numexpr.set_num_threads(2) == 1 assert", "of threads: assert numexpr.set_num_threads(2) == 1 assert blosc.set_nthreads(2) == 1", "is set to 1.\"\"\" import numexpr import blosc import threadpoolctl", "blosc.set_nthreads(2) == 1 for d in threadpoolctl.threadpool_info(): assert d[\"num_threads\"] ==", "set to 1.\"\"\" import numexpr import blosc import threadpoolctl #", "numexpr import blosc import threadpoolctl # APIs that return previous", "numexpr.set_num_threads(2) == 1 assert blosc.set_nthreads(2) == 1 for d in", "1.\"\"\" import numexpr import blosc import threadpoolctl # APIs that", "that number of threads in thread pools is set to", "assert numexpr.set_num_threads(2) == 1 assert blosc.set_nthreads(2) == 1 for d", "1 assert blosc.set_nthreads(2) == 1 for d in threadpoolctl.threadpool_info(): assert", "import threadpoolctl # APIs that return previous number of threads:", "== 1 for d in threadpoolctl.threadpool_info(): assert d[\"num_threads\"] == 1,", "threads: assert numexpr.set_num_threads(2) == 1 assert blosc.set_nthreads(2) == 1 for", "# APIs that return previous number of threads: assert numexpr.set_num_threads(2)", "APIs that return previous number of threads: assert numexpr.set_num_threads(2) ==", "number of threads in thread pools is set to 1.\"\"\"", "number of threads: assert numexpr.set_num_threads(2) == 1 assert blosc.set_nthreads(2) ==", "thread pools is set to 1.\"\"\" import numexpr import blosc", "assert blosc.set_nthreads(2) == 1 for d in threadpoolctl.threadpool_info(): assert d[\"num_threads\"]", "1 for d in threadpoolctl.threadpool_info(): assert d[\"num_threads\"] == 1, d", "in thread pools is set to 1.\"\"\" import numexpr import", "threads in thread pools is set to 1.\"\"\" import numexpr", "to 1.\"\"\" import numexpr import blosc import threadpoolctl # APIs", "pools is set to 1.\"\"\" import numexpr import blosc import", "\"\"\"Validate that number of threads in thread pools is set", "blosc import threadpoolctl # APIs that return previous number of", "previous number of threads: assert numexpr.set_num_threads(2) == 1 assert blosc.set_nthreads(2)", "== 1 assert blosc.set_nthreads(2) == 1 for d in threadpoolctl.threadpool_info():", "import numexpr import blosc import threadpoolctl # APIs that return" ]
[ "label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4 = fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\")", "StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p, tvf_q) = (TVecFields(), TVecFields())", "elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\")", "numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU =", "GHz') plt.show() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\",", "one for each polarization channel.)\"\"\" import os import argparse import", "to Stokes vector. This assumes dual-pol antenna receiving unpolarized unit", "help='Filename of polarization channel p') parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency in", "x = THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI) #x= THETA #y=PHI xyNames", "numpy import matplotlib.pyplot as plt from antpat.reps.sphgridfun.tvecfun import TVecFields from", "ax2.set_title('Q/I') ax3 = fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I')", "p') parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency in Hertz\") args = parser.parse_args()", "== \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of polarization channel", "channel.)\"\"\" import os import argparse import numpy import matplotlib.pyplot as", "argparse import numpy import matplotlib.pyplot as plt from antpat.reps.sphgridfun.tvecfun import", "ax2 = fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3", "StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return", "= Jones2Stokes(Jones) x = THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI) #x= THETA", "= fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3 =", "ax3 = fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4", "ax3.set_title('U/I') ax4 = fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I')", "pattern files. (Possibly based on one FF pattern files if", "TVecFields from antpat.radfarfield import RadFarField from antpat.dualpolelem import DualPolElem FEKOsuffix", "DualPolElem(ant_p, ant_q) THETA, PHI, Jones = dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU,", "import TVecFields from antpat.radfarfield import RadFarField from antpat.dualpolelem import DualPolElem", "q_chan_file, freq): (tvf_p, tvf_q) = (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p,", "This assumes dual-pol antenna receiving unpolarized unit valued radiation i.e.", "help='Filename of polarization channel p') parser.add_argument(\"q_chan_file\", help='Filename of polarization channel", "= (p_chan_name, q_chan_name) dualpolAnt = DualPolElem(ant_p, ant_q) THETA, PHI, Jones", "requests: one for each polarization channel.)\"\"\" import os import argparse", "y = THETA*numpy.sin(PHI) #x= THETA #y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)') fig", "args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented", "Hertz\") args = parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif", "ant_q) THETA, PHI, Jones = dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU, StokesV)", "StokesU, StokesV) = Jones2Stokes(Jones) x = THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI)", "= dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU, StokesV) = Jones2Stokes(Jones) x =", "label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj) @ ' +str(freq/1e9)+' GHz')", "= fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant", "tvf_q) = (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) = (RadFarField(tvf_p),", "TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name)", "tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name) =", "q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) = (p_chan_name, q_chan_name) dualpolAnt", "Jones matrix to Stokes vector. This assumes dual-pol antenna receiving", "incoming Stokes = (1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI =", "(dB)') ax2 = fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I')", "= plt.figure() ax1 = fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x,", "polarization channel.)\"\"\" import os import argparse import numpy import matplotlib.pyplot", "= numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU", "parser.add_argument(\"q_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency", "vector. This assumes dual-pol antenna receiving unpolarized unit valued radiation", "polarization channel p') parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency in Hertz\") args", "argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"q_chan_file\", help='Filename of", "THETA*numpy.sin(PHI) #x= THETA #y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)') fig = plt.figure()", "of polarization channel p') parser.add_argument(\"q_chan_file\", help='Filename of polarization channel p')", "RadFarField(tvf_q)) (p_chan_name, q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) = (p_chan_name,", "parser.add_argument(\"p_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"q_chan_file\", help='Filename of polarization", "import DualPolElem FEKOsuffix = 'ffe' GRASPsuffix = 'swe' NECsuffix =", "if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of", "Jones = dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU, StokesV) = Jones2Stokes(Jones) x", "implemented yet.\") else: print(\"Far-field pattern file type not known\") exit(1)", "= fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4 =", "from antpat.dualpolelem import DualPolElem FEKOsuffix = 'ffe' GRASPsuffix = 'swe'", "StokesV) = Jones2Stokes(Jones) x = THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI) #x=", "nargs='?', type=float, help=\"Frequency in Hertz\") args = parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix):", "(Possibly based on one FF pattern files if it has", "import os import argparse import numpy import matplotlib.pyplot as plt", "antpat.reps.sphgridfun.tvecfun import TVecFields from antpat.radfarfield import RadFarField from antpat.dualpolelem import", "q_chan_name) dualpolAnt = DualPolElem(ant_p, ant_q) THETA, PHI, Jones = dualpolAnt.getJonesPat(freq)", "(tvf_p, tvf_q) = (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) =", "(p_chan_name, q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) = (p_chan_name, q_chan_name)", "args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\") elif", "ant_q.name) = (p_chan_name, q_chan_name) dualpolAnt = DualPolElem(ant_p, ant_q) THETA, PHI,", "y, StokesI, label=\"I\") plt.colorbar() ax1.set_title('I (dB)') ax2 = fig.add_subplot(222) plt.pcolormesh(x,", "numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ, StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq):", "patterns based on two far-field pattern files. (Possibly based on", "= (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name)", "valued radiation i.e. incoming Stokes = (1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones,", "(ant_p.name, ant_q.name) = (p_chan_name, q_chan_name) dualpolAnt = DualPolElem(ant_p, ant_q) THETA,", "<gh_stars>1-10 #!/usr/bin/env python \"\"\"A simple viewer for Stokes patterns based", "one FF pattern files if it has two requests: one", "\"\"\"Convert Jones matrix to Stokes vector. This assumes dual-pol antenna", "PHI, Jones = dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU, StokesV) = Jones2Stokes(Jones)", "parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"q_chan_file\",", "' +str(freq/1e9)+' GHz') plt.show() if __name__ == \"__main__\": parser =", "parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency in Hertz\") args = parser.parse_args() if", "'swe' NECsuffix = 'out' def Jones2Stokes(Jones): \"\"\"Convert Jones matrix to", "= (1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ", "yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\") else: print(\"Far-field pattern file", "os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) = (p_chan_name, q_chan_name) dualpolAnt = DualPolElem(ant_p, ant_q)", "viewer for Stokes patterns based on two far-field pattern files.", "plt.colorbar() ax1.set_title('I (dB)') ax2 = fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\")", "args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\") else:", "ax4 = fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes", "type=float, help=\"Frequency in Hertz\") args = parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file,", "matplotlib.pyplot as plt from antpat.reps.sphgridfun.tvecfun import TVecFields from antpat.radfarfield import", "StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj) @ ' +str(freq/1e9)+'", "plt.show() if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename", "'out' def Jones2Stokes(Jones): \"\"\"Convert Jones matrix to Stokes vector. This", "import numpy import matplotlib.pyplot as plt from antpat.reps.sphgridfun.tvecfun import TVecFields", "if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\")", "StokesI, StokesQ, StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p, tvf_q)", "StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ, StokesU,", "if it has two requests: one for each polarization channel.)\"\"\"", "StokesQ, StokesU, StokesV) = Jones2Stokes(Jones) x = THETA*numpy.cos(PHI) y =", "#!/usr/bin/env python \"\"\"A simple viewer for Stokes patterns based on", "pattern files if it has two requests: one for each", "implemented yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\") else: print(\"Far-field pattern", "ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj) @ ' +str(freq/1e9)+' GHz') plt.show() if", "plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4 = fig.add_subplot(224) plt.pcolormesh(x,", "unit valued radiation i.e. incoming Stokes = (1,0,0,0).\"\"\" brightmat =", "of polarization channel p') parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency in Hertz\")", "channel p') parser.add_argument(\"q_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"freq\", nargs='?',", "import matplotlib.pyplot as plt from antpat.reps.sphgridfun.tvecfun import TVecFields from antpat.radfarfield", "print(\"Not implemented yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\") else: print(\"Far-field", "StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4 = fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI,", "from antpat.radfarfield import RadFarField from antpat.dualpolelem import DualPolElem FEKOsuffix =", "polarization channel p') parser.add_argument(\"q_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"freq\",", "\"\"\"A simple viewer for Stokes patterns based on two far-field", "simple viewer for Stokes patterns based on two far-field pattern", "tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name) = (os.path.basename(p_chan_file),", "plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\") elif args.p_chan_file.endswith(NECsuffix):", "numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ, StokesU, StokesV def", "on two far-field pattern files. (Possibly based on one FF", "args = parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix):", "RadFarField from antpat.dualpolelem import DualPolElem FEKOsuffix = 'ffe' GRASPsuffix =", "numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0])", "numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ,", "StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p, tvf_q) = (TVecFields(),", "fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y, StokesI, label=\"I\") plt.colorbar()", "ax1.set_title('I (dB)') ax2 = fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\") plt.colorbar()", "#plt.pcolormesh(x, y, StokesI, label=\"I\") plt.colorbar() ax1.set_title('I (dB)') ax2 = fig.add_subplot(222)", "__name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of polarization", "(azimuthal-equidistant proj) @ ' +str(freq/1e9)+' GHz') plt.show() if __name__ ==", "dual-pol antenna receiving unpolarized unit valued radiation i.e. incoming Stokes", "plt.colorbar() ax2.set_title('Q/I') ax3 = fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\") plt.colorbar()", "NECsuffix = 'out' def Jones2Stokes(Jones): \"\"\"Convert Jones matrix to Stokes", "= (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q))", "fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3 = fig.add_subplot(223)", "from antpat.reps.sphgridfun.tvecfun import TVecFields from antpat.radfarfield import RadFarField from antpat.dualpolelem", "y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y, StokesI, label=\"I\") plt.colorbar() ax1.set_title('I (dB)')", "channel p') parser.add_argument(\"freq\", nargs='?', type=float, help=\"Frequency in Hertz\") args =", "python \"\"\"A simple viewer for Stokes patterns based on two", "two far-field pattern files. (Possibly based on one FF pattern", "files. (Possibly based on one FF pattern files if it", "= ('theta*cos(phi)','theta*sin(phi)') fig = plt.figure() ax1 = fig.add_subplot(221) plt.pcolormesh(x, y,", "= numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV =", "label=\"I\") plt.colorbar() ax1.set_title('I (dB)') ax2 = fig.add_subplot(222) plt.pcolormesh(x, y, StokesQ/StokesI,", "p') parser.add_argument(\"q_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"freq\", nargs='?', type=float,", "= 'ffe' GRASPsuffix = 'swe' NECsuffix = 'out' def Jones2Stokes(Jones):", "receiving unpolarized unit valued radiation i.e. incoming Stokes = (1,0,0,0).\"\"\"", "= parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not", "(TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name,", "def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p, tvf_q) = (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file)", "THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI) #x= THETA #y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)')", "= 'out' def Jones2Stokes(Jones): \"\"\"Convert Jones matrix to Stokes vector.", "@ ' +str(freq/1e9)+' GHz') plt.show() if __name__ == \"__main__\": parser", "fig = plt.figure() ax1 = fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\")", "plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj) @", "GRASPsuffix = 'swe' NECsuffix = 'out' def Jones2Stokes(Jones): \"\"\"Convert Jones", "plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj) @ ' +str(freq/1e9)+' GHz') plt.show()", "each polarization channel.)\"\"\" import os import argparse import numpy import", "assumes dual-pol antenna receiving unpolarized unit valued radiation i.e. incoming", "label=\"I\") #plt.pcolormesh(x, y, StokesI, label=\"I\") plt.colorbar() ax1.set_title('I (dB)') ax2 =", "on one FF pattern files if it has two requests:", "elif args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\") else: print(\"Far-field pattern file type", "xyNames = ('theta*cos(phi)','theta*sin(phi)') fig = plt.figure() ax1 = fig.add_subplot(221) plt.pcolormesh(x,", "fig.suptitle('Stokes (azimuthal-equidistant proj) @ ' +str(freq/1e9)+' GHz') plt.show() if __name__", "dualpolAnt = DualPolElem(ant_p, ant_q) THETA, PHI, Jones = dualpolAnt.getJonesPat(freq) (StokesI,", "for each polarization channel.)\"\"\" import os import argparse import numpy", "= (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) = (p_chan_name, q_chan_name) dualpolAnt =", "in Hertz\") args = parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq)", "FEKOsuffix = 'ffe' GRASPsuffix = 'swe' NECsuffix = 'out' def", "label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3 = fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\")", "ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name,", "print(\"Not implemented yet.\") else: print(\"Far-field pattern file type not known\")", "plt.figure() ax1 = fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y,", "= DualPolElem(ant_p, ant_q) THETA, PHI, Jones = dualpolAnt.getJonesPat(freq) (StokesI, StokesQ,", "args.p_chan_file.endswith(NECsuffix): print(\"Not implemented yet.\") else: print(\"Far-field pattern file type not", "Stokes = (1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1])", "= numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI,", "brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1])", "#y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)') fig = plt.figure() ax1 = fig.add_subplot(221)", "two requests: one for each polarization channel.)\"\"\" import os import", "proj) @ ' +str(freq/1e9)+' GHz') plt.show() if __name__ == \"__main__\":", "matrix to Stokes vector. This assumes dual-pol antenna receiving unpolarized", "= THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI) #x= THETA #y=PHI xyNames =", "antpat.dualpolelem import DualPolElem FEKOsuffix = 'ffe' GRASPsuffix = 'swe' NECsuffix", "(RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) =", "far-field pattern files. (Possibly based on one FF pattern files", "StokesI, label=\"I\") plt.colorbar() ax1.set_title('I (dB)') ax2 = fig.add_subplot(222) plt.pcolormesh(x, y,", "fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj)", "DualPolElem FEKOsuffix = 'ffe' GRASPsuffix = 'swe' NECsuffix = 'out'", "os import argparse import numpy import matplotlib.pyplot as plt from", "plt.colorbar() ax3.set_title('U/I') ax4 = fig.add_subplot(224) plt.pcolormesh(x, y, StokesV/StokesI, label=\"V\") plt.colorbar()", "y, StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3 = fig.add_subplot(223) plt.pcolormesh(x, y,", "= numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ, StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file,", "antenna receiving unpolarized unit valued radiation i.e. incoming Stokes =", "return StokesI, StokesQ, StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p,", "Jones2Stokes(Jones) x = THETA*numpy.cos(PHI) y = THETA*numpy.sin(PHI) #x= THETA #y=PHI", "('theta*cos(phi)','theta*sin(phi)') fig = plt.figure() ax1 = fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI),", "files if it has two requests: one for each polarization", "ax1 = fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y, StokesI,", "plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y, StokesI, label=\"I\") plt.colorbar() ax1.set_title('I", "= argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of polarization channel p') parser.add_argument(\"q_chan_file\", help='Filename", "Stokes vector. This assumes dual-pol antenna receiving unpolarized unit valued", "antpat.radfarfield import RadFarField from antpat.dualpolelem import DualPolElem FEKOsuffix = 'ffe'", "def Jones2Stokes(Jones): \"\"\"Convert Jones matrix to Stokes vector. This assumes", "plt.pcolormesh(x, y, StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3 = fig.add_subplot(223) plt.pcolormesh(x,", "+str(freq/1e9)+' GHz') plt.show() if __name__ == \"__main__\": parser = argparse.ArgumentParser()", "= fig.add_subplot(221) plt.pcolormesh(x, y, 10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y, StokesI, label=\"I\")", "dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU, StokesV) = Jones2Stokes(Jones) x = THETA*numpy.cos(PHI)", "StokesQ, StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p, tvf_q) =", "import argparse import numpy import matplotlib.pyplot as plt from antpat.reps.sphgridfun.tvecfun", "based on two far-field pattern files. (Possibly based on one", "'ffe' GRASPsuffix = 'swe' NECsuffix = 'out' def Jones2Stokes(Jones): \"\"\"Convert", "based on one FF pattern files if it has two", "fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4 = fig.add_subplot(224)", "= THETA*numpy.sin(PHI) #x= THETA #y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)') fig =", "numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0])", "for Stokes patterns based on two far-field pattern files. (Possibly", "StokesQ/StokesI, label=\"Q\") plt.colorbar() ax2.set_title('Q/I') ax3 = fig.add_subplot(223) plt.pcolormesh(x, y, StokesU/StokesI,", "Stokes patterns based on two far-field pattern files. (Possibly based", "(1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ =", "plt from antpat.reps.sphgridfun.tvecfun import TVecFields from antpat.radfarfield import RadFarField from", "(ant_p, ant_q) = (RadFarField(tvf_p), RadFarField(tvf_q)) (p_chan_name, q_chan_name) = (os.path.basename(p_chan_file), os.path.basename(q_chan_file))", "args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented yet.\") elif args.p_chan_file.endswith(NECsuffix): print(\"Not", "10*numpy.log10(StokesI), label=\"I\") #plt.pcolormesh(x, y, StokesI, label=\"I\") plt.colorbar() ax1.set_title('I (dB)') ax2", "radiation i.e. incoming Stokes = (1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2))", "help=\"Frequency in Hertz\") args = parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file,", "import RadFarField from antpat.dualpolelem import DualPolElem FEKOsuffix = 'ffe' GRASPsuffix", "freq): (tvf_p, tvf_q) = (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file) (ant_p, ant_q)", "(StokesI, StokesQ, StokesU, StokesV) = Jones2Stokes(Jones) x = THETA*numpy.cos(PHI) y", "(os.path.basename(p_chan_file), os.path.basename(q_chan_file)) (ant_p.name, ant_q.name) = (p_chan_name, q_chan_name) dualpolAnt = DualPolElem(ant_p,", "y, StokesU/StokesI, label=\"U\") plt.colorbar() ax3.set_title('U/I') ax4 = fig.add_subplot(224) plt.pcolormesh(x, y,", "= 'swe' NECsuffix = 'out' def Jones2Stokes(Jones): \"\"\"Convert Jones matrix", "unpolarized unit valued radiation i.e. incoming Stokes = (1,0,0,0).\"\"\" brightmat", "it has two requests: one for each polarization channel.)\"\"\" import", "has two requests: one for each polarization channel.)\"\"\" import os", "FF pattern files if it has two requests: one for", "#x= THETA #y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)') fig = plt.figure() ax1", "\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"p_chan_file\", help='Filename of polarization channel p')", "THETA #y=PHI xyNames = ('theta*cos(phi)','theta*sin(phi)') fig = plt.figure() ax1 =", "plotStokes_fromFEKOfiles(p_chan_file, q_chan_file, freq): (tvf_p, tvf_q) = (TVecFields(), TVecFields()) tvf_p.load_ffe(p_chan_file) tvf_q.load_ffe(q_chan_file)", "THETA, PHI, Jones = dualpolAnt.getJonesPat(freq) (StokesI, StokesQ, StokesU, StokesV) =", "y, StokesV/StokesI, label=\"V\") plt.colorbar() ax4.set_title('V/I') fig.suptitle('Stokes (azimuthal-equidistant proj) @ '", "= numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ, StokesU, StokesV", "parser.parse_args() if args.p_chan_file.endswith(FEKOsuffix): plotStokes_fromFEKOfiles(args.p_chan_file, args.q_chan_file, args.freq) elif args.p_chan_file.endswith(GRASPsuffix): print(\"Not implemented", "as plt from antpat.reps.sphgridfun.tvecfun import TVecFields from antpat.radfarfield import RadFarField", "StokesI = numpy.real(brightmat[...,0,0]+brightmat[...,1,1]) StokesQ = numpy.real(brightmat[...,0,0]-brightmat[...,1,1]) StokesU = numpy.real(brightmat[...,0,1]+brightmat[...,1,0]) StokesV", "(p_chan_name, q_chan_name) dualpolAnt = DualPolElem(ant_p, ant_q) THETA, PHI, Jones =", "i.e. incoming Stokes = (1,0,0,0).\"\"\" brightmat = numpy.matmul(Jones, numpy.swapaxes(numpy.conjugate(Jones),-1,-2)) StokesI", "StokesV = numpy.imag(brightmat[...,0,1]-brightmat[...,1,0]) return StokesI, StokesQ, StokesU, StokesV def plotStokes_fromFEKOfiles(p_chan_file,", "Jones2Stokes(Jones): \"\"\"Convert Jones matrix to Stokes vector. This assumes dual-pol" ]
[ "current < total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer, lr):", "= cur_time tot_time = cur_time - begin_time L = []", "sys import time import math import torch import torch.nn as", "sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer, lr): for group in", "begin_time L = [] if msg: L.append(' | ' +", "i in range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time = time.time() step_time =", "rate - clip_gradient : clip gradient ''' import os import", "the center of the bar. for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b')", "total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer, lr): for group", "Loss: 1.961 | Acc: 22.000% (537/2432) def progress_bar(current, total, msg=None):", "int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write(' [')", "time import math import torch import torch.nn as nn import", "progress_bar(current, total, msg=None): global last_time, begin_time if current == 0:", "time.time() # Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len", "1 sys.stdout.write(' [') for i in range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for", "sys.stdout.write(']') cur_time = time.time() step_time = cur_time - last_time last_time", "cur_len) - 1 sys.stdout.write(' [') for i in range(cur_len): sys.stdout.write('=')", "#获取控制台行、列数 if sys.platform == 'win32': term_width = 80 else: print('###',", "') # Go back to the center of the bar.", "int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write(' [') for i in", "sys.stdout.write(msg) for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') # Go back", "if current == 0: begin_time = time.time() # Reset for", "set_lr : set the learning rate - clip_gradient : clip", "19/225 ...........] | Loss: 1.961 | Acc: 22.000% (537/2432) def", "optimizer.param_groups: group['lr'] = lr def clip_gradient(optimizer, grad_clip): for group in", "''.join(L) sys.stdout.write(msg) for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') # Go", "print('###', os.popen('stty size', 'r').read()) _, term_width = os.popen('stty size', 'r').read().split()", "range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for i in range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time", "in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') # Go back to the center", "sys.stdout.flush() def set_lr(optimizer, lr): for group in optimizer.param_groups: group['lr'] =", "PyTorch, including: - progress_bar: progress bar mimic xlua.progress. - set_lr", "[] if msg: L.append(' | ' + msg) msg =", "sys.platform == 'win32': term_width = 80 else: print('###', os.popen('stty size',", "%d/%d ' % (current+1, total)) if current < total-1: sys.stdout.write('\\r')", "range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time = time.time() step_time = cur_time -", "clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups: #print(group['params']) for param in", "- progress_bar: progress bar mimic xlua.progress. - set_lr : set", "term_width = 80 else: print('###', os.popen('stty size', 'r').read()) _, term_width", "os.popen('stty size', 'r').read()) _, term_width = os.popen('stty size', 'r').read().split() term_width", "total, msg=None): global last_time, begin_time if current == 0: begin_time", "else: sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer, lr): for group in optimizer.param_groups:", "def set_lr(optimizer, lr): for group in optimizer.param_groups: group['lr'] = lr", "= 30. last_time = time.time() begin_time = last_time #[==>........ 19/225", "else: print('###', os.popen('stty size', 'r').read()) _, term_width = os.popen('stty size',", "' + msg) msg = ''.join(L) sys.stdout.write(msg) for i in", "for PyTorch, including: - progress_bar: progress bar mimic xlua.progress. -", "L.append(' | ' + msg) msg = ''.join(L) sys.stdout.write(msg) for", "= 80 else: print('###', os.popen('stty size', 'r').read()) _, term_width =", "Function #获取控制台行、列数 if sys.platform == 'win32': term_width = 80 else:", "= lr def clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups: #print(group['params'])", "sys.stdout.write('=') sys.stdout.write('>') for i in range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time =", "i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') # Go back to the", "time.time() step_time = cur_time - last_time last_time = cur_time tot_time", "range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d ' % (current+1, total)) if current", "= ''.join(L) sys.stdout.write(msg) for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') #", "_, term_width = os.popen('stty size', 'r').read().split() term_width = int(term_width) TOTAL_BAR_LENGTH", "for i in range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time = time.time() step_time", "of the bar. for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d", "group['lr'] = lr def clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups:", "nn import torch.nn.init as init from torch.autograd import Function #获取控制台行、列数", "step_time = cur_time - last_time last_time = cur_time tot_time =", "for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') # Go back to", "sys.stdout.write('.') sys.stdout.write(']') cur_time = time.time() step_time = cur_time - last_time", "+ msg) msg = ''.join(L) sys.stdout.write(msg) for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3):", "the bar. for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d '", "- cur_len) - 1 sys.stdout.write(' [') for i in range(cur_len):", "22.000% (537/2432) def progress_bar(current, total, msg=None): global last_time, begin_time if", "80 else: print('###', os.popen('stty size', 'r').read()) _, term_width = os.popen('stty", "L = [] if msg: L.append(' | ' + msg)", "bar. cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH - cur_len) -", "(current+1, total)) if current < total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush()", "== 0: begin_time = time.time() # Reset for new bar.", "msg=None): global last_time, begin_time if current == 0: begin_time =", "as init from torch.autograd import Function #获取控制台行、列数 if sys.platform ==", "'r').read().split() term_width = int(term_width) TOTAL_BAR_LENGTH = 30. last_time = time.time()", "1.961 | Acc: 22.000% (537/2432) def progress_bar(current, total, msg=None): global", "# Go back to the center of the bar. for", "time.time() begin_time = last_time #[==>........ 19/225 ...........] | Loss: 1.961", "import torch.nn as nn import torch.nn.init as init from torch.autograd", "size', 'r').read()) _, term_width = os.popen('stty size', 'r').read().split() term_width =", "to the center of the bar. for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2):", "mimic xlua.progress. - set_lr : set the learning rate -", "= int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write(' [') for i", "msg = ''.join(L) sys.stdout.write(msg) for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ')", "for new bar. cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH -", "last_time #[==>........ 19/225 ...........] | Loss: 1.961 | Acc: 22.000%", "for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d ' % (current+1,", "cur_time - begin_time L = [] if msg: L.append(' |", "group in optimizer.param_groups: #print(group['params']) for param in group['params']: param.grad.data.clamp_(-grad_clip, grad_clip)", "progress_bar: progress bar mimic xlua.progress. - set_lr : set the", "as nn import torch.nn.init as init from torch.autograd import Function", "sys.stdout.write('>') for i in range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time = time.time()", "begin_time if current == 0: begin_time = time.time() # Reset", "cur_time = time.time() step_time = cur_time - last_time last_time =", "term_width = os.popen('stty size', 'r').read().split() term_width = int(term_width) TOTAL_BAR_LENGTH =", "int(term_width) TOTAL_BAR_LENGTH = 30. last_time = time.time() begin_time = last_time", "helper functions for PyTorch, including: - progress_bar: progress bar mimic", "last_time last_time = cur_time tot_time = cur_time - begin_time L", "...........] | Loss: 1.961 | Acc: 22.000% (537/2432) def progress_bar(current,", "== 'win32': term_width = 80 else: print('###', os.popen('stty size', 'r').read())", "learning rate - clip_gradient : clip gradient ''' import os", "size', 'r').read().split() term_width = int(term_width) TOTAL_BAR_LENGTH = 30. last_time =", "set_lr(optimizer, lr): for group in optimizer.param_groups: group['lr'] = lr def", "torch import torch.nn as nn import torch.nn.init as init from", "current == 0: begin_time = time.time() # Reset for new", "begin_time = time.time() # Reset for new bar. cur_len =", "i in range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for i in range(rest_len): sys.stdout.write('.')", "torch.autograd import Function #获取控制台行、列数 if sys.platform == 'win32': term_width =", "= time.time() step_time = cur_time - last_time last_time = cur_time", "cur_time - last_time last_time = cur_time tot_time = cur_time -", "the learning rate - clip_gradient : clip gradient ''' import", "clip_gradient : clip gradient ''' import os import sys import", "for group in optimizer.param_groups: #print(group['params']) for param in group['params']: param.grad.data.clamp_(-grad_clip,", "cur_time tot_time = cur_time - begin_time L = [] if", "import torch.nn.init as init from torch.autograd import Function #获取控制台行、列数 if", "sys.stdout.write(' %d/%d ' % (current+1, total)) if current < total-1:", "sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer, lr): for group in optimizer.param_groups: group['lr']", "last_time = time.time() begin_time = last_time #[==>........ 19/225 ...........] |", "sys.stdout.write(' ') # Go back to the center of the", "in range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for i in range(rest_len): sys.stdout.write('.') sys.stdout.write(']')", "center of the bar. for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write('", "- clip_gradient : clip gradient ''' import os import sys", "# Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len =", "if msg: L.append(' | ' + msg) msg = ''.join(L)", "back to the center of the bar. for i in", "import sys import time import math import torch import torch.nn", "''' import os import sys import time import math import", "= int(term_width) TOTAL_BAR_LENGTH = 30. last_time = time.time() begin_time =", "TOTAL_BAR_LENGTH = 30. last_time = time.time() begin_time = last_time #[==>........", "progress bar mimic xlua.progress. - set_lr : set the learning", "msg: L.append(' | ' + msg) msg = ''.join(L) sys.stdout.write(msg)", "def clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups: #print(group['params']) for param", "= time.time() begin_time = last_time #[==>........ 19/225 ...........] | Loss:", "def progress_bar(current, total, msg=None): global last_time, begin_time if current ==", "[') for i in range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for i in", "'win32': term_width = 80 else: print('###', os.popen('stty size', 'r').read()) _,", "% (current+1, total)) if current < total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n')", "os.popen('stty size', 'r').read().split() term_width = int(term_width) TOTAL_BAR_LENGTH = 30. last_time", "tot_time = cur_time - begin_time L = [] if msg:", "' % (current+1, total)) if current < total-1: sys.stdout.write('\\r') else:", "import time import math import torch import torch.nn as nn", "| ' + msg) msg = ''.join(L) sys.stdout.write(msg) for i", "bar. for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d ' %", "global last_time, begin_time if current == 0: begin_time = time.time()", "- set_lr : set the learning rate - clip_gradient :", "last_time, begin_time if current == 0: begin_time = time.time() #", "| Acc: 22.000% (537/2432) def progress_bar(current, total, msg=None): global last_time,", "= time.time() # Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH*current/total)", "0: begin_time = time.time() # Reset for new bar. cur_len", "sys.stdout.write('\\b') sys.stdout.write(' %d/%d ' % (current+1, total)) if current <", "total)) if current < total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush() def", "for group in optimizer.param_groups: group['lr'] = lr def clip_gradient(optimizer, grad_clip):", "cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1", ": set the learning rate - clip_gradient : clip gradient", "math import torch import torch.nn as nn import torch.nn.init as", "- 1 sys.stdout.write(' [') for i in range(cur_len): sys.stdout.write('=') sys.stdout.write('>')", "sys.stdout.write(' [') for i in range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for i", "grad_clip): for group in optimizer.param_groups: #print(group['params']) for param in group['params']:", "lr def clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups: #print(group['params']) for", "torch.nn.init as init from torch.autograd import Function #获取控制台行、列数 if sys.platform", "30. last_time = time.time() begin_time = last_time #[==>........ 19/225 ...........]", "| Loss: 1.961 | Acc: 22.000% (537/2432) def progress_bar(current, total,", "for i in range(cur_len): sys.stdout.write('=') sys.stdout.write('>') for i in range(rest_len):", "lr): for group in optimizer.param_groups: group['lr'] = lr def clip_gradient(optimizer,", "in optimizer.param_groups: group['lr'] = lr def clip_gradient(optimizer, grad_clip): for group", "range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write(' ') # Go back to the center of", "import os import sys import time import math import torch", "gradient ''' import os import sys import time import math", "import torch import torch.nn as nn import torch.nn.init as init", "init from torch.autograd import Function #获取控制台行、列数 if sys.platform == 'win32':", "in range(rest_len): sys.stdout.write('.') sys.stdout.write(']') cur_time = time.time() step_time = cur_time", "group in optimizer.param_groups: group['lr'] = lr def clip_gradient(optimizer, grad_clip): for", "last_time = cur_time tot_time = cur_time - begin_time L =", "#[==>........ 19/225 ...........] | Loss: 1.961 | Acc: 22.000% (537/2432)", "Go back to the center of the bar. for i", "bar mimic xlua.progress. - set_lr : set the learning rate", "msg) msg = ''.join(L) sys.stdout.write(msg) for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3): sys.stdout.write('", "(537/2432) def progress_bar(current, total, msg=None): global last_time, begin_time if current", "'r').read()) _, term_width = os.popen('stty size', 'r').read().split() term_width = int(term_width)", "rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write(' [') for", "- begin_time L = [] if msg: L.append(' | '", "Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH", "if current < total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer,", "- last_time last_time = cur_time tot_time = cur_time - begin_time", "< total-1: sys.stdout.write('\\r') else: sys.stdout.write('\\n') sys.stdout.flush() def set_lr(optimizer, lr): for", "= cur_time - last_time last_time = cur_time tot_time = cur_time", "new bar. cur_len = int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH - cur_len)", "= int(TOTAL_BAR_LENGTH*current/total) rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1 sys.stdout.write('", "'''Some helper functions for PyTorch, including: - progress_bar: progress bar", "in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d ' % (current+1, total)) if", "i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2): sys.stdout.write('\\b') sys.stdout.write(' %d/%d ' % (current+1, total))", "= cur_time - begin_time L = [] if msg: L.append('", "set the learning rate - clip_gradient : clip gradient '''", "os import sys import time import math import torch import", "if sys.platform == 'win32': term_width = 80 else: print('###', os.popen('stty", "= last_time #[==>........ 19/225 ...........] | Loss: 1.961 | Acc:", "xlua.progress. - set_lr : set the learning rate - clip_gradient", "including: - progress_bar: progress bar mimic xlua.progress. - set_lr :", "functions for PyTorch, including: - progress_bar: progress bar mimic xlua.progress.", "= os.popen('stty size', 'r').read().split() term_width = int(term_width) TOTAL_BAR_LENGTH = 30.", "import Function #获取控制台行、列数 if sys.platform == 'win32': term_width = 80", ": clip gradient ''' import os import sys import time", "import math import torch import torch.nn as nn import torch.nn.init", "torch.nn as nn import torch.nn.init as init from torch.autograd import", "from torch.autograd import Function #获取控制台行、列数 if sys.platform == 'win32': term_width", "term_width = int(term_width) TOTAL_BAR_LENGTH = 30. last_time = time.time() begin_time", "begin_time = last_time #[==>........ 19/225 ...........] | Loss: 1.961 |", "= [] if msg: L.append(' | ' + msg) msg", "clip gradient ''' import os import sys import time import", "Acc: 22.000% (537/2432) def progress_bar(current, total, msg=None): global last_time, begin_time" ]
[ "print(self.nbins, self.ndim, self.nbins ** self.ndim) raise Exception(\"Invalid index %s. You", "np.empty((len(vector),) + grid_shape) for idx, v in enumerate(vector): grids[idx] =", "= logging.getLogger(\"indexconverter\") class IndexConverter(object): def __init__(self, ndim, ngrid): self.ndim =", "ndim self.ngrid = ngrid self._modulus = [(ngrid - 1) **", "index %s. You are probably outside the grid. Size:%s\" %", "__init__(self, ndim, ngrid): self.ndim = ndim self.ngrid = ngrid self._modulus", "bin_idx) grid_idx = ((self._zerodim + bin_idx) / self._modulus) % (self.ngrid", "bin_idx in range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def convert_to_grid(self,", "range(ndim)] self._zerodim = np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid - 1) **", "raise Exception(\"Invalid index %s. You are probably outside the grid...\"", "self.ndim) raise Exception(\"Invalid index %s. You are probably outside the", "bin_idx < 0: raise Exception( \"Invalid bin index %s. You", "1) for j in range(ndim)] self._zerodim = np.zeros((self.ndim,)) self.nbins =", "def __init__(self, ndim, ngrid): self.ndim = ndim self.ngrid = ngrid", "np.zeros(grid_shape) for idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return grid", "- 1) ** (ndim - j - 1) for j", "if grid.shape[0] != self.ngrid - 1: raise Exception(\"Wrong dimension of", "grids else: grid = np.zeros(grid_shape) for idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))]", "= np.zeros(grid_shape) for idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return", "as np import utils logger = logging.getLogger(\"indexconverter\") class IndexConverter(object): def", "the grid...\" % bin_idx) grid_idx = ((self._zerodim + bin_idx) /", "return vector def convert_to_grid(self, vector): grid_shape = tuple(np.zeros(self.ndim).astype(int) + (self.ngrid", "grid): if grid.shape[0] != self.ngrid - 1: raise Exception(\"Wrong dimension", "v in enumerate(vector): grids[idx] = self.convert_to_grid(v) return grids else: grid", ">= self.nbins or bin_idx < 0: print(self.nbins, self.ndim, self.nbins **", "dimension of grid. Expect length fo %s got %s\" %", "def convert_to_grid(self, vector): grid_shape = tuple(np.zeros(self.ndim).astype(int) + (self.ngrid - 1))", "logger = logging.getLogger(\"indexconverter\") class IndexConverter(object): def __init__(self, ndim, ngrid): self.ndim", "(self.ngrid - 1, grid.shape[0])) vector = np.empty((self.nbins,)) for bin_idx in", "(self.ngrid - 1) return grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx): bin_idx =", "are probably outside the grid...\" % bin_idx) grid_idx = ((self._zerodim", "grids = np.empty((len(vector),) + grid_shape) for idx, v in enumerate(vector):", "range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return grid def convert_to_grid_idx(self, bin_idx): if", "bin index %s. You are probably outside the grid. Size:%s\"", "logging import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d", "return grids else: grid = np.zeros(grid_shape) for idx in range(len(vector)):", "sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') import", "ngrid self._modulus = [(ngrid - 1) ** (ndim - j", "IndexConverter(object): def __init__(self, ndim, ngrid): self.ndim = ndim self.ngrid =", "= ndim self.ngrid = ngrid self._modulus = [(ngrid - 1)", "enumerate(vector): grids[idx] = self.convert_to_grid(v) return grids else: grid = np.zeros(grid_shape)", "level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') import numpy as np", "grid...\" % bin_idx) grid_idx = ((self._zerodim + bin_idx) / self._modulus)", "utils.rint(np.sum(grid_idx * self._modulus)) if bin_idx >= self.nbins or bin_idx <", "np import utils logger = logging.getLogger(\"indexconverter\") class IndexConverter(object): def __init__(self,", "1: raise Exception(\"Wrong dimension of grid. Expect length fo %s", "for idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return grid def", "self.nbins ** self.ndim) raise Exception(\"Invalid index %s. You are probably", "self._zerodim = np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid - 1) ** ndim))", "Exception(\"Invalid index %s. You are probably outside the grid...\" %", "grid_idx): bin_idx = utils.rint(np.sum(grid_idx * self._modulus)) if bin_idx >= self.nbins", "bin_idx) / self._modulus) % (self.ngrid - 1) return grid_idx.astype(int) def", "are probably outside the grid. Size:%s\" % (bin_idx, self.nbins)) return", "grid_shape = tuple(np.zeros(self.ndim).astype(int) + (self.ngrid - 1)) if len(vector.shape) >", "= tuple(np.zeros(self.ndim).astype(int) + (self.ngrid - 1)) if len(vector.shape) > 1:", "self.ndim, self.nbins ** self.ndim) raise Exception(\"Invalid index %s. You are", "for j in range(ndim)] self._zerodim = np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid", "\"Invalid bin index %s. You are probably outside the grid.", "convert_to_vector(self, grid): if grid.shape[0] != self.ngrid - 1: raise Exception(\"Wrong", "convert_to_grid(self, vector): grid_shape = tuple(np.zeros(self.ndim).astype(int) + (self.ngrid - 1)) if", "/ self._modulus) % (self.ngrid - 1) return grid_idx.astype(int) def convert_to_bin_idx(self,", "class IndexConverter(object): def __init__(self, ndim, ngrid): self.ndim = ndim self.ngrid", "self.ngrid = ngrid self._modulus = [(ngrid - 1) ** (ndim", "% (self.ngrid - 1, grid.shape[0])) vector = np.empty((self.nbins,)) for bin_idx", "- 1) ** ndim)) def convert_to_vector(self, grid): if grid.shape[0] !=", "tuple(np.zeros(self.ndim).astype(int) + (self.ngrid - 1)) if len(vector.shape) > 1: grids", "0: raise Exception( \"Invalid bin index %s. You are probably", "outside the grid...\" % bin_idx) grid_idx = ((self._zerodim + bin_idx)", "if len(vector.shape) > 1: grids = np.empty((len(vector),) + grid_shape) for", "= np.empty((self.nbins,)) for bin_idx in range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return", "> 1: grids = np.empty((len(vector),) + grid_shape) for idx, v", "< 0: print(self.nbins, self.ndim, self.nbins ** self.ndim) raise Exception(\"Invalid index", "1: grids = np.empty((len(vector),) + grid_shape) for idx, v in", "- 1) return grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx): bin_idx = utils.rint(np.sum(grid_idx", "for idx, v in enumerate(vector): grids[idx] = self.convert_to_grid(v) return grids", "% bin_idx) grid_idx = ((self._zerodim + bin_idx) / self._modulus) %", "length fo %s got %s\" % (self.ngrid - 1, grid.shape[0]))", "import numpy as np import utils logger = logging.getLogger(\"indexconverter\") class", "= self.convert_to_grid(v) return grids else: grid = np.zeros(grid_shape) for idx", "grid.shape[0] != self.ngrid - 1: raise Exception(\"Wrong dimension of grid.", "index %s. You are probably outside the grid...\" % bin_idx)", "convert_to_bin_idx(self, grid_idx): bin_idx = utils.rint(np.sum(grid_idx * self._modulus)) if bin_idx >=", ">= self.nbins or bin_idx < 0: raise Exception( \"Invalid bin", "np.empty((self.nbins,)) for bin_idx in range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector", "< 0: raise Exception( \"Invalid bin index %s. You are", "numpy as np import utils logger = logging.getLogger(\"indexconverter\") class IndexConverter(object):", "in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return grid def convert_to_grid_idx(self, bin_idx):", "= np.empty((len(vector),) + grid_shape) for idx, v in enumerate(vector): grids[idx]", "You are probably outside the grid. Size:%s\" % (bin_idx, self.nbins))", "probably outside the grid. Size:%s\" % (bin_idx, self.nbins)) return bin_idx", "__future__ import absolute_import, division, print_function import logging import sys logging.basicConfig(", "logging.getLogger(\"indexconverter\") class IndexConverter(object): def __init__(self, ndim, ngrid): self.ndim = ndim", "%H:%M:%S') import numpy as np import utils logger = logging.getLogger(\"indexconverter\")", "in enumerate(vector): grids[idx] = self.convert_to_grid(v) return grids else: grid =", "= ngrid self._modulus = [(ngrid - 1) ** (ndim -", "= ((self._zerodim + bin_idx) / self._modulus) % (self.ngrid - 1)", "1) return grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx): bin_idx = utils.rint(np.sum(grid_idx *", "from __future__ import absolute_import, division, print_function import logging import sys", "in range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def convert_to_grid(self, vector):", "in range(ndim)] self._zerodim = np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid - 1)", "(self.ngrid - 1)) if len(vector.shape) > 1: grids = np.empty((len(vector),)", "idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return grid def convert_to_grid_idx(self,", "import absolute_import, division, print_function import logging import sys logging.basicConfig( stream=sys.stdout,", "import logging import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s',", "grid_shape) for idx, v in enumerate(vector): grids[idx] = self.convert_to_grid(v) return", "1)) if len(vector.shape) > 1: grids = np.empty((len(vector),) + grid_shape)", "vector): grid_shape = tuple(np.zeros(self.ndim).astype(int) + (self.ngrid - 1)) if len(vector.shape)", "bin_idx = utils.rint(np.sum(grid_idx * self._modulus)) if bin_idx >= self.nbins or", "self.ngrid - 1: raise Exception(\"Wrong dimension of grid. Expect length", "- 1, grid.shape[0])) vector = np.empty((self.nbins,)) for bin_idx in range(self.nbins):", "%(message)s', datefmt='%Y-%m-%d %H:%M:%S') import numpy as np import utils logger", "got %s\" % (self.ngrid - 1, grid.shape[0])) vector = np.empty((self.nbins,))", "grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def convert_to_grid(self, vector): grid_shape = tuple(np.zeros(self.ndim).astype(int) +", "import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')", "+ bin_idx) / self._modulus) % (self.ngrid - 1) return grid_idx.astype(int)", "vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def convert_to_grid(self, vector): grid_shape =", "%(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') import numpy as np import utils", "vector = np.empty((self.nbins,)) for bin_idx in range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))]", "= int(np.rint((ngrid - 1) ** ndim)) def convert_to_vector(self, grid): if", "range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def convert_to_grid(self, vector): grid_shape", "def convert_to_grid_idx(self, bin_idx): if bin_idx >= self.nbins or bin_idx <", "bin_idx): if bin_idx >= self.nbins or bin_idx < 0: print(self.nbins,", "or bin_idx < 0: print(self.nbins, self.ndim, self.nbins ** self.ndim) raise", "self.nbins = int(np.rint((ngrid - 1) ** ndim)) def convert_to_vector(self, grid):", "grid_idx = ((self._zerodim + bin_idx) / self._modulus) % (self.ngrid -", "Exception( \"Invalid bin index %s. You are probably outside the", "%s\" % (self.ngrid - 1, grid.shape[0])) vector = np.empty((self.nbins,)) for", "- 1)) if len(vector.shape) > 1: grids = np.empty((len(vector),) +", "+ (self.ngrid - 1)) if len(vector.shape) > 1: grids =", "grid = np.zeros(grid_shape) for idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx]", "of grid. Expect length fo %s got %s\" % (self.ngrid", "((self._zerodim + bin_idx) / self._modulus) % (self.ngrid - 1) return", "ndim, ngrid): self.ndim = ndim self.ngrid = ngrid self._modulus =", "fo %s got %s\" % (self.ngrid - 1, grid.shape[0])) vector", "if bin_idx >= self.nbins or bin_idx < 0: print(self.nbins, self.ndim,", "grid[tuple(self.convert_to_grid_idx(idx))] = vector[idx] return grid def convert_to_grid_idx(self, bin_idx): if bin_idx", "= np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid - 1) ** ndim)) def", "for bin_idx in range(self.nbins): vector[bin_idx] = grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def", "= grid[tuple(self.convert_to_grid_idx(bin_idx))] return vector def convert_to_grid(self, vector): grid_shape = tuple(np.zeros(self.ndim).astype(int)", "** self.ndim) raise Exception(\"Invalid index %s. You are probably outside", "- j - 1) for j in range(ndim)] self._zerodim =", "%s. You are probably outside the grid...\" % bin_idx) grid_idx", "ndim)) def convert_to_vector(self, grid): if grid.shape[0] != self.ngrid - 1:", "utils logger = logging.getLogger(\"indexconverter\") class IndexConverter(object): def __init__(self, ndim, ngrid):", "%s got %s\" % (self.ngrid - 1, grid.shape[0])) vector =", "raise Exception( \"Invalid bin index %s. You are probably outside", "= vector[idx] return grid def convert_to_grid_idx(self, bin_idx): if bin_idx >=", "np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid - 1) ** ndim)) def convert_to_vector(self,", "!= self.ngrid - 1: raise Exception(\"Wrong dimension of grid. Expect", "[(ngrid - 1) ** (ndim - j - 1) for", "stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') import numpy as", "raise Exception(\"Wrong dimension of grid. Expect length fo %s got", "You are probably outside the grid...\" % bin_idx) grid_idx =", "grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx): bin_idx = utils.rint(np.sum(grid_idx * self._modulus)) if", "self.nbins or bin_idx < 0: raise Exception( \"Invalid bin index", "datefmt='%Y-%m-%d %H:%M:%S') import numpy as np import utils logger =", "Expect length fo %s got %s\" % (self.ngrid - 1,", "j in range(ndim)] self._zerodim = np.zeros((self.ndim,)) self.nbins = int(np.rint((ngrid -", "return grid def convert_to_grid_idx(self, bin_idx): if bin_idx >= self.nbins or", "bin_idx >= self.nbins or bin_idx < 0: raise Exception( \"Invalid", "%s. You are probably outside the grid. Size:%s\" % (bin_idx,", "idx, v in enumerate(vector): grids[idx] = self.convert_to_grid(v) return grids else:", "probably outside the grid...\" % bin_idx) grid_idx = ((self._zerodim +", "= [(ngrid - 1) ** (ndim - j - 1)", "absolute_import, division, print_function import logging import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG,", "grid def convert_to_grid_idx(self, bin_idx): if bin_idx >= self.nbins or bin_idx", "- 1: raise Exception(\"Wrong dimension of grid. Expect length fo", "return grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx): bin_idx = utils.rint(np.sum(grid_idx * self._modulus))", "self._modulus)) if bin_idx >= self.nbins or bin_idx < 0: raise", "format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') import numpy as np import", "self._modulus = [(ngrid - 1) ** (ndim - j -", "or bin_idx < 0: raise Exception( \"Invalid bin index %s.", "else: grid = np.zeros(grid_shape) for idx in range(len(vector)): grid[tuple(self.convert_to_grid_idx(idx))] =", "1, grid.shape[0])) vector = np.empty((self.nbins,)) for bin_idx in range(self.nbins): vector[bin_idx]", "1) ** ndim)) def convert_to_vector(self, grid): if grid.shape[0] != self.ngrid", "convert_to_grid_idx(self, bin_idx): if bin_idx >= self.nbins or bin_idx < 0:", "(ndim - j - 1) for j in range(ndim)] self._zerodim", "grids[idx] = self.convert_to_grid(v) return grids else: grid = np.zeros(grid_shape) for", "len(vector.shape) > 1: grids = np.empty((len(vector),) + grid_shape) for idx,", "= utils.rint(np.sum(grid_idx * self._modulus)) if bin_idx >= self.nbins or bin_idx", "1) ** (ndim - j - 1) for j in", "j - 1) for j in range(ndim)] self._zerodim = np.zeros((self.ndim,))", "self.ndim = ndim self.ngrid = ngrid self._modulus = [(ngrid -", "** (ndim - j - 1) for j in range(ndim)]", "bin_idx >= self.nbins or bin_idx < 0: print(self.nbins, self.ndim, self.nbins", "+ grid_shape) for idx, v in enumerate(vector): grids[idx] = self.convert_to_grid(v)", "int(np.rint((ngrid - 1) ** ndim)) def convert_to_vector(self, grid): if grid.shape[0]", "grid. Expect length fo %s got %s\" % (self.ngrid -", "logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') import numpy", "self._modulus) % (self.ngrid - 1) return grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx):", "def convert_to_bin_idx(self, grid_idx): bin_idx = utils.rint(np.sum(grid_idx * self._modulus)) if bin_idx", "vector[idx] return grid def convert_to_grid_idx(self, bin_idx): if bin_idx >= self.nbins", "ngrid): self.ndim = ndim self.ngrid = ngrid self._modulus = [(ngrid", "division, print_function import logging import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s", "% (self.ngrid - 1) return grid_idx.astype(int) def convert_to_bin_idx(self, grid_idx): bin_idx", "self.nbins or bin_idx < 0: print(self.nbins, self.ndim, self.nbins ** self.ndim)", "* self._modulus)) if bin_idx >= self.nbins or bin_idx < 0:", "Exception(\"Wrong dimension of grid. Expect length fo %s got %s\"", "vector def convert_to_grid(self, vector): grid_shape = tuple(np.zeros(self.ndim).astype(int) + (self.ngrid -", "import utils logger = logging.getLogger(\"indexconverter\") class IndexConverter(object): def __init__(self, ndim,", "grid.shape[0])) vector = np.empty((self.nbins,)) for bin_idx in range(self.nbins): vector[bin_idx] =", "- 1) for j in range(ndim)] self._zerodim = np.zeros((self.ndim,)) self.nbins", "** ndim)) def convert_to_vector(self, grid): if grid.shape[0] != self.ngrid -", "self.convert_to_grid(v) return grids else: grid = np.zeros(grid_shape) for idx in", "print_function import logging import sys logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(asctime)s %(name)s-%(levelname)s:", "bin_idx < 0: print(self.nbins, self.ndim, self.nbins ** self.ndim) raise Exception(\"Invalid", "if bin_idx >= self.nbins or bin_idx < 0: raise Exception(", "def convert_to_vector(self, grid): if grid.shape[0] != self.ngrid - 1: raise", "0: print(self.nbins, self.ndim, self.nbins ** self.ndim) raise Exception(\"Invalid index %s." ]
[]
[ "in qubits if a != b]) ) # pylint: enable=missing-raises-doc", "are handled internally by Pasqal. \"\"\" def __init__(self, qubits: Sequence[cirq.Qid])", "in the distance computation q: qubit involved in the distance", "device.') if isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask != (): raise NotImplementedError(", "z position. Must be of type ThreeDQubit, TwoDQubit, LineQubit or", "{q!r} are too far away\") def validate_moment(self, moment: cirq.Moment): \"\"\"Raises", "2.0 (the \"License\"); # you may not use this file", "is not a valid qubit for gate {!r}. This '", "Distance is measured in units of the coordinates passed into", "valid if operation in self.controlled_gateset: for p in operation.qubits: for", "@property def maximum_qubit_number(self): return 100 @property def metadata(self): return self._metadata", "away\") def validate_moment(self, moment: cirq.Moment): \"\"\"Raises an error if the", "be of the type cirq.NamedQubit and assumed to be all", "# pylint: enable=missing-raises-doc @property def supported_qubit_type(self): return (NamedQubit,) @property def", "ValueError: If the given circuit can't be run on this", "in 3d space, although 2d layouts will be supported sooner", "bool] ) -> List[cirq.Operation]: def on_stuck_raise(bad): return TypeError( \"Don't know", "operation is not valid \"\"\" super().validate_operation(operation) # Verify that a", "converter for compatibility with Pasqal processors. Modified version of ConvertToNeutralAtomGates,", "cirq.InsertStrategy.NEW.\") def minimal_distance(self) -> float: \"\"\"Returns the minimal distance between", "the 'keep' function as an input. \"\"\" def pasqal_convert( self,", "qubits. Args: qubits: qubit involved in the distance computation Raises:", "# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "devices. Serves as the parent class of all Pasqal devices,", "self.maximum_qubit_number) ) self.gateset = PasqalGateset() self.qubits = qubits self._metadata =", "qubits if a != b]) ) # pylint: enable=missing-raises-doc @property", "deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) def qubit_list(self): return", "on the device, identified by their x, y, z position.", "if the given circuit is invalid on this device. A", "Pasqal device, enforcing the constraints typically found in a physical", "one qubit Returns: The minimal distance between qubits, in spacial", "isinstance(qub, self.supported_qubit_type): raise ValueError( '{} is not a valid qubit", "This device ' 'supports qubit types: {}'.format(q, self.supported_qubit_type) ) if", "be a non-negative float.') if len(self.qubits) > 1: if control_radius", "a non-negative float.') if len(self.qubits) > 1: if control_radius >", "spacial coordinate units. \"\"\" if len(self.qubits) <= 1: raise ValueError(\"Two", "- q.y) ** 2 + (p.z - q.z) ** 2)", "and are thus recommended. Only accepts qubits with physical placement.", "supported sooner and are thus recommended. Only accepts qubits with", "'Too many qubits. {} accepts at most {} ' 'qubits.'.format(type(self),", "moment to validate. Raises: ValueError: If the given moment is", "times' ' the minimal distance between qubits.' ) self.control_radius =", "device. When used as a circuit's device, the qubits have", "** 2) def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits) )", "= cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b) for a in qubits for", "LineQubit) def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error if the", "qubits. Args: control_radius: the maximum distance between qubits for a", "Only accepts qubits with physical placement. \"\"\" def __init__( self,", "supported gate') for qub in operation.qubits: if not isinstance(qub, self.supported_qubit_type):", "p or q not part of the device Returns: The", "into the qubit constructor. qubits: Qubits on the device, identified", "return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return self.qubits def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self,", "a minimal distance.\") return min([self.distance(q1, q2) for q1 in self.qubits", "the given circuit can't be run on this device \"\"\"", "language governing permissions and # limitations under the License. from", "{!r}. This device ' 'supports qubit types: {}'.format(q, self.supported_qubit_type) )", "distance.\") return min([self.distance(q1, q2) for q1 in self.qubits for q2", "be of type ThreeDQubit, TwoDQubit, LineQubit or GridQubit. Raises: ValueError:", "wrong qubit type is provided. ValueError: If the number of", "is measured in units of the coordinates passed into the", "to be all connected, the idea behind it being that", "control_radius: float, qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] ) -> None: \"\"\"Initializes", "If the operation is not valid \"\"\" super().validate_operation(operation) # Verify", "a controlled gate operation is valid if operation in self.controlled_gateset:", "use this file except in compliance with the License. #", "in self.qubits for q2 in self.qubits if q1 != q2])", "PasqalDevice operation, \" \"a 1 or 2 qubit gate with", "moment with a measurement. Args: circuit: The circuit to validate", "a new 'convert' method 'pasqal_convert' takes the 'keep' function as", "@cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal device. The most general", "self.minimal_distance(): raise ValueError( 'Control_radius cannot be larger than 3 times'", "is not valid. NotImplementedError: If the operation is a measurement", "-> None: \"\"\"Raises an error if the given circuit is", "computation Raises: ValueError: If the device has only one qubit", "applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) def qubit_list(self):", "__repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return self.qubits def _json_dict_(self): return", "gate converter for compatibility with Pasqal processors. Modified version of", "units. \"\"\" if len(self.qubits) <= 1: raise ValueError(\"Two qubits to", "qubits: qubit involved in the distance computation Raises: ValueError: If", "of same type.\") if len(qubits) > self.maximum_qubit_number: raise ValueError( 'Too", "return abs(p.x - q.x) return np.sqrt((p.x - q.x) ** 2", "- q.x) return np.sqrt((p.x - q.x) ** 2 + (p.y", "from cirq import _compat, GridQubit, LineQubit from cirq.ops import NamedQubit", "def on_stuck_raise(bad): return TypeError( \"Don't know how to work with", "License. # You may obtain a copy of the License", "of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless", "The qubits can be positioned in 3d space, although 2d", "qubit involved in the distance computation Raises: ValueError: If p", "for p in operation.qubits: for q in operation.qubits: if self.distance(p,", "moment: cirq.Moment): \"\"\"Raises an error if the given moment is", "import cirq from cirq import _compat, GridQubit, LineQubit from cirq.ops", "is valid if operation in self.controlled_gateset: for p in operation.qubits:", "= cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self): return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit)", "not part of the device.\") if isinstance(p, GridQubit): return np.sqrt((p.row", "under the License is distributed on an \"AS IS\" BASIS,", "ValueError( 'Too many qubits. {} accepts at most {} '", "ValueError( 'Control_radius cannot be larger than 3 times' ' the", "License for the specific language governing permissions and # limitations", "an input. \"\"\" def pasqal_convert( self, op: cirq.Operation, keep: Callable[[cirq.Operation],", "are invalid or if there is a non-empty moment after", "shared by all future devices. Serves as the parent class", "device. Args: moment: The moment to validate. Raises: ValueError: If", "self.maximum_qubit_number: raise ValueError( 'Too many qubits. {} accepts at most", "qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] ) -> None: \"\"\"Initializes a device", "with some qubits. Args: control_radius: the maximum distance between qubits", "control_radius >= 0: raise ValueError('Control_radius needs to be a non-negative", "Raises: ValueError: If the operation is not valid \"\"\" super().validate_operation(operation)", "__init__(self, qubits: Sequence[cirq.Qid]) -> None: \"\"\"Initializes a device with some", "has_measurement_occurred: if len(moment.operations) > 0: raise ValueError(\"Non-empty moment after measurement\")", "moment after measurement\") for operation in moment.operations: if isinstance(operation.gate, cirq.MeasurementGate):", "on this device. Args: moment: The moment to validate. Raises:", "import _compat, GridQubit, LineQubit from cirq.ops import NamedQubit from cirq_pasqal", "is provided. ValueError: If the number of qubits is greater", "-> float: \"\"\"Returns the distance between two qubits. Args: p:", "qubits is greater than the devices maximum. \"\"\" if len(qubits)", "for control_radius.\"\"\" super().__init__(qubits) if not control_radius >= 0: raise ValueError('Control_radius", "all Pasqal devices, but can also be used on its", "supported_qubit_type(self): return (NamedQubit,) @property def maximum_qubit_number(self): return 100 @property def", "self._metadata = cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b) for a in qubits", "keep: Callable[[cirq.Operation], bool] ) -> List[cirq.Operation]: def on_stuck_raise(bad): return TypeError(", "if not control_radius >= 0: raise ValueError('Control_radius needs to be", "bool: if not isinstance(op, cirq.Operation): raise ValueError('Got unknown operation:', op)", "def _json_dict_(self) -> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class(", "be used on its own for hosting a nearly unconstrained", "cirq_pasqal import ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A generic", "the wrong qubit type is provided. ValueError: If the number", "many qubits. {} accepts at most {} ' 'qubits.'.format(type(self), self.maximum_qubit_number)", "and q. \"\"\" all_qubits = self.qubit_list() if p not in", "= True def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return self.qubits", ") -> None: \"\"\"Initializes a device with some qubits. Args:", "minimal distance between qubits, in spacial coordinate units. \"\"\" if", "if not isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported operation\") if not self.is_pasqal_device_op(operation):", "qubits can be positioned in 3d space, although 2d layouts", "between two qubits. Args: p: qubit involved in the distance", ") -> List[cirq.Operation]: def on_stuck_raise(bad): return TypeError( \"Don't know how", "100 @property def metadata(self): return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.',", "invalid on this device. Args: operation: The operation to validate.", "If the operation is a measurement with an invert mask.", "isinstance(p, LineQubit): return abs(p.x - q.x) return np.sqrt((p.x - q.x)", "self.qubits) def _json_dict_(self) -> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits'])", "class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter for compatibility with Pasqal processors.", "(NamedQubit): Qubits on the device, exclusively unrelated to a physical", "needs to be a non-negative float.') if len(self.qubits) > 1:", "if isinstance(p, GridQubit): return np.sqrt((p.row - q.row) ** 2 +", "gate. Distance is measured in units of the coordinates passed", "class PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal device. The most general of", "exclusively unrelated to a physical position. Raises: TypeError: If the", "if not type(q) is q_type: raise TypeError(\"All qubits must be", "q.x) return np.sqrt((p.x - q.x) ** 2 + (p.y -", "_value_equality_values_(self): return self.qubits def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice):", "self.supported_qubit_type): raise ValueError( '{} is not a valid qubit for", "valid. NotImplementedError: If the operation is a measurement with an", "in compliance with the License. # You may obtain a", "The distance between qubits p and q. \"\"\" all_qubits =", "<= 1: raise ValueError(\"Two qubits to compute a minimal distance.\")", "software # distributed under the License is distributed on an", "compatibility with Pasqal processors. Modified version of ConvertToNeutralAtomGates, where a", "general of Pasqal devices, enforcing only restrictions expected to be", "to be shared by all future devices. Serves as the", "Qubits on the device, exclusively unrelated to a physical position.", "has_measurement_occurred = False for moment in circuit: if has_measurement_occurred: if", "cirq.MeasurementGate): if operation.gate.invert_mask != (): raise NotImplementedError( \"Measurements on Pasqal", "self.gateset def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error if the", "'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset = PasqalGateset() self.qubits = qubits self._metadata", "qubit_list(self): return [qubit for qubit in self.qubits] def is_pasqal_device_op(self, op:", "typing import FrozenSet, Callable, List, Sequence, Any, Union, Dict import", "Pasqal. \"\"\" def __init__(self, qubits: Sequence[cirq.Qid]) -> None: \"\"\"Initializes a", "ThreeDQubit, TwoDQubit, LineQubit or GridQubit. Raises: ValueError: if the wrong", "Raises: ValueError: if the wrong qubit type is provided or", "enforcing only restrictions expected to be shared by all future", "be supported sooner and are thus recommended. Only accepts qubits", "If p or q not part of the device Returns:", "limitations under the License. from typing import FrozenSet, Callable, List,", "to be a non-negative float.') if len(self.qubits) > 1: if", "new 'convert' method 'pasqal_convert' takes the 'keep' function as an", "to be of the type cirq.NamedQubit and assumed to be", "if not isinstance(qub, self.supported_qubit_type): raise ValueError( '{} is not a", "the idea behind it being that after submission, all optimization", "return (self.control_radius, self.qubits) def _json_dict_(self) -> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self,", "Serves as the parent class of all Pasqal devices, but", "networkx as nx import cirq from cirq import _compat, GridQubit,", "return 100 @property def metadata(self): return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if", "involved in the distance computation Raises: ValueError: If the device", "expected to be shared by all future devices. Serves as", "raise ValueError('Control_radius needs to be a non-negative float.') if len(self.qubits)", "NotImplementedError( \"Measurements on Pasqal devices don't support invert_mask.\" ) def", "device. The qubits can be positioned in 3d space, although", "if len(self.qubits) > 1: if control_radius > 3.0 * self.minimal_distance():", "not isinstance(op, cirq.Operation): raise ValueError('Got unknown operation:', op) return op", "function as an input. \"\"\" def pasqal_convert( self, op: cirq.Operation,", "after submission, all optimization and transpilation necessary for its execution", "a device with some qubits. Args: control_radius: the maximum distance", "self.control_radius: raise ValueError(f\"Qubits {p!r}, {q!r} are too far away\") def", "PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter for compatibility with Pasqal processors. Modified", "computation Raises: ValueError: If p or q not part of", "q: qubit involved in the distance computation Raises: ValueError: If", "between qubits, in spacial coordinate units. \"\"\" if len(self.qubits) <=", "> 1: for operation in moment: if not isinstance(operation.gate, cirq.MeasurementGate):", "in 3d. A virtual representation of a Pasqal device, enforcing", "not a supported gate') for qub in operation.qubits: if not", "float, qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] ) -> None: \"\"\"Initializes a", "the constraints typically found in a physical device. The qubits", "Args: operation: the operation to validate Raises: ValueError: If the", "qubits. Args: qubits (NamedQubit): Qubits on the device, exclusively unrelated", "the distance between two qubits. Args: p: qubit involved in", "valid \"\"\" super().validate_operation(operation) # Verify that a controlled gate operation", "qubits for a controlled gate. Distance is measured in units", "ValueError(\"Qubit not part of the device.\") if isinstance(p, GridQubit): return", "the devices maximum. \"\"\" if len(qubits) > 0: q_type =", "from cirq_pasqal import ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A", "it being that after submission, all optimization and transpilation necessary", "raise ValueError( 'Control_radius cannot be larger than 3 times' '", "(ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an", "accepts gates on qubits of type: ' '{}'.format(qub, operation.gate, self.supported_qubit_type)", ") if not type(q) is q_type: raise TypeError(\"All qubits must", "validate Raises: ValueError: If the operation is not valid \"\"\"", "with qubits in 3d. A virtual representation of a Pasqal", "# # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "Developers # # Licensed under the Apache License, Version 2.0", "invalid parameter is provided for control_radius.\"\"\" super().__init__(qubits) if not control_radius", "validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None: \"\"\"Raises an error if the", "that after submission, all optimization and transpilation necessary for its", "part of the device.') if isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask !=", "(self.control_radius, self.qubits) def _json_dict_(self) -> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius',", ") # pylint: enable=missing-raises-doc @property def supported_qubit_type(self): return (NamedQubit,) @property", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"\"\" if not isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported operation\") if not", "f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return self.qubits def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits'])", "if not isinstance(q, self.supported_qubit_type): raise TypeError( 'Unsupported qubit type: {!r}.", "be of same type.\") if len(qubits) > self.maximum_qubit_number: raise ValueError(", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "for a in qubits for b in qubits if a", "if a != b]) ) # pylint: enable=missing-raises-doc @property def", "not isinstance(q, self.supported_qubit_type): raise TypeError( 'Unsupported qubit type: {!r}. This", "are thus recommended. Only accepts qubits with physical placement. \"\"\"", "x, y, z position. Must be of type ThreeDQubit, TwoDQubit,", "or GridQubit. Raises: ValueError: if the wrong qubit type is", "self.control_radius, sorted(self.qubits) ) def _value_equality_values_(self) -> Any: return (self.control_radius, self.qubits)", "TypeError( \"Don't know how to work with {!r}. \" \"It", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "for qub in operation.qubits: if not isinstance(qub, self.supported_qubit_type): raise ValueError(", "raise ValueError(\"Two qubits to compute a minimal distance.\") return min([self.distance(q1,", "a supported gate') for qub in operation.qubits: if not isinstance(qub,", "computation q: qubit involved in the distance computation Raises: ValueError:", "a device with some qubits. Args: qubits (NamedQubit): Qubits on", "to in writing, software # distributed under the License is", "qubits={!r})').format( self.control_radius, sorted(self.qubits) ) def _value_equality_values_(self) -> Any: return (self.control_radius,", "as a circuit's device, the qubits have to be of", "class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual device with qubits in 3d.", "isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported operation\") if not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r}", "# See the License for the specific language governing permissions", "q2 in self.qubits if q1 != q2]) def distance(self, p:", "A circuit is invalid if any of its moments are", "type cirq.NamedQubit and assumed to be all connected, the idea", "> 3.0 * self.minimal_distance(): raise ValueError( 'Control_radius cannot be larger", "the device Returns: The distance between qubits p and q.", "\"\"\"Returns the minimal distance between two qubits in qubits. Args:", "\" \"It isn't a native PasqalDevice operation, \" \"a 1", "1: for operation in moment: if not isinstance(operation.gate, cirq.MeasurementGate): raise", "qubits: if not isinstance(q, self.supported_qubit_type): raise TypeError( 'Unsupported qubit type:", "moment has_measurement_occurred = False for moment in circuit: if has_measurement_occurred:", "or agreed to in writing, software # distributed under the", "the wrong qubit type is provided or if invalid parameter", "required by applicable law or agreed to in writing, software", "GridQubit. Raises: ValueError: if the wrong qubit type is provided", "The Cirq Developers # # Licensed under the Apache License,", "simultaneous gates. Use cirq.InsertStrategy.NEW.\") def minimal_distance(self) -> float: \"\"\"Returns the", "a Pasqal device, enforcing the constraints typically found in a", "1: raise ValueError(\"Two qubits to compute a minimal distance.\") return", "return np.sqrt((p.row - q.row) ** 2 + (p.col - q.col)", "device. Args: operation: the operation to validate Raises: ValueError: If", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "Any, Union, Dict import numpy as np import networkx as", "with the License. # You may obtain a copy of", "len(moment) > 1: for operation in moment: if not isinstance(operation.gate,", "GridQubit): return np.sqrt((p.row - q.row) ** 2 + (p.col -", "device are handled internally by Pasqal. \"\"\" def __init__(self, qubits:", "2) def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits) ) def", "as an input. \"\"\" def pasqal_convert( self, op: cirq.Operation, keep:", "NamedQubit from cirq_pasqal import ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device):", "len(qubits) > 0: q_type = type(qubits[0]) for q in qubits:", "The most general of Pasqal devices, enforcing only restrictions expected", "operation is invalid on this device. Args: operation: The operation", "not isinstance(qub, self.supported_qubit_type): raise ValueError( '{} is not a valid", "the device.') if isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask != (): raise", "If the operation is not valid. NotImplementedError: If the operation", "qubit constructor. qubits: Qubits on the device, identified by their", "qubits of type: ' '{}'.format(qub, operation.gate, self.supported_qubit_type) ) if qub", "the given moment is invalid on this device. Args: moment:", "fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter for", ") def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None: \"\"\"Raises an error", "obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0", "this device. Args: operation: the operation to validate Raises: ValueError:", "if has_measurement_occurred: if len(moment.operations) > 0: raise ValueError(\"Non-empty moment after", "is a non-empty moment after a moment with a measurement.", "if len(qubits) > self.maximum_qubit_number: raise ValueError( 'Too many qubits. {}", "-> bool: if not isinstance(op, cirq.Operation): raise ValueError('Got unknown operation:',", "self, control_radius: float, qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] ) -> None:", "is invalid on this device. Args: moment: The moment to", "in qubits. Args: qubits: qubit involved in the distance computation", "is not part of the device.') if isinstance(operation.gate, cirq.MeasurementGate): if", "= control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def", "q.row) ** 2 + (p.col - q.col) ** 2) if", "compliance with the License. # You may obtain a copy", "if len(moment.operations) > 0: raise ValueError(\"Non-empty moment after measurement\") for", "type is provided. ValueError: If the number of qubits is", "agreed to in writing, software # distributed under the License", "raise ValueError(f'{operation.gate!r} is not a supported gate') for qub in", "to validate Raises: ValueError: If the given circuit can't be", "Any: return (self.control_radius, self.qubits) def _json_dict_(self) -> Dict[str, Any]: return", "operation.gate, self.supported_qubit_type) ) if qub not in self.metadata.qubit_set: raise ValueError(f'{qub}", "The minimal distance between qubits, in spacial coordinate units. \"\"\"", "gate with a known unitary, \" \"or composite.\".format(bad) ) return", "distributed under the License is distributed on an \"AS IS\"", "two qubits in qubits. Args: qubits: qubit involved in the", "len(self.qubits) > 1: if control_radius > 3.0 * self.minimal_distance(): raise", "q.col) ** 2) if isinstance(p, LineQubit): return abs(p.x - q.x)", "type: ' '{}'.format(qub, operation.gate, self.supported_qubit_type) ) if qub not in", "def qubit_list(self): return [qubit for qubit in self.qubits] def is_pasqal_device_op(self,", "!= b]) ) # pylint: enable=missing-raises-doc @property def supported_qubit_type(self): return", "how to work with {!r}. \" \"It isn't a native", "mask. \"\"\" if not isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported operation\") if", "for a controlled gate. Distance is measured in units of", "if invalid parameter is provided for control_radius.\"\"\" super().__init__(qubits) if not", "raise ValueError( '{} is not a valid qubit for gate", "in the distance computation Raises: ValueError: If p or q", "moment: if not isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot do simultaneous gates.", "method 'pasqal_convert' takes the 'keep' function as an input. \"\"\"", "def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits) ) def _value_equality_values_(self)", "op in self.gateset def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error", "express or implied. # See the License for the specific", "['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual device with qubits in", "ValueError: if the wrong qubit type is provided or if", "p in operation.qubits: for q in operation.qubits: if self.distance(p, q)", "except in compliance with the License. # You may obtain", "in a physical device. The qubits can be positioned in", "not part of the device Returns: The distance between qubits", "isinstance(p, GridQubit): return np.sqrt((p.row - q.row) ** 2 + (p.col", "' '{}'.format(qub, operation.gate, self.supported_qubit_type) ) if qub not in self.metadata.qubit_set:", "takes the 'keep' function as an input. \"\"\" def pasqal_convert(", "know how to work with {!r}. \" \"It isn't a", "Raises: ValueError: If the given circuit can't be run on", "with {!r}. \" \"It isn't a native PasqalDevice operation, \"", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot do simultaneous gates. Use cirq.InsertStrategy.NEW.\") def", "= False for moment in circuit: if has_measurement_occurred: if len(moment.operations)", "invert mask. \"\"\" if not isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported operation\")", "not use this file except in compliance with the License.", "an error if the given operation is invalid on this", "than the devices maximum. \"\"\" if len(qubits) > 0: q_type", "all connected, the idea behind it being that after submission,", "type: {!r}. This device ' 'supports qubit types: {}'.format(q, self.supported_qubit_type)", "provided or if invalid parameter is provided for control_radius.\"\"\" super().__init__(qubits)", "sorted(self.qubits) ) def _value_equality_values_(self) -> Any: return (self.control_radius, self.qubits) def", "ConvertToNeutralAtomGates, where a new 'convert' method 'pasqal_convert' takes the 'keep'", "on the device, exclusively unrelated to a physical position. Raises:", "writing, software # distributed under the License is distributed on", "Callable, List, Sequence, Any, Union, Dict import numpy as np", "units of the coordinates passed into the qubit constructor. qubits:", "non-empty moment has_measurement_occurred = False for moment in circuit: if", "you may not use this file except in compliance with", "by Pasqal. \"\"\" def __init__(self, qubits: Sequence[cirq.Qid]) -> None: \"\"\"Initializes", "operation.qubits: if not isinstance(qub, self.supported_qubit_type): raise ValueError( '{} is not", "a physical device. The qubits can be positioned in 3d", "that a controlled gate operation is valid if operation in", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "qub not in self.metadata.qubit_set: raise ValueError(f'{qub} is not part of", "super().validate_circuit(circuit) # Measurements must be in the last non-empty moment", "q: Any) -> float: \"\"\"Returns the distance between two qubits.", "LineQubit): return abs(p.x - q.x) return np.sqrt((p.x - q.x) **", "The operation to validate. Raises: ValueError: If the operation is", "virtual device with qubits in 3d. A virtual representation of", "the last non-empty moment has_measurement_occurred = False for moment in", "__init__( self, control_radius: float, qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] ) ->", "'Unsupported qubit type: {!r}. This device ' 'supports qubit types:", "' the minimal distance between qubits.' ) self.control_radius = control_radius", "cirq.MeasurementGate): raise ValueError(\"Cannot do simultaneous gates. Use cirq.InsertStrategy.NEW.\") def minimal_distance(self)", "if len(qubits) > 0: q_type = type(qubits[0]) for q in", "minimal distance.\") return min([self.distance(q1, q2) for q1 in self.qubits for", "2) if isinstance(p, LineQubit): return abs(p.x - q.x) return np.sqrt((p.x", "return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' )", "if isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask != (): raise NotImplementedError( \"Measurements", "op: cirq.Operation, keep: Callable[[cirq.Operation], bool] ) -> List[cirq.Operation]: def on_stuck_raise(bad):", "on_stuck_raise(bad): return TypeError( \"Don't know how to work with {!r}.", "> 0: q_type = type(qubits[0]) for q in qubits: if", "valid qubit for gate {!r}. This ' 'device accepts gates", "self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self): return (ThreeDQubit, TwoDQubit, GridQubit,", "+ (p.col - q.col) ** 2) if isinstance(p, LineQubit): return", "- q.col) ** 2) if isinstance(p, LineQubit): return abs(p.x -", "CONDITIONS OF ANY KIND, either express or implied. # See", "can also be used on its own for hosting a", "PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal device. The most general of Pasqal", "validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error if the given operation", "operation\") if not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is not a supported", "of the type cirq.NamedQubit and assumed to be all connected,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "TypeError: If the wrong qubit type is provided. ValueError: If", "device with some qubits. Args: control_radius: the maximum distance between", "cannot be larger than 3 times' ' the minimal distance", "0: q_type = type(qubits[0]) for q in qubits: if not", "{}'.format(q, self.supported_qubit_type) ) if not type(q) is q_type: raise TypeError(\"All", "if not isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot do simultaneous gates. Use", "cirq.GateOperation): raise ValueError(\"Unsupported operation\") if not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is", "a controlled gate. Distance is measured in units of the", "if control_radius > 3.0 * self.minimal_distance(): raise ValueError( 'Control_radius cannot", "np.sqrt((p.row - q.row) ** 2 + (p.col - q.col) **", "moment is invalid on this device. Args: moment: The moment", "float: \"\"\"Returns the minimal distance between two qubits in qubits.", "2 qubit gate with a known unitary, \" \"or composite.\".format(bad)", "a nearly unconstrained device. When used as a circuit's device,", "for its execution on the specified device are handled internally", "> 0: raise ValueError(\"Non-empty moment after measurement\") for operation in", "in self.gateset def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error if", "operation.gate.invert_mask != (): raise NotImplementedError( \"Measurements on Pasqal devices don't", "p: qubit involved in the distance computation q: qubit involved", "List[cirq.Operation]: def on_stuck_raise(bad): return TypeError( \"Don't know how to work", "raise TypeError( 'Unsupported qubit type: {!r}. This device ' 'supports", "gate') for qub in operation.qubits: if not isinstance(qub, self.supported_qubit_type): raise", "after measurement\") for operation in moment.operations: if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred", "qubit type: {!r}. This device ' 'supports qubit types: {}'.format(q,", "type ThreeDQubit, TwoDQubit, LineQubit or GridQubit. Raises: ValueError: if the", "generic Pasqal device. The most general of Pasqal devices, enforcing", "b]) ) # pylint: enable=missing-raises-doc @property def supported_qubit_type(self): return (NamedQubit,)", "be shared by all future devices. Serves as the parent", "maximum distance between qubits for a controlled gate. Distance is", "{} accepts at most {} ' 'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset", "def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return self.qubits def _json_dict_(self):", "far away\") def validate_moment(self, moment: cirq.Moment): \"\"\"Raises an error if", "@property def metadata(self): return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15')", "False for moment in circuit: if has_measurement_occurred: if len(moment.operations) >", "if self.distance(p, q) > self.control_radius: raise ValueError(f\"Qubits {p!r}, {q!r} are", "behind it being that after submission, all optimization and transpilation", "def _value_equality_values_(self) -> Any: return (self.control_radius, self.qubits) def _json_dict_(self) ->", "involved in the distance computation Raises: ValueError: If p or", "qubits p and q. \"\"\" all_qubits = self.qubit_list() if p", "this device. Args: operation: The operation to validate. Raises: ValueError:", "numpy as np import networkx as nx import cirq from", "is_pasqal_device_op(self, op: cirq.Operation) -> bool: if not isinstance(op, cirq.Operation): raise", "qubits: Sequence[cirq.Qid]) -> None: \"\"\"Initializes a device with some qubits.", "the operation is not valid. NotImplementedError: If the operation is", "-> None: \"\"\"Initializes a device with some qubits. Args: control_radius:", "q in operation.qubits: if self.distance(p, q) > self.control_radius: raise ValueError(f\"Qubits", "constraints typically found in a physical device. The qubits can", "len(moment.operations) > 0: raise ValueError(\"Non-empty moment after measurement\") for operation", "if operation in self.controlled_gateset: for p in operation.qubits: for q", "the qubits have to be of the type cirq.NamedQubit and", "controlled gate. Distance is measured in units of the coordinates", "q2) for q1 in self.qubits for q2 in self.qubits if", "as the parent class of all Pasqal devices, but can", "non-negative float.') if len(self.qubits) > 1: if control_radius > 3.0", "by all future devices. Serves as the parent class of", "q1 != q2]) def distance(self, p: Any, q: Any) ->", "OR CONDITIONS OF ANY KIND, either express or implied. #", "gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter for compatibility with", "q. \"\"\" all_qubits = self.qubit_list() if p not in all_qubits", "Args: p: qubit involved in the distance computation q: qubit", "NotImplementedError: If the operation is a measurement with an invert", "qubits. {} accepts at most {} ' 'qubits.'.format(type(self), self.maximum_qubit_number) )", "must be in the last non-empty moment has_measurement_occurred = False", "the License is distributed on an \"AS IS\" BASIS, #", "a != b]) ) # pylint: enable=missing-raises-doc @property def supported_qubit_type(self):", "restrictions expected to be shared by all future devices. Serves", "> 1: if control_radius > 3.0 * self.minimal_distance(): raise ValueError(", "distance between two qubits. Args: p: qubit involved in the", "unitary, \" \"or composite.\".format(bad) ) return cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one,", "in spacial coordinate units. \"\"\" if len(self.qubits) <= 1: raise", "device. A circuit is invalid if any of its moments", "q.x) ** 2 + (p.y - q.y) ** 2 +", "import NamedQubit from cirq_pasqal import ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality class", "not isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported operation\") if not self.is_pasqal_device_op(operation): raise", "minimal distance between qubits.' ) self.control_radius = control_radius self.gateset =", "- q.row) ** 2 + (p.col - q.col) ** 2)", "** 2 + (p.y - q.y) ** 2 + (p.z", "the distance computation q: qubit involved in the distance computation", "do simultaneous gates. Use cirq.InsertStrategy.NEW.\") def minimal_distance(self) -> float: \"\"\"Returns", "for compatibility with Pasqal processors. Modified version of ConvertToNeutralAtomGates, where", "metadata.qubit_set() if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits)", "moment.operations: if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred = True def __repr__(self): return", "be larger than 3 times' ' the minimal distance between", "physical placement. \"\"\" def __init__( self, control_radius: float, qubits: Sequence[Union[ThreeDQubit,", "0: raise ValueError(\"Non-empty moment after measurement\") for operation in moment.operations:", "accepts at most {} ' 'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset =", ") self.control_radius = control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate))", "composite.\".format(bad) ) return cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one, on_stuck_raise=None if self.ignore_failures", "of the coordinates passed into the qubit constructor. qubits: Qubits", "distance between qubits p and q. \"\"\" all_qubits = self.qubit_list()", "b) for a in qubits for b in qubits if", "\"\"\"A gate converter for compatibility with Pasqal processors. Modified version", "Args: operation: The operation to validate. Raises: ValueError: If the", "an error if the given moment is invalid on this", "not in all_qubits or q not in all_qubits: raise ValueError(\"Qubit", "the distance computation Raises: ValueError: If p or q not", "device, enforcing the constraints typically found in a physical device.", "\"or composite.\".format(bad) ) return cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one, on_stuck_raise=None if", "with physical placement. \"\"\" def __init__( self, control_radius: float, qubits:", "device. Args: operation: The operation to validate. Raises: ValueError: If", "to compute a minimal distance.\") return min([self.distance(q1, q2) for q1", "all_qubits or q not in all_qubits: raise ValueError(\"Qubit not part", "law or agreed to in writing, software # distributed under", "between qubits.' ) self.control_radius = control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset", "def validate_moment(self, moment: cirq.Moment): \"\"\"Raises an error if the given", "if len(moment) > 1: for operation in moment: if not", "than 3 times' ' the minimal distance between qubits.' )", "measurement\") for operation in moment.operations: if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred =", "with Pasqal processors. Modified version of ConvertToNeutralAtomGates, where a new", "parameter is provided for control_radius.\"\"\" super().__init__(qubits) if not control_radius >=", "device ' 'supports qubit types: {}'.format(q, self.supported_qubit_type) ) if not", "(p.col - q.col) ** 2) if isinstance(p, LineQubit): return abs(p.x", "qubit involved in the distance computation q: qubit involved in", "Raises: ValueError: If p or q not part of the", "between two qubits in qubits. Args: qubits: qubit involved in", "PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self): return (ThreeDQubit, TwoDQubit,", "device.\") if isinstance(p, GridQubit): return np.sqrt((p.row - q.row) ** 2", "its own for hosting a nearly unconstrained device. When used", "ValueError(f'{operation.gate!r} is not a supported gate') for qub in operation.qubits:", "an error if the given circuit is invalid on this", "qubit type is provided. ValueError: If the number of qubits", "in moment.operations: if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred = True def __repr__(self):", "operation in moment.operations: if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred = True def", "GridQubit, LineQubit]] ) -> None: \"\"\"Initializes a device with some", "if the wrong qubit type is provided or if invalid", "the distance computation Raises: ValueError: If the device has only", "Returns: The minimal distance between qubits, in spacial coordinate units.", "in self.qubits if q1 != q2]) def distance(self, p: Any,", "qubit type is provided or if invalid parameter is provided", "!= q2]) def distance(self, p: Any, q: Any) -> float:", "connected, the idea behind it being that after submission, all", "Raises: TypeError: If the wrong qubit type is provided. ValueError:", "self.qubits = qubits self._metadata = cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b) for", "of qubits is greater than the devices maximum. \"\"\" if", "** 2) if isinstance(p, LineQubit): return abs(p.x - q.x) return", "where a new 'convert' method 'pasqal_convert' takes the 'keep' function", "TwoDQubit, GridQubit, LineQubit) def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error", "ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal device.", "the operation to validate Raises: ValueError: If the operation is", "provided. ValueError: If the number of qubits is greater than", "# limitations under the License. from typing import FrozenSet, Callable,", "on this device. Args: operation: the operation to validate Raises:", "self.gateset = PasqalGateset() self.qubits = qubits self._metadata = cirq.DeviceMetadata( qubits,", "FrozenSet, Callable, List, Sequence, Any, Union, Dict import numpy as", "\"\"\"A generic Pasqal device. The most general of Pasqal devices,", "given operation is invalid on this device. Args: operation: the", "from cirq.ops import NamedQubit from cirq_pasqal import ThreeDQubit, TwoDQubit, PasqalGateset", "isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask != (): raise NotImplementedError( \"Measurements on", "in self.controlled_gateset: for p in operation.qubits: for q in operation.qubits:", "of ConvertToNeutralAtomGates, where a new 'convert' method 'pasqal_convert' takes the", "{!r}. \" \"It isn't a native PasqalDevice operation, \" \"a", "may obtain a copy of the License at # #", "transpilation necessary for its execution on the specified device are", "raise ValueError(f'{qub} is not part of the device.') if isinstance(operation.gate,", "raise ValueError(\"Qubit not part of the device.\") if isinstance(p, GridQubit):", "some qubits. Args: control_radius: the maximum distance between qubits for", "1 or 2 qubit gate with a known unitary, \"", "isinstance(q, self.supported_qubit_type): raise TypeError( 'Unsupported qubit type: {!r}. This device", "self.supported_qubit_type) ) if qub not in self.metadata.qubit_set: raise ValueError(f'{qub} is", "def __init__( self, control_radius: float, qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] )", "the minimal distance between qubits.' ) self.control_radius = control_radius self.gateset", "the parent class of all Pasqal devices, but can also", "LineQubit]] ) -> None: \"\"\"Initializes a device with some qubits.", "this device. A circuit is invalid if any of its", "b in qubits if a != b]) ) # pylint:", "of Pasqal devices, enforcing only restrictions expected to be shared", "Must be of type ThreeDQubit, TwoDQubit, LineQubit or GridQubit. Raises:", "distance between qubits.' ) self.control_radius = control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False)", "@property def supported_qubit_type(self): return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def validate_operation(self,", "used on its own for hosting a nearly unconstrained device.", "circuit: The circuit to validate Raises: ValueError: If the given", "physical position. Raises: TypeError: If the wrong qubit type is", "ValueError: If the number of qubits is greater than the", "at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "Copyright 2020 The Cirq Developers # # Licensed under the", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "super().__init__(qubits) if not control_radius >= 0: raise ValueError('Control_radius needs to", "circuit's device, the qubits have to be of the type", "cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b) for a in qubits for b", "p and q. \"\"\" all_qubits = self.qubit_list() if p not", "unrelated to a physical position. Raises: TypeError: If the wrong", "a native PasqalDevice operation, \" \"a 1 or 2 qubit", "def __init__(self, qubits: Sequence[cirq.Qid]) -> None: \"\"\"Initializes a device with", "q_type = type(qubits[0]) for q in qubits: if not isinstance(q,", "may not use this file except in compliance with the", "\"\"\" super().validate_circuit(circuit) # Measurements must be in the last non-empty", "When used as a circuit's device, the qubits have to", "if q1 != q2]) def distance(self, p: Any, q: Any)", "(): raise NotImplementedError( \"Measurements on Pasqal devices don't support invert_mask.\"", "float.') if len(self.qubits) > 1: if control_radius > 3.0 *", "q in qubits: if not isinstance(q, self.supported_qubit_type): raise TypeError( 'Unsupported", "self.distance(p, q) > self.control_radius: raise ValueError(f\"Qubits {p!r}, {q!r} are too", "if the given moment is invalid on this device. Args:", "Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).'", "invert_mask.\" ) def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None: \"\"\"Raises an", "of type: ' '{}'.format(qub, operation.gate, self.supported_qubit_type) ) if qub not", "any of its moments are invalid or if there is", "operation:', op) return op in self.gateset def validate_operation(self, operation: cirq.Operation):", "on this device. A circuit is invalid if any of", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "2d layouts will be supported sooner and are thus recommended.", "- q.x) ** 2 + (p.y - q.y) ** 2", "this file except in compliance with the License. # You", "Pasqal devices, but can also be used on its own", "own for hosting a nearly unconstrained device. When used as", "measurement with an invert mask. \"\"\" if not isinstance(operation, cirq.GateOperation):", "# Measurements must be in the last non-empty moment has_measurement_occurred", "None: \"\"\"Initializes a device with some qubits. Args: control_radius: the", "for q in operation.qubits: if self.distance(p, q) > self.control_radius: raise", "in qubits: if not isinstance(q, self.supported_qubit_type): raise TypeError( 'Unsupported qubit", "an invert mask. \"\"\" if not isinstance(operation, cirq.GateOperation): raise ValueError(\"Unsupported", "{} ' 'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset = PasqalGateset() self.qubits =", "The moment to validate. Raises: ValueError: If the given moment", "device has only one qubit Returns: The minimal distance between", "on this device \"\"\" super().validate_circuit(circuit) # Measurements must be in", "2 + (p.col - q.col) ** 2) if isinstance(p, LineQubit):", "Qubits on the device, identified by their x, y, z", "ValueError: If the device has only one qubit Returns: The", "greater than the devices maximum. \"\"\" if len(qubits) > 0:", "https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "return frozenset(self.qubits) def qubit_list(self): return [qubit for qubit in self.qubits]", "given circuit is invalid on this device. A circuit is", "nx import cirq from cirq import _compat, GridQubit, LineQubit from", "a measurement with an invert mask. \"\"\" if not isinstance(operation,", "in operation.qubits: for q in operation.qubits: if self.distance(p, q) >", "Raises: ValueError: If the device has only one qubit Returns:", "# # Licensed under the Apache License, Version 2.0 (the", "Dict import numpy as np import networkx as nx import", "Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit,", "be positioned in 3d space, although 2d layouts will be", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "under the License. from typing import FrozenSet, Callable, List, Sequence,", "Pasqal virtual device with qubits in 3d. A virtual representation", "q_type: raise TypeError(\"All qubits must be of same type.\") if", "qubit in self.qubits] def is_pasqal_device_op(self, op: cirq.Operation) -> bool: if", "Modified version of ConvertToNeutralAtomGates, where a new 'convert' method 'pasqal_convert'", "nearly unconstrained device. When used as a circuit's device, the", "measurement. Args: circuit: The circuit to validate Raises: ValueError: If", "\"\"\"Returns the distance between two qubits. Args: p: qubit involved", "\"\"\"Initializes a device with some qubits. Args: qubits (NamedQubit): Qubits", "raise ValueError( 'Too many qubits. {} accepts at most {}", "this device \"\"\" super().validate_circuit(circuit) # Measurements must be in the", "= PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self): return (ThreeDQubit,", "assumed to be all connected, the idea behind it being", "supported_qubit_type(self): return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def validate_operation(self, operation: cirq.Operation):", "np.sqrt((p.x - q.x) ** 2 + (p.y - q.y) **", "metadata(self): return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15') def qubit_set(self)", "isn't a native PasqalDevice operation, \" \"a 1 or 2", "\" \"a 1 or 2 qubit gate with a known", "distance computation q: qubit involved in the distance computation Raises:", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "virtual representation of a Pasqal device, enforcing the constraints typically", "has_measurement_occurred = True def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return", "operation.qubits: for q in operation.qubits: if self.distance(p, q) > self.control_radius:", "not part of the device.') if isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask", "{!r}. This ' 'device accepts gates on qubits of type:", "= qubits self._metadata = cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b) for a", "circuit is invalid on this device. A circuit is invalid", "if not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is not a supported gate')", "self.supported_qubit_type): raise TypeError( 'Unsupported qubit type: {!r}. This device '", "gate {!r}. This ' 'device accepts gates on qubits of", "If the wrong qubit type is provided. ValueError: If the", "if not isinstance(op, cirq.Operation): raise ValueError('Got unknown operation:', op) return", "a moment with a measurement. Args: circuit: The circuit to", "Args: qubits (NamedQubit): Qubits on the device, exclusively unrelated to", "'cirq.AbstractCircuit') -> None: \"\"\"Raises an error if the given circuit", "return cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one, on_stuck_raise=None if self.ignore_failures else on_stuck_raise,", "Use cirq.InsertStrategy.NEW.\") def minimal_distance(self) -> float: \"\"\"Returns the minimal distance", "If the device has only one qubit Returns: The minimal", "devices, but can also be used on its own for", "qubits with physical placement. \"\"\" def __init__( self, control_radius: float,", "by their x, y, z position. Must be of type", "self.control_radius = control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property", "if len(self.qubits) <= 1: raise ValueError(\"Two qubits to compute a", "\" \"or composite.\".format(bad) ) return cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one, on_stuck_raise=None", "float: \"\"\"Returns the distance between two qubits. Args: p: qubit", "> self.control_radius: raise ValueError(f\"Qubits {p!r}, {q!r} are too far away\")", "space, although 2d layouts will be supported sooner and are", "for b in qubits if a != b]) ) #", "'Control_radius cannot be larger than 3 times' ' the minimal", "device Returns: The distance between qubits p and q. \"\"\"", "the specified device are handled internally by Pasqal. \"\"\" def", "not isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot do simultaneous gates. Use cirq.InsertStrategy.NEW.\")", "ValueError: If the given moment is invalid. \"\"\" super().validate_moment(moment) if", "with a known unitary, \" \"or composite.\".format(bad) ) return cirq.protocols.decompose(", "gates. Use cirq.InsertStrategy.NEW.\") def minimal_distance(self) -> float: \"\"\"Returns the minimal", "2 + (p.z - q.z) ** 2) def __repr__(self): return", "Args: control_radius: the maximum distance between qubits for a controlled", "q.z) ** 2) def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits)", "governing permissions and # limitations under the License. from typing", "ValueError(\"Two qubits to compute a minimal distance.\") return min([self.distance(q1, q2)", "be all connected, the idea behind it being that after", "self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is not a supported gate') for qub", "\"\"\" def pasqal_convert( self, op: cirq.Operation, keep: Callable[[cirq.Operation], bool] )", "this device. Args: moment: The moment to validate. Raises: ValueError:", "qubits in qubits. Args: qubits: qubit involved in the distance", "\"\"\" def __init__(self, qubits: Sequence[cirq.Qid]) -> None: \"\"\"Initializes a device", "PasqalGateset() self.qubits = qubits self._metadata = cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b)", "Args: qubits: qubit involved in the distance computation Raises: ValueError:", "invalid on this device. Args: moment: The moment to validate.", "if there is a non-empty moment after a moment with", "3.0 * self.minimal_distance(): raise ValueError( 'Control_radius cannot be larger than", "ValueError: If the operation is not valid \"\"\" super().validate_operation(operation) #", "cirq.Operation) -> bool: if not isinstance(op, cirq.Operation): raise ValueError('Got unknown", "operation in moment: if not isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot do", "cirq.MeasurementGate): has_measurement_occurred = True def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self):", "_compat, GridQubit, LineQubit from cirq.ops import NamedQubit from cirq_pasqal import", "at most {} ' 'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset = PasqalGateset()", "Raises: ValueError: If the operation is not valid. NotImplementedError: If", "with an invert mask. \"\"\" if not isinstance(operation, cirq.GateOperation): raise", "raise NotImplementedError( \"Measurements on Pasqal devices don't support invert_mask.\" )", "@_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return", "moment after a moment with a measurement. Args: circuit: The", "\"\"\"A Pasqal virtual device with qubits in 3d. A virtual", "the License. from typing import FrozenSet, Callable, List, Sequence, Any,", "physical device. The qubits can be positioned in 3d space,", "known unitary, \" \"or composite.\".format(bad) ) return cirq.protocols.decompose( op, keep=keep,", "of all Pasqal devices, but can also be used on", "Measurements must be in the last non-empty moment has_measurement_occurred =", "or implied. # See the License for the specific language", "raise TypeError(\"All qubits must be of same type.\") if len(qubits)", "super().validate_operation(operation) # Verify that a controlled gate operation is valid", "qubits in 3d. A virtual representation of a Pasqal device,", "is provided or if invalid parameter is provided for control_radius.\"\"\"", "circuit is invalid if any of its moments are invalid", "for qubit in self.qubits] def is_pasqal_device_op(self, op: cirq.Operation) -> bool:", "\"a 1 or 2 qubit gate with a known unitary,", "= type(qubits[0]) for q in qubits: if not isinstance(q, self.supported_qubit_type):", "y, z position. Must be of type ThreeDQubit, TwoDQubit, LineQubit", "cirq.Operation, keep: Callable[[cirq.Operation], bool] ) -> List[cirq.Operation]: def on_stuck_raise(bad): return", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "part of the device.\") if isinstance(p, GridQubit): return np.sqrt((p.row -", ") self.gateset = PasqalGateset() self.qubits = qubits self._metadata = cirq.DeviceMetadata(", "type(q) is q_type: raise TypeError(\"All qubits must be of same", "of the device.') if isinstance(operation.gate, cirq.MeasurementGate): if operation.gate.invert_mask != ():", "3d space, although 2d layouts will be supported sooner and", "the device, identified by their x, y, z position. Must", "q2]) def distance(self, p: Any, q: Any) -> float: \"\"\"Returns", "def _value_equality_values_(self): return self.qubits def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class", "self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self): return", "the device has only one qubit Returns: The minimal distance", "2 + (p.y - q.y) ** 2 + (p.z -", "cirq.Moment): \"\"\"Raises an error if the given moment is invalid", "\"Don't know how to work with {!r}. \" \"It isn't", "of a Pasqal device, enforcing the constraints typically found in", "PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual device with qubits in 3d. A", "sooner and are thus recommended. Only accepts qubits with physical", "from typing import FrozenSet, Callable, List, Sequence, Any, Union, Dict", "unconstrained device. When used as a circuit's device, the qubits", "its moments are invalid or if there is a non-empty", "control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset = cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self):", "if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred = True def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})'", "for gate {!r}. This ' 'device accepts gates on qubits", "a non-empty moment after a moment with a measurement. Args:", "validate Raises: ValueError: If the given circuit can't be run", "q.y) ** 2 + (p.z - q.z) ** 2) def", "error if the given circuit is invalid on this device.", "its execution on the specified device are handled internally by", "not a valid qubit for gate {!r}. This ' 'device", "p not in all_qubits or q not in all_qubits: raise", "def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) def qubit_list(self): return [qubit", "operation: The operation to validate. Raises: ValueError: If the operation", "two qubits. Args: p: qubit involved in the distance computation", "(the \"License\"); # you may not use this file except", "True def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def _value_equality_values_(self): return self.qubits def", "operation to validate. Raises: ValueError: If the operation is not", "error if the given operation is invalid on this device.", "raise ValueError(f\"Qubits {p!r}, {q!r} are too far away\") def validate_moment(self,", "the minimal distance between two qubits in qubits. Args: qubits:", "# you may not use this file except in compliance", "the number of qubits is greater than the devices maximum.", "cirq import _compat, GridQubit, LineQubit from cirq.ops import NamedQubit from", "a in qubits for b in qubits if a !=", "operation.qubits: if self.distance(p, q) > self.control_radius: raise ValueError(f\"Qubits {p!r}, {q!r}", "native PasqalDevice operation, \" \"a 1 or 2 qubit gate", "as nx import cirq from cirq import _compat, GridQubit, LineQubit", "ValueError('Got unknown operation:', op) return op in self.gateset def validate_operation(self,", "only restrictions expected to be shared by all future devices.", "import networkx as nx import cirq from cirq import _compat,", "the type cirq.NamedQubit and assumed to be all connected, the", "too far away\") def validate_moment(self, moment: cirq.Moment): \"\"\"Raises an error", "are too far away\") def validate_moment(self, moment: cirq.Moment): \"\"\"Raises an", "typically found in a physical device. The qubits can be", "deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter", "in the last non-empty moment has_measurement_occurred = False for moment", "distance(self, p: Any, q: Any) -> float: \"\"\"Returns the distance", "PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal device. The most", "the operation is not valid \"\"\" super().validate_operation(operation) # Verify that", "frozenset(self.qubits) def qubit_list(self): return [qubit for qubit in self.qubits] def", "gates on qubits of type: ' '{}'.format(qub, operation.gate, self.supported_qubit_type) )", "and transpilation necessary for its execution on the specified device", "the device.\") if isinstance(p, GridQubit): return np.sqrt((p.row - q.row) **", "on its own for hosting a nearly unconstrained device. When", "permissions and # limitations under the License. from typing import", "a measurement. Args: circuit: The circuit to validate Raises: ValueError:", "+ (p.y - q.y) ** 2 + (p.z - q.z)", "will be supported sooner and are thus recommended. Only accepts", "LineQubit or GridQubit. Raises: ValueError: if the wrong qubit type", "# # Unless required by applicable law or agreed to", "not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is not a supported gate') for", "if qub not in self.metadata.qubit_set: raise ValueError(f'{qub} is not part", "import ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal", "invalid on this device. A circuit is invalid if any", "of the device.\") if isinstance(p, GridQubit): return np.sqrt((p.row - q.row)", "-> List[cirq.Operation]: def on_stuck_raise(bad): return TypeError( \"Don't know how to", "is not a supported gate') for qub in operation.qubits: if", "# Verify that a controlled gate operation is valid if", "if any of its moments are invalid or if there", "placement. \"\"\" def __init__( self, control_radius: float, qubits: Sequence[Union[ThreeDQubit, GridQubit,", "gate operation is valid if operation in self.controlled_gateset: for p", "if p not in all_qubits or q not in all_qubits:", "(p.z - q.z) ** 2) def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format(", ") return cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one, on_stuck_raise=None if self.ignore_failures else", "Version 2.0 (the \"License\"); # you may not use this", "LineQubit from cirq.ops import NamedQubit from cirq_pasqal import ThreeDQubit, TwoDQubit,", "def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None: \"\"\"Raises an error if", "return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits) ) def _value_equality_values_(self) -> Any:", "in operation.qubits: if self.distance(p, q) > self.control_radius: raise ValueError(f\"Qubits {p!r},", "def distance(self, p: Any, q: Any) -> float: \"\"\"Returns the", "qubit types: {}'.format(q, self.supported_qubit_type) ) if not type(q) is q_type:", "and assumed to be all connected, the idea behind it", "handled internally by Pasqal. \"\"\" def __init__(self, qubits: Sequence[cirq.Qid]) ->", "TypeError( 'Unsupported qubit type: {!r}. This device ' 'supports qubit", "def supported_qubit_type(self): return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def validate_operation(self, operation:", "parent class of all Pasqal devices, but can also be", "Pasqal devices, enforcing only restrictions expected to be shared by", "have to be of the type cirq.NamedQubit and assumed to", ">= 0: raise ValueError('Control_radius needs to be a non-negative float.')", "qubits.' ) self.control_radius = control_radius self.gateset = PasqalGateset(include_additional_controlled_ops=False) self.controlled_gateset =", "in self.metadata.qubit_set: raise ValueError(f'{qub} is not part of the device.')", "the coordinates passed into the qubit constructor. qubits: Qubits on", "FrozenSet[cirq.Qid]: return frozenset(self.qubits) def qubit_list(self): return [qubit for qubit in", "Args: circuit: The circuit to validate Raises: ValueError: If the", "hosting a nearly unconstrained device. When used as a circuit's", "support invert_mask.\" ) def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None: \"\"\"Raises", "cirq.ops import NamedQubit from cirq_pasqal import ThreeDQubit, TwoDQubit, PasqalGateset @cirq.value.value_equality", "for q in qubits: if not isinstance(q, self.supported_qubit_type): raise TypeError(", "qubits must be of same type.\") if len(qubits) > self.maximum_qubit_number:", "cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter for compatibility", "validate_moment(self, moment: cirq.Moment): \"\"\"Raises an error if the given moment", "implied. # See the License for the specific language governing", "Pasqal processors. Modified version of ConvertToNeutralAtomGates, where a new 'convert'", "\"\"\" all_qubits = self.qubit_list() if p not in all_qubits or", "@property def supported_qubit_type(self): return (NamedQubit,) @property def maximum_qubit_number(self): return 100", "q) > self.control_radius: raise ValueError(f\"Qubits {p!r}, {q!r} are too far", "super().validate_moment(moment) if len(moment) > 1: for operation in moment: if", "under the Apache License, Version 2.0 (the \"License\"); # you", "raise ValueError('Got unknown operation:', op) return op in self.gateset def", "cirq.Gateset(cirq.AnyIntegerPowerGateFamily(cirq.CZPowGate)) @property def supported_qubit_type(self): return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def", "op: cirq.Operation) -> bool: if not isinstance(op, cirq.Operation): raise ValueError('Got", "specified device are handled internally by Pasqal. \"\"\" def __init__(self,", "some qubits. Args: qubits (NamedQubit): Qubits on the device, exclusively", "validate. Raises: ValueError: If the operation is not valid. NotImplementedError:", "compute a minimal distance.\") return min([self.distance(q1, q2) for q1 in", "> self.maximum_qubit_number: raise ValueError( 'Too many qubits. {} accepts at", "** 2 + (p.col - q.col) ** 2) if isinstance(p,", "Sequence[cirq.Qid]) -> None: \"\"\"Initializes a device with some qubits. Args:", "position. Must be of type ThreeDQubit, TwoDQubit, LineQubit or GridQubit.", "-> FrozenSet[cirq.Qid]: return frozenset(self.qubits) def qubit_list(self): return [qubit for qubit", "2020 The Cirq Developers # # Licensed under the Apache", "internally by Pasqal. \"\"\" def __init__(self, qubits: Sequence[cirq.Qid]) -> None:", "GridQubit, LineQubit from cirq.ops import NamedQubit from cirq_pasqal import ThreeDQubit,", "3d. A virtual representation of a Pasqal device, enforcing the", "self.controlled_gateset: for p in operation.qubits: for q in operation.qubits: if", "be run on this device \"\"\" super().validate_circuit(circuit) # Measurements must", "3 times' ' the minimal distance between qubits.' ) self.control_radius", "by applicable law or agreed to in writing, software #", "!= (): raise NotImplementedError( \"Measurements on Pasqal devices don't support", "distance between two qubits in qubits. Args: qubits: qubit involved", "Pasqal devices don't support invert_mask.\" ) def validate_circuit(self, circuit: 'cirq.AbstractCircuit')", "License. from typing import FrozenSet, Callable, List, Sequence, Any, Union,", "there is a non-empty moment after a moment with a", "given operation is invalid on this device. Args: operation: The", "of its moments are invalid or if there is a", "minimal distance between two qubits in qubits. Args: qubits: qubit", "has only one qubit Returns: The minimal distance between qubits,", "be in the last non-empty moment has_measurement_occurred = False for", "device, identified by their x, y, z position. Must be", "* self.minimal_distance(): raise ValueError( 'Control_radius cannot be larger than 3", "Raises: ValueError: If the given moment is invalid. \"\"\" super().validate_moment(moment)", "invalid. \"\"\" super().validate_moment(moment) if len(moment) > 1: for operation in", "in all_qubits: raise ValueError(\"Qubit not part of the device.\") if", "def supported_qubit_type(self): return (NamedQubit,) @property def maximum_qubit_number(self): return 100 @property", "for operation in moment: if not isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot", "distance between qubits, in spacial coordinate units. \"\"\" if len(self.qubits)", "Sequence, Any, Union, Dict import numpy as np import networkx", "unknown operation:', op) return op in self.gateset def validate_operation(self, operation:", "operation is valid if operation in self.controlled_gateset: for p in", "device. The most general of Pasqal devices, enforcing only restrictions", "(p.y - q.y) ** 2 + (p.z - q.z) **", "in qubits for b in qubits if a != b])", "[qubit for qubit in self.qubits] def is_pasqal_device_op(self, op: cirq.Operation) ->", "\"\"\" if len(qubits) > 0: q_type = type(qubits[0]) for q", "Cirq Developers # # Licensed under the Apache License, Version", "all optimization and transpilation necessary for its execution on the", "_value_equality_values_(self) -> Any: return (self.control_radius, self.qubits) def _json_dict_(self) -> Dict[str,", "return np.sqrt((p.x - q.x) ** 2 + (p.y - q.y)", "qubits have to be of the type cirq.NamedQubit and assumed", "is invalid if any of its moments are invalid or", "most general of Pasqal devices, enforcing only restrictions expected to", "moment: The moment to validate. Raises: ValueError: If the given", "device with some qubits. Args: qubits (NamedQubit): Qubits on the", "not type(q) is q_type: raise TypeError(\"All qubits must be of", "\"\"\" def __init__( self, control_radius: float, qubits: Sequence[Union[ThreeDQubit, GridQubit, LineQubit]]", "passed into the qubit constructor. qubits: Qubits on the device,", "on the specified device are handled internally by Pasqal. \"\"\"", "identified by their x, y, z position. Must be of", "type.\") if len(qubits) > self.maximum_qubit_number: raise ValueError( 'Too many qubits.", "or if invalid parameter is provided for control_radius.\"\"\" super().__init__(qubits) if", "maximum_qubit_number(self): return 100 @property def metadata(self): return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set()", "import numpy as np import networkx as nx import cirq", "'supports qubit types: {}'.format(q, self.supported_qubit_type) ) if not type(q) is", "qubit for gate {!r}. This ' 'device accepts gates on", "for q2 in self.qubits if q1 != q2]) def distance(self,", "** 2 + (p.z - q.z) ** 2) def __repr__(self):", "qubit involved in the distance computation Raises: ValueError: If the", "len(self.qubits) <= 1: raise ValueError(\"Two qubits to compute a minimal", "qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) def qubit_list(self): return [qubit for", "minimal_distance(self) -> float: \"\"\"Returns the minimal distance between two qubits", "control_radius > 3.0 * self.minimal_distance(): raise ValueError( 'Control_radius cannot be", "# Copyright 2020 The Cirq Developers # # Licensed under", "self.qubits] def is_pasqal_device_op(self, op: cirq.Operation) -> bool: if not isinstance(op,", "'{}'.format(qub, operation.gate, self.supported_qubit_type) ) if qub not in self.metadata.qubit_set: raise", "constructor. qubits: Qubits on the device, identified by their x,", "return (ThreeDQubit, TwoDQubit, GridQubit, LineQubit) def validate_operation(self, operation: cirq.Operation): \"\"\"Raises", "for q1 in self.qubits for q2 in self.qubits if q1", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Any, q: Any) -> float: \"\"\"Returns the distance between two", "all future devices. Serves as the parent class of all", "Unless required by applicable law or agreed to in writing,", "If the number of qubits is greater than the devices", "operation is a measurement with an invert mask. \"\"\" if", "GridQubit, LineQubit) def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error if", "ValueError(\"Non-empty moment after measurement\") for operation in moment.operations: if isinstance(operation.gate,", "layouts will be supported sooner and are thus recommended. Only", "is invalid on this device. Args: operation: the operation to", "the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "+ (p.z - q.z) ** 2) def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r},", "self.supported_qubit_type) ) if not type(q) is q_type: raise TypeError(\"All qubits", "self.qubits def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal", "between qubits p and q. \"\"\" all_qubits = self.qubit_list() if", "moment in circuit: if has_measurement_occurred: if len(moment.operations) > 0: raise", "invalid or if there is a non-empty moment after a", "the specific language governing permissions and # limitations under the", "cirq.NamedQubit and assumed to be all connected, the idea behind", "None: \"\"\"Raises an error if the given circuit is invalid", "circuit can't be run on this device \"\"\" super().validate_circuit(circuit) #", "return TypeError( \"Don't know how to work with {!r}. \"", "a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 #", "cirq.Operation): \"\"\"Raises an error if the given operation is invalid", "qubits, in spacial coordinate units. \"\"\" if len(self.qubits) <= 1:", "pasqal_convert( self, op: cirq.Operation, keep: Callable[[cirq.Operation], bool] ) -> List[cirq.Operation]:", "applicable law or agreed to in writing, software # distributed", "operation to validate Raises: ValueError: If the operation is not", ") def _value_equality_values_(self) -> Any: return (self.control_radius, self.qubits) def _json_dict_(self)", "not control_radius >= 0: raise ValueError('Control_radius needs to be a", "operation is not valid. NotImplementedError: If the operation is a", "thus recommended. Only accepts qubits with physical placement. \"\"\" def", "not in all_qubits: raise ValueError(\"Qubit not part of the device.\")", "copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # #", "processors. Modified version of ConvertToNeutralAtomGates, where a new 'convert' method", "0: raise ValueError('Control_radius needs to be a non-negative float.') if", "operation is invalid on this device. Args: operation: the operation", "self.qubit_list() if p not in all_qubits or q not in", "return (NamedQubit,) @property def maximum_qubit_number(self): return 100 @property def metadata(self):", "not valid. NotImplementedError: If the operation is a measurement with", "-> None: \"\"\"Initializes a device with some qubits. Args: qubits", "representation of a Pasqal device, enforcing the constraints typically found", "in writing, software # distributed under the License is distributed", "devices maximum. \"\"\" if len(qubits) > 0: q_type = type(qubits[0])", "ValueError(f'{qub} is not part of the device.') if isinstance(operation.gate, cirq.MeasurementGate):", "1: if control_radius > 3.0 * self.minimal_distance(): raise ValueError( 'Control_radius", "coordinates passed into the qubit constructor. qubits: Qubits on the", "\"It isn't a native PasqalDevice operation, \" \"a 1 or", "isinstance(op, cirq.Operation): raise ValueError('Got unknown operation:', op) return op in", "run on this device \"\"\" super().validate_circuit(circuit) # Measurements must be", "wrong qubit type is provided or if invalid parameter is", "invalid on this device. Args: operation: the operation to validate", "\"\"\" super().validate_moment(moment) if len(moment) > 1: for operation in moment:", "Callable[[cirq.Operation], bool] ) -> List[cirq.Operation]: def on_stuck_raise(bad): return TypeError( \"Don't", "pylint: enable=missing-raises-doc @property def supported_qubit_type(self): return (NamedQubit,) @property def maximum_qubit_number(self):", "of type ThreeDQubit, TwoDQubit, LineQubit or GridQubit. Raises: ValueError: if", "enable=missing-raises-doc @property def supported_qubit_type(self): return (NamedQubit,) @property def maximum_qubit_number(self): return", "can't be run on this device \"\"\" super().validate_circuit(circuit) # Measurements", "number of qubits is greater than the devices maximum. \"\"\"", "although 2d layouts will be supported sooner and are thus", "only one qubit Returns: The minimal distance between qubits, in", "Verify that a controlled gate operation is valid if operation", "cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class", "TwoDQubit, PasqalGateset @cirq.value.value_equality class PasqalDevice(cirq.devices.Device): \"\"\"A generic Pasqal device. The", "qubits self._metadata = cirq.DeviceMetadata( qubits, nx.from_edgelist([(a, b) for a in", "nx.from_edgelist([(a, b) for a in qubits for b in qubits", "If the given circuit can't be run on this device", "invalid if any of its moments are invalid or if", "devices, enforcing only restrictions expected to be shared by all", "Union, Dict import numpy as np import networkx as nx", "their x, y, z position. Must be of type ThreeDQubit,", "a circuit's device, the qubits have to be of the", "larger than 3 times' ' the minimal distance between qubits.'", "Returns: The distance between qubits p and q. \"\"\" all_qubits", "qubit gate with a known unitary, \" \"or composite.\".format(bad) )", "with some qubits. Args: qubits (NamedQubit): Qubits on the device,", "submission, all optimization and transpilation necessary for its execution on", "idea behind it being that after submission, all optimization and", "optimization and transpilation necessary for its execution on the specified", "qubits: Qubits on the device, identified by their x, y,", "_json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual device", "qub in operation.qubits: if not isinstance(qub, self.supported_qubit_type): raise ValueError( '{}", "= PasqalGateset() self.qubits = qubits self._metadata = cirq.DeviceMetadata( qubits, nx.from_edgelist([(a,", "return min([self.distance(q1, q2) for q1 in self.qubits for q2 in", "len(qubits) > self.maximum_qubit_number: raise ValueError( 'Too many qubits. {} accepts", "the operation is a measurement with an invert mask. \"\"\"", "raise ValueError(\"Non-empty moment after measurement\") for operation in moment.operations: if", "' 'supports qubit types: {}'.format(q, self.supported_qubit_type) ) if not type(q)", "\"\"\"Raises an error if the given moment is invalid on", "a valid qubit for gate {!r}. This ' 'device accepts", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "in moment: if not isinstance(operation.gate, cirq.MeasurementGate): raise ValueError(\"Cannot do simultaneous", "qubits. Args: p: qubit involved in the distance computation q:", "This ' 'device accepts gates on qubits of type: '", "\"\"\"Raises an error if the given circuit is invalid on", "License, Version 2.0 (the \"License\"); # you may not use", "distance between qubits for a controlled gate. Distance is measured", "validate. Raises: ValueError: If the given moment is invalid. \"\"\"", "given moment is invalid. \"\"\" super().validate_moment(moment) if len(moment) > 1:", "qubits (NamedQubit): Qubits on the device, exclusively unrelated to a", "non-empty moment after a moment with a measurement. Args: circuit:", "# You may obtain a copy of the License at", "most {} ' 'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset = PasqalGateset() self.qubits", "not in self.metadata.qubit_set: raise ValueError(f'{qub} is not part of the", "circuit: if has_measurement_occurred: if len(moment.operations) > 0: raise ValueError(\"Non-empty moment", "Pasqal device. The most general of Pasqal devices, enforcing only", "involved in the distance computation q: qubit involved in the", "measured in units of the coordinates passed into the qubit", "on Pasqal devices don't support invert_mask.\" ) def validate_circuit(self, circuit:", "operation: the operation to validate Raises: ValueError: If the operation", "the device, exclusively unrelated to a physical position. Raises: TypeError:", "self.qubits for q2 in self.qubits if q1 != q2]) def", "ValueError( '{} is not a valid qubit for gate {!r}.", "\"Measurements on Pasqal devices don't support invert_mask.\" ) def validate_circuit(self,", "TwoDQubit, LineQubit or GridQubit. Raises: ValueError: if the wrong qubit", "distance computation Raises: ValueError: If the device has only one", "but can also be used on its own for hosting", "being that after submission, all optimization and transpilation necessary for", "to validate. Raises: ValueError: If the operation is not valid.", "the maximum distance between qubits for a controlled gate. Distance", "in units of the coordinates passed into the qubit constructor.", "Args: moment: The moment to validate. Raises: ValueError: If the", "of the device Returns: The distance between qubits p and", "op) return op in self.gateset def validate_operation(self, operation: cirq.Operation): \"\"\"Raises", "can be positioned in 3d space, although 2d layouts will", "is not valid \"\"\" super().validate_operation(operation) # Verify that a controlled", "q not in all_qubits: raise ValueError(\"Qubit not part of the", "@_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate", "operation, \" \"a 1 or 2 qubit gate with a", "between qubits for a controlled gate. Distance is measured in", "a physical position. Raises: TypeError: If the wrong qubit type", "controlled gate operation is valid if operation in self.controlled_gateset: for", "a known unitary, \" \"or composite.\".format(bad) ) return cirq.protocols.decompose( op,", "to validate Raises: ValueError: If the operation is not valid", "after a moment with a measurement. Args: circuit: The circuit", ") class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A gate converter for compatibility with Pasqal", "is q_type: raise TypeError(\"All qubits must be of same type.\")", "raise ValueError(\"Unsupported operation\") if not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is not", "def pasqal_convert( self, op: cirq.Operation, keep: Callable[[cirq.Operation], bool] ) ->", "position. Raises: TypeError: If the wrong qubit type is provided.", "for moment in circuit: if has_measurement_occurred: if len(moment.operations) > 0:", "isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred = True def __repr__(self): return f'pasqal.PasqalDevice(qubits={sorted(self.qubits)!r})' def", "cirq from cirq import _compat, GridQubit, LineQubit from cirq.ops import", "'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates): \"\"\"A", "the License for the specific language governing permissions and #", "is greater than the devices maximum. \"\"\" if len(qubits) >", "np import networkx as nx import cirq from cirq import", "Apache License, Version 2.0 (the \"License\"); # you may not", "(NamedQubit,) @property def maximum_qubit_number(self): return 100 @property def metadata(self): return", "abs(p.x - q.x) return np.sqrt((p.x - q.x) ** 2 +", "either express or implied. # See the License for the", "License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "last non-empty moment has_measurement_occurred = False for moment in circuit:", "the qubit constructor. qubits: Qubits on the device, identified by", "cirq.protocols.decompose( op, keep=keep, intercepting_decomposer=self._convert_one, on_stuck_raise=None if self.ignore_failures else on_stuck_raise, )", "devices don't support invert_mask.\" ) def validate_circuit(self, circuit: 'cirq.AbstractCircuit') ->", "if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]: return frozenset(self.qubits) def", "'keep' function as an input. \"\"\" def pasqal_convert( self, op:", "work with {!r}. \" \"It isn't a native PasqalDevice operation,", "The circuit to validate Raises: ValueError: If the given circuit", "def metadata(self): return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15') def", "ValueError(\"Unsupported operation\") if not self.is_pasqal_device_op(operation): raise ValueError(f'{operation.gate!r} is not a", "in the distance computation Raises: ValueError: If the device has", "must be of same type.\") if len(qubits) > self.maximum_qubit_number: raise", "given circuit can't be run on this device \"\"\" super().validate_circuit(circuit)", "ValueError(\"Cannot do simultaneous gates. Use cirq.InsertStrategy.NEW.\") def minimal_distance(self) -> float:", "None: \"\"\"Initializes a device with some qubits. Args: qubits (NamedQubit):", "is invalid on this device. Args: operation: The operation to", "List, Sequence, Any, Union, Dict import numpy as np import", "device, the qubits have to be of the type cirq.NamedQubit", "Sequence[Union[ThreeDQubit, GridQubit, LineQubit]] ) -> None: \"\"\"Initializes a device with", "if operation.gate.invert_mask != (): raise NotImplementedError( \"Measurements on Pasqal devices", "return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual device with", "to work with {!r}. \" \"It isn't a native PasqalDevice", ") if qub not in self.metadata.qubit_set: raise ValueError(f'{qub} is not", "control_radius.\"\"\" super().__init__(qubits) if not control_radius >= 0: raise ValueError('Control_radius needs", "-> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use", "['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16', fix='Use cirq.optimize_for_target_gateset(circuit, gateset=PasqalGateset()).' ) class PasqalConverter(cirq.neutral_atoms.ConvertToNeutralAtomGates):", "same type.\") if len(qubits) > self.maximum_qubit_number: raise ValueError( 'Too many", "types: {}'.format(q, self.supported_qubit_type) ) if not type(q) is q_type: raise", "execution on the specified device are handled internally by Pasqal.", "found in a physical device. The qubits can be positioned", "is a measurement with an invert mask. \"\"\" if not", "moment is invalid. \"\"\" super().validate_moment(moment) if len(moment) > 1: for", "is invalid. \"\"\" super().validate_moment(moment) if len(moment) > 1: for operation", "on this device. Args: operation: The operation to validate. Raises:", "qubits, nx.from_edgelist([(a, b) for a in qubits for b in", "in all_qubits or q not in all_qubits: raise ValueError(\"Qubit not", "also be used on its own for hosting a nearly", "circuit to validate Raises: ValueError: If the given circuit can't", "def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual", "control_radius: the maximum distance between qubits for a controlled gate.", "ValueError(f\"Qubits {p!r}, {q!r} are too far away\") def validate_moment(self, moment:", "\"\"\" if len(self.qubits) <= 1: raise ValueError(\"Two qubits to compute", "def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an error if the given", "raise ValueError(\"Cannot do simultaneous gates. Use cirq.InsertStrategy.NEW.\") def minimal_distance(self) ->", "coordinate units. \"\"\" if len(self.qubits) <= 1: raise ValueError(\"Two qubits", "ValueError: If p or q not part of the device", "don't support invert_mask.\" ) def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None:", "all_qubits: raise ValueError(\"Qubit not part of the device.\") if isinstance(p,", "q not part of the device Returns: The distance between", "'pasqal_convert' takes the 'keep' function as an input. \"\"\" def", "or if there is a non-empty moment after a moment", "q1 in self.qubits for q2 in self.qubits if q1 !=", "self.metadata.qubit_set: raise ValueError(f'{qub} is not part of the device.') if", "return self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15') def qubit_set(self) ->", "return [qubit for qubit in self.qubits] def is_pasqal_device_op(self, op: cirq.Operation)", "future devices. Serves as the parent class of all Pasqal", "qubits for b in qubits if a != b]) )", "for hosting a nearly unconstrained device. When used as a", "' 'device accepts gates on qubits of type: ' '{}'.format(qub,", "error if the given moment is invalid on this device.", "_json_dict_(self) -> Dict[str, Any]: return cirq.protocols.obj_to_dict_helper(self, ['control_radius', 'qubits']) @_compat.deprecated_class( deadline='v0.16',", "the given circuit is invalid on this device. A circuit", "is provided for control_radius.\"\"\" super().__init__(qubits) if not control_radius >= 0:", "provided for control_radius.\"\"\" super().__init__(qubits) if not control_radius >= 0: raise", "or q not in all_qubits: raise ValueError(\"Qubit not part of", "import FrozenSet, Callable, List, Sequence, Any, Union, Dict import numpy", "for operation in moment.operations: if isinstance(operation.gate, cirq.MeasurementGate): has_measurement_occurred = True", "positioned in 3d space, although 2d layouts will be supported", "recommended. Only accepts qubits with physical placement. \"\"\" def __init__(", "version of ConvertToNeutralAtomGates, where a new 'convert' method 'pasqal_convert' takes", "p: Any, q: Any) -> float: \"\"\"Returns the distance between", "\"License\"); # you may not use this file except in", "\"\"\"Initializes a device with some qubits. Args: control_radius: the maximum", "'convert' method 'pasqal_convert' takes the 'keep' function as an input.", "device with qubits in 3d. A virtual representation of a", "If the given moment is invalid. \"\"\" super().validate_moment(moment) if len(moment)", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "the given moment is invalid. \"\"\" super().validate_moment(moment) if len(moment) >", "moments are invalid or if there is a non-empty moment", "or q not part of the device Returns: The distance", "if the given operation is invalid on this device. Args:", "= self.qubit_list() if p not in all_qubits or q not", "with a measurement. Args: circuit: The circuit to validate Raises:", "Any) -> float: \"\"\"Returns the distance between two qubits. Args:", "type is provided or if invalid parameter is provided for", "as np import networkx as nx import cirq from cirq", "operation in self.controlled_gateset: for p in operation.qubits: for q in", "type(qubits[0]) for q in qubits: if not isinstance(q, self.supported_qubit_type): raise", "\"\"\" super().validate_operation(operation) # Verify that a controlled gate operation is", "# distributed under the License is distributed on an \"AS", "def minimal_distance(self) -> float: \"\"\"Returns the minimal distance between two", "'{} is not a valid qubit for gate {!r}. This", "-> float: \"\"\"Returns the minimal distance between two qubits in", "if isinstance(p, LineQubit): return abs(p.x - q.x) return np.sqrt((p.x -", "# Unless required by applicable law or agreed to in", "qubits to compute a minimal distance.\") return min([self.distance(q1, q2) for", "ValueError('Control_radius needs to be a non-negative float.') if len(self.qubits) >", "-> Any: return (self.control_radius, self.qubits) def _json_dict_(self) -> Dict[str, Any]:", "cirq.Operation): raise ValueError('Got unknown operation:', op) return op in self.gateset", "accepts qubits with physical placement. \"\"\" def __init__( self, control_radius:", "'device accepts gates on qubits of type: ' '{}'.format(qub, operation.gate,", "device, exclusively unrelated to a physical position. Raises: TypeError: If", "on qubits of type: ' '{}'.format(qub, operation.gate, self.supported_qubit_type) ) if", "self._metadata @_compat.deprecated(fix='Use metadata.qubit_set() if applicable.', deadline='v0.15') def qubit_set(self) -> FrozenSet[cirq.Qid]:", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "not valid \"\"\" super().validate_operation(operation) # Verify that a controlled gate", "used as a circuit's device, the qubits have to be", "enforcing the constraints typically found in a physical device. The", "def maximum_qubit_number(self): return 100 @property def metadata(self): return self._metadata @_compat.deprecated(fix='Use", "in self.qubits] def is_pasqal_device_op(self, op: cirq.Operation) -> bool: if not", "class of all Pasqal devices, but can also be used", "in circuit: if has_measurement_occurred: if len(moment.operations) > 0: raise ValueError(\"Non-empty", "qubit Returns: The minimal distance between qubits, in spacial coordinate", "('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits) ) def _value_equality_values_(self) -> Any: return", "or 2 qubit gate with a known unitary, \" \"or", "self, op: cirq.Operation, keep: Callable[[cirq.Operation], bool] ) -> List[cirq.Operation]: def", "A virtual representation of a Pasqal device, enforcing the constraints", "You may obtain a copy of the License at #", "given moment is invalid on this device. Args: moment: The", "maximum. \"\"\" if len(qubits) > 0: q_type = type(qubits[0]) for", "device \"\"\" super().validate_circuit(circuit) # Measurements must be in the last", "\"\"\"Raises an error if the given operation is invalid on", "operation: cirq.Operation): \"\"\"Raises an error if the given operation is", "__repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius, sorted(self.qubits) ) def _value_equality_values_(self) ->", "{p!r}, {q!r} are too far away\") def validate_moment(self, moment: cirq.Moment):", "cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A Pasqal virtual device with qubits", "self.qubits if q1 != q2]) def distance(self, p: Any, q:", "distance computation Raises: ValueError: If p or q not part", "is invalid on this device. A circuit is invalid if", "input. \"\"\" def pasqal_convert( self, op: cirq.Operation, keep: Callable[[cirq.Operation], bool]", "return op in self.gateset def validate_operation(self, operation: cirq.Operation): \"\"\"Raises an", "in operation.qubits: if not isinstance(qub, self.supported_qubit_type): raise ValueError( '{} is", "the Apache License, Version 2.0 (the \"License\"); # you may", "necessary for its execution on the specified device are handled", "ValueError: If the operation is not valid. NotImplementedError: If the", "to validate. Raises: ValueError: If the given moment is invalid.", "- q.z) ** 2) def __repr__(self): return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( self.control_radius,", "' 'qubits.'.format(type(self), self.maximum_qubit_number) ) self.gateset = PasqalGateset() self.qubits = qubits", "min([self.distance(q1, q2) for q1 in self.qubits for q2 in self.qubits", "return self.qubits def _json_dict_(self): return cirq.protocols.obj_to_dict_helper(self, ['qubits']) class PasqalVirtualDevice(PasqalDevice): \"\"\"A", "all_qubits = self.qubit_list() if p not in all_qubits or q", "the given operation is invalid on this device. Args: operation:", "circuit: 'cirq.AbstractCircuit') -> None: \"\"\"Raises an error if the given", "to a physical position. Raises: TypeError: If the wrong qubit", "and # limitations under the License. from typing import FrozenSet,", "def is_pasqal_device_op(self, op: cirq.Operation) -> bool: if not isinstance(op, cirq.Operation):", "TypeError(\"All qubits must be of same type.\") if len(qubits) >", "part of the device Returns: The distance between qubits p" ]
[ "\"%.3f\", } for rlist in reflections: from dials.algorithms.shoebox import MaskCode", "to be true. So we have to reinstatiate # the", "each scan point.\" show_shared_models = False .type = bool .help", "text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if expt.scan is not None: text.append(str(expt.scan)) if", "\"%.4e, %.4e, %.4e\", \"xyzobs.px.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f,", "({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, ) x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px)", "\"\"]) si = col.summed_intensity().observed_value() rows.append( [ \" summed I\", formats.get(k,", "table we're building flag_rows.append( [ indent + flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len),", "expt.scaling_model is not None: text.append(str(expt.scaling_model)) return \"\\n\".join(text) def show_image_statistics(experiments, im_type):", "s += \"Beam centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px),", "(flex.int, flex.size_t): col = col.as_double() rows.append( [ k, formats.get(k, \"%s\")", "= os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data = expt.imageset.get_raw_data(i) else: pnl_data =", "import OrderedSet formats = { \"miller_index\": \"%i, %i, %i\", \"d\":", "\"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\":", "to reinstatiate # the experiment list here try: experiments =", "\"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\",", "\"%\"]] max_count_len = max(5, len(str(max(flag_count.values())))) last_flag = None for flag", "elif isinstance(data, flex.miller_index): c_strings = [ c.as_string(format_strings[i].strip()) for i, c", "] ) fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append( [ \" N valid", "= abc.mean() alpha, beta, gamma = angles.mean() mean_unit_cell = uctbx.unit_cell((a,", "len(rlist))) line = [] for j in range(len(columns)): key =", "xy = [detector[pnl].millimeter_to_pixel(e) for e in xy] x_px, y_px =", "= [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox): x1, x2, y1, y2, z1,", "for k in keys: columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\")", "if panel_id >= 0 and x is not None and", "else: row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return text if len(experiments) ==", "c)) angles.append((alpha, beta, gamma)) a, b, c = abc.mean() alpha,", "= False .type = bool show_centroids = False .type =", "experiment identifiers map if set\" image_statistics{ show_corrected = False .type", "flex.mean(fore_valid), ] ) text.append(tabulate(rows, headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers:", "\"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", }", "y1) * (x2 - x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key +=", "beam_centre_px_str + \"\\n\" if beam_centre_raw_mm_str: s += beam_centre_raw_mm_str + \"\\n\"", "in each corrected image\" show_raw = False .type = bool", "print() print(model_connectivity(experiments)) if len(reflections): print( show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids,", "= [\"\"] text.append(f\"{model.capitalize()}:\") models = getattr(experiments, f\"{model}s\")() rows = [[\"\"]", "= col.bounding_boxes().parts() bbox_sizes = ((z2 - z1) * (y2 -", "beam.get_s0()) beam_centre_raw_px_str = \" px, raw image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px,", "panel = detector[panel_id] x_px, y_px = panel.millimeter_to_pixel((x, y)) offset =", "= \"Show which models are linked to which experiments\" show_all_reflection_data", "detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) ) beam_centre_raw_mm_str = \" mm, raw image:", "if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if params.show_shared_models: print() print(model_connectivity(experiments)) if len(reflections):", "x2, y1, y2, z1, z2 = data.bounding_boxes().parts() bbox_sizes = ((z2", "to pixels xy = [detector[pnl].millimeter_to_pixel(e) for e in xy] x_px,", "s += \" s0 sampled at \" + str(beam.num_scan_points) +", "\"\\nBeam centre: \\n\" s += beam_centre_mm_str + \"\\n\" + beam_centre_px_str", "on the distribution of values in each corrected image\" show_raw", "in pnl_data[1:]: flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data) print( \"{}: Min: {:.1f}", "e in enumerate(experiments): row = [\"Experiment %d\" % j] for", ") text.append( \"Max resolution (inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\")", "parser = OptionParser( usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message,", "text.append(f\"Image template: {template}\") text.append(str(expt.detector)) text.append( \"Max resolution (at corners): %f\"", "\"max\", \"mean\"]] for k, col in rlist.cols(): if k in", "table of reflection flags\" show_identifiers = False .type = bool", "OrderedSet() if show_intensities: for k in intensity_keys: keys_to_print.add(k) if show_profile_fit:", "\"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\",", "px: panel %i, (%.2f,%.2f)\" % ( panel_id, x_px, y_px, )", "= [k for k in keys_to_print if k in rlist]", ".help = \"Show experiment identifiers map if set\" image_statistics{ show_corrected", "({x:.2f},{y:.2f})\" beam_centre_px_str = f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str", "model) is m: row.append(\"x\") else: row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return", "\"shoebox\": key += \" (N pix)\" width = max(len(key), columns[j].max_element_length())", "flex.shoebox): rows.append([k, \"\", \"\", \"\"]) si = col.summed_intensity().observed_value() rows.append( [", "{ flag: np.sum(numpy_flags & value != 0) for value, flag", "and len(reflections) == 0: parser.print_help() exit() if len(experiments): if not", "*fns ) ) def model_connectivity(experiments): def model_connectivity_impl(experiments, model): text =", "flag_order = sorted(table.flags.values.values(), key=lambda x: x.real) # Build the actual", "ExperimentListFactory.from_json( experiments.as_json(), check_format=True ) except OSError as e: raise Sorry(", "\"Whether or not to show the crystal at each scan", "which experiments\" show_all_reflection_data = False .type = bool .help =", "\"s1\": \"%.4f, %.4f, %.4f\", \"s2\": \"%.4f, %.4f, %.4f\", \"shoebox\": \"%.1f\",", "x2, y1, y2, z1, z2 = col.bounding_boxes().parts() bbox_sizes = ((z2", "from dials.array_family import flex from dials.util import Sorry, tabulate help_message", "text.append(\"\") text.append(\"Printing %i of %i reflections:\" % (max_reflections, len(rlist))) line", "\"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\", \"xyzobs.px.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f,", "from dials.util import Sorry, tabulate help_message = \"\"\" Examples:: dials.show", "% flex.max(bbox_sizes), formats.get(k, \"%s\") % flex.mean(bbox_sizes), ] ) fore_valid =", "x, y = panel.get_ray_intersection(s0) except RuntimeError: continue else: if panel.is_coord_valid_mm((x,", "at \" + str(goniometer.num_scan_points) + \" scan points\\n\" ) return", "% flex.min(si), formats.get(k, \"%s\") % flex.max(si), formats.get(k, \"%s\") % flex.mean(si),", "print individual reflections\" show_intensities = False .type = bool show_centroids", "phil_scope = iotbx.phil.parse( \"\"\"\\ show_scan_varying = False .type = bool", "image_*.cbf\" parser = OptionParser( usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False,", "+ flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 * flag_count[flag] / len(table):5.01f}\", ]", "> 0: # get scan-varying beam centres, ensuring all on", "with the previous one. if last_flag and (last_flag.real & flag.real):", "\"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\", \"partiality\": \"%.4f\",", "data.bounding_boxes().parts() bbox_sizes = ((z2 - z1) * (y2 - y1)", "expt in enumerate(experiments): for i in range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i))", "in keys_to_print if k in rlist] if max_reflections is not", "overlaps with the previous one. if last_flag and (last_flag.real &", "x, y) beam_centre_px_str = \" px: panel %i, (%.2f,%.2f)\" %", "\"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate", "in c_strings] for i in range(len(c_strings[0])): column.append( f\"%{len(key)}s\" % \",", "list contains {len(rlist)} reflections\") if len(rlist) == 0: continue rows", "from dxtbx.model.experiment_list import ExperimentListFactory from scitbx.math import five_number_summary import dials.util", "False .type = bool .help = \"Show statistics on the", "x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y)) if len(detector) > 1: beam_centre_mm_str", "in enumerate(experiments): for i in range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if", "show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False, ): text = [] from orderedset", "except AttributeError: template = None if template: text.append(f\"Image template: {template}\")", "\"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print", "{im_type}\") # To show image statistics, check_format has to be", "\"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\", \"xyzobs.px.value\":", "\"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\":", "def beam_centre_mm(detector, s0): x, y = (None, None) for panel_id,", "to show the crystal at each scan point.\" show_shared_models =", "- y1) * (x2 - x1)).as_double() rows.append( [ \" N", "output strings text = [] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return", "beam_centre_mm(detector, s0) panel = detector[panel_id] x_px, y_px = panel.millimeter_to_pixel((x, y))", "in range(expt.crystal.num_scan_points): ( a, b, c, alpha, beta, gamma, )", "beam_centre_mm_str + \"\\n\" + beam_centre_px_str + \"\\n\" if beam_centre_raw_mm_str: s", "row = [\"Experiment %d\" % j] for m in models:", "model beam centres if beam.num_scan_points > 0: # get scan-varying", "Min: {:.1f} Q1: {:.1f} Med: {:.1f} Q3: {:.1f} Max: {:.1f}\".format(", "import sys import numpy as np import iotbx.phil from cctbx", "} max_reflections = None .type = int .help = \"Limit", "{ \"miller_index\": \"%i, %i, %i\", \"d\": \"%.2f\", \"qe\": \"%.3f\", \"dqe\":", "if beam_centre_raw_mm_str: s += beam_centre_raw_mm_str + \"\\n\" if beam_centre_raw_px_str: s", "None: x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y)) if len(detector) > 1:", "\"d\") centroid_keys = ( \"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\",", "x_mm, y_mm = zip(*xy) # convert to pixels xy =", "if not all(e.beam for e in experiments): sys.exit(\"Error: experiment has", "no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected:", "\"id\": \"%i\", \"imageset_id\": \"%i\", \"panel\": \"%i\", \"flags\": \"%i\", \"background.mean\": \"%.1f\",", "beam_centre_raw_px_str: s += beam_centre_raw_px_str + \"\\n\" # report range of", "s += ( \" Setting rotation sampled at \" +", "\"%s\"), ] ) elif type(col) in (flex.double, flex.int, flex.size_t): if", "for value, flag in table.flags.values.items() } # Work out the", "i in range(max_reflections): line = (c[i] for c in columns)", "A reflection table :returns: A string of the formatted flags", "0 and len(reflections) == 0: parser.print_help() exit() if len(experiments): if", "show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) ) def", "panel_id, (x, y) = beam_centre_mm(detector, beam.get_s0()) if panel_id >= 0", ".type = bool .help = \"Show experiment identifiers map if", "values in each corrected image\" show_raw = False .type =", "except OSError as e: raise Sorry( f\"Unable to read image", "flex.min(fore_valid), formats.get(k, \"%s\") % flex.max(fore_valid), formats.get(k, \"%s\") % flex.mean(fore_valid), ]", "uctbx from dxtbx.model.experiment_list import ExperimentListFactory from scitbx.math import five_number_summary import", "(c[i] for c in columns) text.append(\" \".join(line)) return \"\\n\".join(text) if", "five_number_summary(flat_data) print( \"{}: Min: {:.1f} Q1: {:.1f} Med: {:.1f} Q3:", "= parser.parse_args(args=args, show_diff_phil=True) reflections, experiments = reflections_and_experiments_from_files( params.input.reflections, params.input.experiments )", "To show image statistics, check_format has to be true. So", "Build the actual table flag_rows = [[\"Flag\", \"Count\", \"%\"]] max_count_len", "x, y = (None, None) return panel_id, (x, y) def", "elif type(col) in (flex.vec3_double, flex.miller_index): if isinstance(col, flex.miller_index): col =", "show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if", "%i, (%.2f,%.2f)\" % (panel_id, x, y) beam_centre_px_str = \" px:", "# Build the actual table flag_rows = [[\"Flag\", \"Count\", \"%\"]]", "in rlist] if max_reflections is not None: max_reflections = min(len(rlist),", "else: x, y = (None, None) return panel_id, (x, y)", "for e in xy] x_px, y_px = zip(*xy) s +=", "[ indent + flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 * flag_count[flag] /", "which models are linked to which experiments\" show_all_reflection_data = False", "\"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", } for rlist in reflections: from", "OptionParser, reflections_and_experiments_from_files usage = \"dials.show [options] models.expt | image_*.cbf\" parser", "or not to print individual reflections\" show_intensities = False .type", "\"\"\"Experiment identifiers id-map values:\\n%s\"\"\" % ( \"\\n\".join( \"id:\" + str(k)", "show_reflections( reflections, show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False, ):", "except RuntimeError: continue else: if panel.is_coord_valid_mm((x, y)): break else: x,", "offset[0], y_px + offset[1] def show_beam(detector, beam): # standard static", "model string s = str(goniometer) # report whether the goniometer", "%.2f, %.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f,", "print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\")", "<reponame>huwjenkins/dials import os import sys import numpy as np import", "text.append(str(expt.profile)) if expt.scaling_model is not None: text.append(str(expt.scaling_model)) return \"\\n\".join(text) def", "as np import iotbx.phil from cctbx import uctbx from dxtbx.model.experiment_list", "mm: panel %i, (%.2f,%.2f)\" % (panel_id, x, y) beam_centre_px_str =", "centroid_keys: keys_to_print.add(k) if show_all_reflection_data: for k in formats: keys_to_print.add(k) def", "models: if getattr(e, model) is m: row.append(\"x\") else: row.append(\".\") rows.append(row)", "[bbox_sizes.as_string(format_strings[0].strip())] key += \" (N pix)\" else: c_strings = [data.as_string(format_strings[0].strip())]", "offset = panel.get_raw_image_offset() return x_px + offset[0], y_px + offset[1]", "bool .help = \"Whether or not to print individual reflections\"", "the array of output strings text = [] text.append(\"Reflection flags:\")", "models = getattr(experiments, f\"{model}s\")() rows = [[\"\"] + [str(j) for", "\"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f, %.2f\", \"xyzcal.px\": \"%.2f, %.2f, %.2f\", \"delpsical.rad\":", "beam_centre_raw_mm_str: s += beam_centre_raw_mm_str + \"\\n\" if beam_centre_raw_px_str: s +=", "formats: keys_to_print.add(k) def format_column(key, data, format_strings=None): if isinstance(data, flex.vec3_double): c_strings", "out of entries that wouldn't make sense rows.append( [ k,", "if isinstance(data, flex.vec3_double): c_strings = [ c.as_string(format_strings[i].strip()) for i, c", "if beam.num_scan_points > 0: # get scan-varying beam centres, ensuring", "scan-varying if goniometer.num_scan_points > 0: s += ( \" Setting", "c.as_string(format_strings[i].strip()) for i, c in enumerate(data.parts()) ] elif isinstance(data, flex.miller_index):", "flex.mean(si), ] ) x1, x2, y1, y2, z1, z2 =", "\"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\":", "flag numpy_flags = table[\"flags\"].as_numpy_array() flag_count = { flag: np.sum(numpy_flags &", ") x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str = \" px,", "c_strings = [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox): x1, x2, y1, y2,", "max_reflections = min(len(rlist), max_reflections) else: max_reflections = len(rlist) columns =", ") return s def show_goniometer(goniometer): # standard static goniometer model", "s0 in sv_s0] pnl, xy = zip(*impacts) uniq_pnls = set(pnl)", "\"xyzobs.px.variance\", ) keys_to_print = OrderedSet() if show_intensities: for k in", "( \"\\n\".join( \"id:\" + str(k) + \" -> experiment identifier:\"", "value != 0) for value, flag in table.flags.values.items() } #", "sense rows.append( [ k, formats.get(k, \"%s\"), formats.get(k, \"%s\"), formats.get(k, \"%s\"),", "!= \"\": text.append(f\"Experiment identifier: {expt.identifier}\") try: template = expt.imageset.get_template() except", "flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 * flag_count[flag] / len(table):5.01f}\", ] )", "= bool show_flags = False .type = bool .help =", "\"%.2f, %.2f, %.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\":", "Add the row to the table we're building flag_rows.append( [", "\"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate a summary", "\"%.4f, %.4f, %.4f\", \"s2\": \"%.4f, %.4f, %.4f\", \"shoebox\": \"%.1f\", \"rlp\":", "else: raise ValueError(f\"Unknown im_type: {im_type}\") # To show image statistics,", "for n in range(expt.crystal.num_scan_points): ( a, b, c, alpha, beta,", "os import sys import numpy as np import iotbx.phil from", "\"\\n\" + beam_centre_px_str + \"\\n\" if beam_centre_raw_mm_str: s += beam_centre_raw_mm_str", "(expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if expt.scan is not None:", "fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append( [ \" N valid foreground pix\",", "blanking out of entries that wouldn't make sense rows.append( [", "out the numeric-value order of the flags flag_order = sorted(table.flags.values.values(),", "None if template: text.append(f\"Image template: {template}\") text.append(str(expt.detector)) text.append( \"Max resolution", "beam.get_s0()) if panel_id >= 0 and x is not None", "in formats.get(k, \"%s\"): # Allow blanking out of entries that", "for panel_id, panel in enumerate(detector): try: x, y = panel.get_ray_intersection(s0)", "keys[j] if key == \"shoebox\": key += \" (N pix)\"", "if set\" image_statistics{ show_corrected = False .type = bool .help", "on the distribution of values in each raw image\" }", "\" Setting rotation sampled at \" + str(goniometer.num_scan_points) + \"", "\"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", } for rlist in reflections:", "\"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", } for rlist in reflections: from dials.algorithms.shoebox", "] elif isinstance(data, flex.miller_index): c_strings = [ c.as_string(format_strings[i].strip()) for i,", "impacts = [beam_centre_mm(detector, s0) for s0 in sv_s0] pnl, xy", "model): text = [\"\"] text.append(f\"{model.capitalize()}:\") models = getattr(experiments, f\"{model}s\")() rows", "rows.append( [ k, formats.get(k, \"%s\") % flex.min(col), formats.get(k, \"%s\") %", "if show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers: if rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers", "# Work out the numeric-value order of the flags flag_order", "= False .type = bool .help = \"Show experiment identifiers", "%.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\", \"xyzobs.px.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\":", "False else: raise ValueError(f\"Unknown im_type: {im_type}\") # To show image", "if params.show_shared_models: print() print(model_connectivity(experiments)) if len(reflections): print( show_reflections( reflections, show_intensities=params.show_intensities,", "show_identifiers=params.show_identifiers, ) ) def show_experiments(experiments, show_scan_varying=False): text = [] for", "flags table \"\"\" # Calculate the counts of entries that", "identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data = expt.imageset.get_raw_data(i) else: pnl_data", "formats.get(k, \"%s\") % flex.max(bbox_sizes), formats.get(k, \"%s\") % flex.mean(bbox_sizes), ] )", "\"%i, %i, %i\", \"d\": \"%.2f\", \"qe\": \"%.3f\", \"dqe\": \"%.3f\", \"id\":", "numeric-value order of the flags flag_order = sorted(table.flags.values.values(), key=lambda x:", "enumerate(experiments): row = [\"Experiment %d\" % j] for m in", "= beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str = \" px, raw image: ({:.2f},{:.2f})\".format(", "( \"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\",", "formats.get(k, \"%s\") % flex.max(fore_valid), formats.get(k, \"%s\") % flex.mean(fore_valid), ] )", "s0): x, y = (None, None) for panel_id, panel in", "else: pnl_data = expt.imageset.get_corrected_data(i) if not isinstance(pnl_data, tuple): pnl_data =", "in experiments): sys.exit(\"Error: experiment has no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if", "is not None: max_reflections = min(len(rlist), max_reflections) else: max_reflections =", ") elif type(col) in (flex.double, flex.int, flex.size_t): if type(col) in", "flex from dials.util import Sorry, tabulate help_message = \"\"\" Examples::", "continue rows = [[\"Column\", \"min\", \"max\", \"mean\"]] for k, col", "max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) ) def show_experiments(experiments, show_scan_varying=False): text = []", "text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate a", "[detector[pnl].millimeter_to_pixel(e) for e in xy] x_px, y_px = zip(*xy) s", "= bool .help = \"Show a summary table of reflection", "reflections:\" % (max_reflections, len(rlist))) line = [] for j in", "max_reflections is not None: max_reflections = min(len(rlist), max_reflections) else: max_reflections", "y_raw_px) ) beam_centre_raw_mm_str = \" mm, raw image: ({:.2f},{:.2f})\".format( x_raw_mm,", "def show_goniometer(goniometer): # standard static goniometer model string s =", "distribution of values in each corrected image\" show_raw = False", "expt.crystal.num_scan_points: abc = flex.vec3_double() angles = flex.vec3_double() for n in", "columns = [] for k in keys: columns.append( format_column(k, rlist[k],", "= detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) ) beam_centre_raw_mm_str = \" mm, raw", "dials.show observations.refl \"\"\" phil_scope = iotbx.phil.parse( \"\"\"\\ show_scan_varying = False", ") except OSError as e: raise Sorry( f\"Unable to read", "MaskCode.Valid | MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list contains {len(rlist)} reflections\") if", "at \" + str(beam.num_scan_points) + \" scan points\\n\" # add", "the number of reflections in the output.\" \"\"\", process_includes=True, )", "# To show image statistics, check_format has to be true.", "distribution of values in each raw image\" } max_reflections =", "\"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\":", "= panel.get_ray_intersection(s0) except RuntimeError: continue else: if panel.is_coord_valid_mm((x, y)): break", "\"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 * flag_count[flag] / len(table):5.01f}\", ] ) #", "\"%s\") % flex.min(bbox_sizes), formats.get(k, \"%s\") % flex.max(bbox_sizes), formats.get(k, \"%s\") %", "[[\"Flag\", \"Count\", \"%\"]] max_count_len = max(5, len(str(max(flag_count.values())))) last_flag = None", "panel.get_raw_image_offset() return x_px + offset[0], y_px + offset[1] def show_beam(detector,", "for k in rlist.experiment_identifiers().keys() ) ) ) intensity_keys = (", "j] for m in models: if getattr(e, model) is m:", "max_reflections=None, show_identifiers=False, ): text = [] from orderedset import OrderedSet", "in formats: keys_to_print.add(k) def format_column(key, data, format_strings=None): if isinstance(data, flex.vec3_double):", "= bool .help = \"Show statistics on the distribution of", "beta, gamma)) text.append(f\" Average unit cell: {mean_unit_cell}\") if expt.profile is", "(x, y) def beam_centre_raw_image_px(detector, s0): panel_id, (x, y) = beam_centre_mm(detector,", "OrderedSet formats = { \"miller_index\": \"%i, %i, %i\", \"d\": \"%.2f\",", "\"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys =", "pnl_data = expt.imageset.get_raw_data(i) else: pnl_data = expt.imageset.get_corrected_data(i) if not isinstance(pnl_data,", "type(col) in (flex.double, flex.int, flex.size_t): if type(col) in (flex.int, flex.size_t):", ".type = bool .help = \"Show which models are linked", "of output strings text = [] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\"))", "z1, z2 = col.bounding_boxes().parts() bbox_sizes = ((z2 - z1) *", "c in enumerate(data.as_vec3_double().parts()) ] elif isinstance(data, flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())]", "foreground pix\", formats.get(k, \"%s\") % flex.min(fore_valid), formats.get(k, \"%s\") % flex.max(fore_valid),", "column.append( f\"%{len(key)}s\" % \", \".join( (\"%%%is\" % max_element_lengths[j]) % c_strings[j][i]", "> 1 or min(uniq_pnls) < 0: return s if any(e", "read image data. Please check {e.filename} is accessible\" ) print(f\"Five", "in flag_order: indent = \"\" # As a hint for", "f\"{model}s\")() rows = [[\"\"] + [str(j) for j in range(len(models))]]", "| MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list contains {len(rlist)} reflections\") if len(rlist)", "range(len(columns)): key = keys[j] if key == \"shoebox\": key +=", "expt.identifier != \"\": text.append(f\"Experiment identifier: {expt.identifier}\") try: template = expt.imageset.get_template()", "= \"Whether or not to print individual reflections\" show_intensities =", "> 1: beam_centre_mm_str = \" mm: panel %i, (%.2f,%.2f)\" %", "False .type = bool .help = \"Show experiment identifiers map", "\"%s\") % flex.max(col), formats.get(k, \"%s\") % flex.mean(col), ] ) elif", "j in range(len(models))]] for j, e in enumerate(experiments): row =", "\"%.3f\", \"dqe\": \"%.3f\", \"id\": \"%i\", \"imageset_id\": \"%i\", \"panel\": \"%i\", \"flags\":", "of entries that match each flag numpy_flags = table[\"flags\"].as_numpy_array() flag_count", ".help = \"Whether or not to print individual reflections\" show_intensities", "< 0: return s if any(e == (None, None) for", ") text.append(\"\") text.append(\"Printing %i of %i reflections:\" % (max_reflections, len(rlist)))", "max(y_px), ) return s def show_goniometer(goniometer): # standard static goniometer", "None: text.append(str(expt.profile)) if expt.scaling_model is not None: text.append(str(expt.scaling_model)) return \"\\n\".join(text)", "\"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\", \"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\":", "% key) text.append(\" \".join(line)) for i in range(max_reflections): line =", "+ \" scan points\\n\" ) return s @dials.util.show_mail_handle_errors() def run(args=None):", "import Sorry, tabulate help_message = \"\"\" Examples:: dials.show models.expt dials.show", "alpha, beta, gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c)) angles.append((alpha,", "range(expt.crystal.num_scan_points): ( a, b, c, alpha, beta, gamma, ) =", "\"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f, %.2f\", \"xyzcal.px\": \"%.2f,", "tabulate help_message = \"\"\" Examples:: dials.show models.expt dials.show image_*.cbf dials.show", "if goniometer.num_scan_points > 0: s += ( \" Setting rotation", "\\n\" s += beam_centre_mm_str + \"\\n\" + beam_centre_px_str + \"\\n\"", "raise Sorry( f\"Unable to read image data. Please check {e.filename}", "in profile_fit_keys: keys_to_print.add(k) if show_centroids: for k in centroid_keys: keys_to_print.add(k)", "\"{}: Min: {:.1f} Q1: {:.1f} Med: {:.1f} Q3: {:.1f} Max:", "\"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys = (\"miller_index\",", "+= \"Beam centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm), max(y_mm),", "for i in range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data", "raw: pnl_data = expt.imageset.get_raw_data(i) else: pnl_data = expt.imageset.get_corrected_data(i) if not", "return s def show_goniometer(goniometer): # standard static goniometer model string", "k in formats: keys_to_print.add(k) def format_column(key, data, format_strings=None): if isinstance(data,", "import iotbx.phil from cctbx import uctbx from dxtbx.model.experiment_list import ExperimentListFactory", ") x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) ) beam_centre_raw_mm_str =", "s += beam_centre_raw_mm_str + \"\\n\" if beam_centre_raw_px_str: s += beam_centre_raw_px_str", "not None: text.append(str(expt.scan)) if expt.goniometer is not None: text.append(show_goniometer(expt.goniometer)) if", "of flag values in a reflection table. :param table: A", "\" + str(goniometer.num_scan_points) + \" scan points\\n\" ) return s", "\"%.2f\", \"qe\": \"%.3f\", \"dqe\": \"%.3f\", \"id\": \"%i\", \"imageset_id\": \"%i\", \"panel\":", "str(beam) # report whether the beam is scan-varying if beam.num_scan_points", "= str(beam) # report whether the beam is scan-varying if", "\"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\":", "show_profile_fit: for k in profile_fit_keys: keys_to_print.add(k) if show_centroids: for k", "s += beam_centre_mm_str + \"\\n\" + beam_centre_px_str + \"\\n\" if", "c = abc.mean() alpha, beta, gamma = angles.mean() mean_unit_cell =", "static beam model string s = str(beam) # report whether", "value, flag in table.flags.values.items() } # Work out the numeric-value", "beam_centre_raw_mm_str = \"\" s += \"\\nBeam centre: \\n\" s +=", "raw image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, ) x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter(", "dials.show image_*.cbf dials.show observations.refl \"\"\" phil_scope = iotbx.phil.parse( \"\"\"\\ show_scan_varying", "not None: x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y)) if len(detector) >", "text.append(show_goniometer(expt.goniometer)) if expt.crystal is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc", "\"\\n\".join(text) def show_reflections( reflections, show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None,", "image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, ) else: beam_centre_mm_str = f\" mm:", "= False .type = bool .help = \"Show statistics on", "0: continue rows = [[\"Column\", \"min\", \"max\", \"mean\"]] for k,", "text.append( \"Max resolution (inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector,", "= False else: raise ValueError(f\"Unknown im_type: {im_type}\") # To show", "for i, c in enumerate(data.parts()) ] elif isinstance(data, flex.miller_index): c_strings", "\"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\",", ") beam_centre_raw_mm_str = \" mm, raw image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm,", "not all(e.detector for e in experiments): sys.exit(\"Error: experiment has no", "report range of scan-varying model beam centres if beam.num_scan_points >", "\"Beam centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px), max(y_px), )", "\"\" s += \"\\nBeam centre: \\n\" s += beam_centre_mm_str +", "pnl_data[1:]: flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data) print( \"{}: Min: {:.1f} Q1:", "flag_count = { flag: np.sum(numpy_flags & value != 0) for", "gamma)) a, b, c = abc.mean() alpha, beta, gamma =", "[[\"Column\", \"min\", \"max\", \"mean\"]] for k, col in rlist.cols(): if", "%i\", \"d\": \"%.2f\", \"qe\": \"%.3f\", \"dqe\": \"%.3f\", \"id\": \"%i\", \"imageset_id\":", "= ( \"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\",", "x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key += \" (N pix)\" else:", "\"%i\", \"panel\": \"%i\", \"flags\": \"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\":", "width % key) text.append(\" \".join(line)) for i in range(max_reflections): line", "expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c)) angles.append((alpha, beta, gamma)) a, b, c", "x_px, y_px = zip(*xy) s += \"Beam centre range (mm):", "from scitbx.math import five_number_summary import dials.util from dials.array_family import flex", "identifier: {expt.identifier}\") try: template = expt.imageset.get_template() except AttributeError: template =", "% flex.max(fore_valid), formats.get(k, \"%s\") % flex.mean(fore_valid), ] ) text.append(tabulate(rows, headers=\"firstrow\"))", "%.4f, %.4f\", \"zeta\": \"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\",", "a, b, c, alpha, beta, gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a,", "the distribution of values in each corrected image\" show_raw =", "parser.print_help() exit() if len(experiments): if not all(e.detector for e in", "(max_reflections, len(rlist))) line = [] for j in range(len(columns)): key", "= [] for k in keys: columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\"))", "in range(len(c_strings[0])): column.append( f\"%{len(key)}s\" % \", \".join( (\"%%%is\" % max_element_lengths[j])", "Allow blanking out of entries that wouldn't make sense rows.append(", ".type = bool show_profile_fit = False .type = bool show_flags", "c, alpha, beta, gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c))", "if beam_centre_raw_px_str: s += beam_centre_raw_px_str + \"\\n\" # report range", "= [beam_centre_mm(detector, s0) for s0 in sv_s0] pnl, xy =", "\"raw\": raw = True elif im_type == \"corrected\": raw =", "\" mm, raw image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, ) else: beam_centre_mm_str", "alpha, beta, gamma)) text.append(f\" Average unit cell: {mean_unit_cell}\") if expt.profile", "params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if params.show_shared_models: print()", "gamma = angles.mean() mean_unit_cell = uctbx.unit_cell((a, b, c, alpha, beta,", "x1, x2, y1, y2, z1, z2 = data.bounding_boxes().parts() bbox_sizes =", "min(y_px), max(y_px), ) return s def show_goniometer(goniometer): # standard static", "all(e.beam for e in experiments): sys.exit(\"Error: experiment has no beam\")", "# the experiment list here try: experiments = ExperimentListFactory.from_json( experiments.as_json(),", "beam_centre_px_str = \" px: panel %i, (%.2f,%.2f)\" % ( panel_id,", "raw image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, ) else: beam_centre_mm_str = f\"", "{:.1f} Max: {:.1f}\".format( identifier, *fns ) ) def model_connectivity(experiments): def", "headers=\"firstrow\")) return \"\\n\".join(text) def show_reflections( reflections, show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False,", "column if keys_to_print: keys = [k for k in keys_to_print", "y)) if len(detector) > 1: beam_centre_mm_str = \" mm: panel", "centres panel_id, (x, y) = beam_centre_mm(detector, beam.get_s0()) if panel_id >=", "in range(len(columns)): key = keys[j] if key == \"shoebox\": key", "== \"shoebox\": key += \" (N pix)\" width = max(len(key),", "table :returns: A string of the formatted flags table \"\"\"", "flag # Add the row to the table we're building", "len(detector) > 1: beam_centre_mm_str = \" mm: panel %i, (%.2f,%.2f)\"", "show_diff_phil=True) reflections, experiments = reflections_and_experiments_from_files( params.input.reflections, params.input.experiments ) if len(experiments)", "raw = False else: raise ValueError(f\"Unknown im_type: {im_type}\") # To", "z1, z2 = data.bounding_boxes().parts() bbox_sizes = ((z2 - z1) *", "of %i reflections:\" % (max_reflections, len(rlist))) line = [] for", "(None, None) for panel_id, panel in enumerate(detector): try: x, y", "\"Format\": text.append(f\"Format class: {format_class.__name__}\") if expt.identifier != \"\": text.append(f\"Experiment identifier:", "col.count_mask_values(foreground_valid).as_double() rows.append( [ \" N valid foreground pix\", formats.get(k, \"%s\")", "{:.1f} Q3: {:.1f} Max: {:.1f}\".format( identifier, *fns ) ) def", "i, c in enumerate(data.parts()) ] elif isinstance(data, flex.miller_index): c_strings =", "\"id:\" + str(k) + \" -> experiment identifier:\" + str(rlist.experiment_identifiers()[k])", "flags\" show_identifiers = False .type = bool .help = \"Show", "f\"Unable to read image data. Please check {e.filename} is accessible\"", "panel_id >= 0 and x is not None and y", "pnl_data = expt.imageset.get_corrected_data(i) if not isinstance(pnl_data, tuple): pnl_data = (pnl_data,)", "the counts of entries that match each flag numpy_flags =", ") # Build the array of output strings text =", "\"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f, %.2f\", \"xyzcal.px\":", "experiment has no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\")", "beam_centre_raw_image_px(detector, s0): panel_id, (x, y) = beam_centre_mm(detector, s0) panel =", "\"\"\" phil_scope = iotbx.phil.parse( \"\"\"\\ show_scan_varying = False .type =", "# report whether the goniometer is scan-varying if goniometer.num_scan_points >", "= f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str = \"\"", "raise ValueError(f\"Unknown im_type: {im_type}\") # To show image statistics, check_format", "key) text.append(\" \".join(line)) for i in range(max_reflections): line = (c[i]", "of reflection flags\" show_identifiers = False .type = bool .help", "y) beam_centre_px_str = \" px: panel %i, (%.2f,%.2f)\" % (", "\" last_flag = flag # Add the row to the", "building flag_rows.append( [ indent + flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 *", "max_count_len), f\"{100 * flag_count[flag] / len(table):5.01f}\", ] ) # Build", ".type = int .help = \"Limit the number of reflections", "epilog=help_message, ) params, options = parser.parse_args(args=args, show_diff_phil=True) reflections, experiments =", "if k in formats and \"%\" not in formats.get(k, \"%s\"):", "= (c[i] for c in columns) text.append(\" \".join(line)) return \"\\n\".join(text)", "print(model_connectivity(experiments)) if len(reflections): print( show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data,", "[] text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\"))", "pix)\" width = max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" % width % key)", "= [[\"Flag\", \"Count\", \"%\"]] max_count_len = max(5, len(str(max(flag_count.values())))) last_flag =", "abc.mean() alpha, beta, gamma = angles.mean() mean_unit_cell = uctbx.unit_cell((a, b,", "max(x_mm), min(y_mm), max(y_mm), ) s += \"Beam centre range (px):", "b, c = abc.mean() alpha, beta, gamma = angles.mean() mean_unit_cell", "params.input.reflections, params.input.experiments ) if len(experiments) == 0 and len(reflections) ==", "text.append(f\"{model.capitalize()}:\") models = getattr(experiments, f\"{model}s\")() rows = [[\"\"] + [str(j)", "+ offset[0], y_px + offset[1] def show_beam(detector, beam): # standard", "not None and y is not None: x_px, y_px =", "\"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\",", "%.4f, %.4f\", \"s2\": \"%.4f, %.4f, %.4f\", \"shoebox\": \"%.1f\", \"rlp\": \"%.4f,", "I\", formats.get(k, \"%s\") % flex.min(si), formats.get(k, \"%s\") % flex.max(si), formats.get(k,", "isinstance(pnl_data, tuple): pnl_data = (pnl_data,) flat_data = pnl_data[0].as_1d() for p", "% col.max(), formats.get(k, \"%s\") % col.mean(), ] ) elif isinstance(col,", "values in each raw image\" } max_reflections = None .type", "max(5, len(str(max(flag_count.values())))) last_flag = None for flag in flag_order: indent", "x_raw_px, y_raw_px, ) x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) )", "beta, gamma = angles.mean() mean_unit_cell = uctbx.unit_cell((a, b, c, alpha,", "beam centres, ensuring all on same panel sv_s0 = beam.get_s0_at_scan_points()", "isinstance(data, flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox): x1, x2,", "type(col) in (flex.int, flex.size_t): col = col.as_double() rows.append( [ k,", "in rlist.experiment_identifiers().keys() ) ) ) intensity_keys = ( \"miller_index\", \"d\",", "return \"\" text = [] text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments, \"detector\"))", "in range(max_reflections): line = (c[i] for c in columns) text.append(\"", "\"rlp\": \"%.4f, %.4f, %.4f\", \"zeta\": \"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\",", ".help = \"Show a summary table of reflection flags\" show_identifiers", "centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm), max(y_mm), ) s", "\" scan points\\n\" ) return s @dials.util.show_mail_handle_errors() def run(args=None): import", "from dials.util.options import OptionParser, reflections_and_experiments_from_files usage = \"dials.show [options] models.expt", "sys.exit(\"Error: experiment has no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments,", "!= 0) for value, flag in table.flags.values.items() } # Work", "b, c)) angles.append((alpha, beta, gamma)) a, b, c = abc.mean()", "None) for panel_id, panel in enumerate(detector): try: x, y =", "formats.get(k, \"%s\") % flex.mean(si), ] ) x1, x2, y1, y2,", "array of output strings text = [] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows,", "import flex from dials.util import Sorry, tabulate help_message = \"\"\"", "and x is not None and y is not None:", "beam centres if beam.num_scan_points > 0: # get scan-varying beam", "Max: {:.1f}\".format( identifier, *fns ) ) def model_connectivity(experiments): def model_connectivity_impl(experiments,", "% ( \"\\n\".join( \"id:\" + str(k) + \" -> experiment", "- y1) * (x2 - x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key", "formats.get(k, \"%s\") % flex.max(col), formats.get(k, \"%s\") % flex.mean(col), ] )", "contains {len(rlist)} reflections\") if len(rlist) == 0: continue rows =", "@dials.util.show_mail_handle_errors() def run(args=None): import dials.util.log dials.util.log.print_banner() from dials.util.options import OptionParser,", "pix\", formats.get(k, \"%s\") % flex.min(fore_valid), formats.get(k, \"%s\") % flex.max(fore_valid), formats.get(k,", ".help = \"Limit the number of reflections in the output.\"", "image statistics, check_format has to be true. So we have", "= { \"miller_index\": \"%i, %i, %i\", \"d\": \"%.2f\", \"qe\": \"%.3f\",", "% i_expt) format_class = expt.imageset.get_format_class() if format_class.__name__ != \"Format\": text.append(f\"Format", "here try: experiments = ExperimentListFactory.from_json( experiments.as_json(), check_format=True ) except OSError", "im_type: {im_type}\") # To show image statistics, check_format has to", "max_reflections = len(rlist) columns = [] for k in keys:", "= detector[panel_id] x_px, y_px = panel.millimeter_to_pixel((x, y)) offset = panel.get_raw_image_offset()", "the {im_type} images\") for i_expt, expt in enumerate(experiments): for i", "isinstance(data, flex.vec3_double): c_strings = [ c.as_string(format_strings[i].strip()) for i, c in", "None) return panel_id, (x, y) def beam_centre_raw_image_px(detector, s0): panel_id, (x,", "\"\\n\".join(text) def show_image_statistics(experiments, im_type): if im_type == \"raw\": raw =", "s0): panel_id, (x, y) = beam_centre_mm(detector, s0) panel = detector[panel_id]", "for k in centroid_keys: keys_to_print.add(k) if show_all_reflection_data: for k in", "\"Whether or not to print individual reflections\" show_intensities = False", "text.append( \"Max resolution (at corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append(", "identifier:\" + str(rlist.experiment_identifiers()[k]) for k in rlist.experiment_identifiers().keys() ) ) )", "# get scan-varying beam centres, ensuring all on same panel", "ensuring all on same panel sv_s0 = beam.get_s0_at_scan_points() impacts =", "show_identifiers = False .type = bool .help = \"Show experiment", "\"d\": \"%.2f\", \"qe\": \"%.3f\", \"dqe\": \"%.3f\", \"id\": \"%i\", \"imageset_id\": \"%i\",", "False .type = bool .help = \"Show a summary table", "bool .help = \"Show experiment identifiers map if set\" image_statistics{", "scitbx.math import five_number_summary import dials.util from dials.array_family import flex from", "* (y2 - y1) * (x2 - x1)).as_double() rows.append( [", "panel %i, (%.2f,%.2f)\" % (panel_id, x, y) beam_centre_px_str = \"", "bool show_flags = False .type = bool .help = \"Show", "= [[\"Column\", \"min\", \"max\", \"mean\"]] for k, col in rlist.cols():", "in the output.\" \"\"\", process_includes=True, ) def beam_centre_mm(detector, s0): x,", "flex.mean(bbox_sizes), ] ) fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append( [ \" N", "else: beam_centre_mm_str = f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str = f\" px:", "\"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\":", "c_strings = [ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.parts()) ]", "for j in range(len(columns)): key = keys[j] if key ==", "max_count_len = max(5, len(str(max(flag_count.values())))) last_flag = None for flag in", "y_px = panel.millimeter_to_pixel((x, y)) offset = panel.get_raw_image_offset() return x_px +", "= five_number_summary(flat_data) print( \"{}: Min: {:.1f} Q1: {:.1f} Med: {:.1f}", "None .type = int .help = \"Limit the number of", "is not None: text.append(str(expt.scaling_model)) return \"\\n\".join(text) def show_image_statistics(experiments, im_type): if", "\" px, raw image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, ) x_raw_mm, y_raw_mm", "\"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\", \"partiality\":", "%.4e\", \"xyzobs.px.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\", \"s1\":", "rows.append( [ \" N pix\", formats.get(k, \"%s\") % flex.min(bbox_sizes), formats.get(k,", "\" -> experiment identifier:\" + str(rlist.experiment_identifiers()[k]) for k in rlist.experiment_identifiers().keys()", "image data. Please check {e.filename} is accessible\" ) print(f\"Five number", "i_expt, expt in enumerate(experiments): text.append(\"Experiment %i:\" % i_expt) format_class =", "for rlist in reflections: from dials.algorithms.shoebox import MaskCode foreground_valid =", "\"\", \"\", \"\"]) si = col.summed_intensity().observed_value() rows.append( [ \" summed", "text.append(tabulate(rows, tablefmt=\"plain\")) return text if len(experiments) == 1: return \"\"", "\"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\",", "if expt.identifier != \"\": text.append(f\"Experiment identifier: {expt.identifier}\") try: template =", "+ \" scan points\\n\" # add static model beam centres", "y1) * (x2 - x1)).as_double() rows.append( [ \" N pix\",", "str(k) + \" -> experiment identifier:\" + str(rlist.experiment_identifiers()[k]) for k", "for m in models: if getattr(e, model) is m: row.append(\"x\")", "cctbx import uctbx from dxtbx.model.experiment_list import ExperimentListFactory from scitbx.math import", "panel.is_coord_valid_mm((x, y)): break else: x, y = (None, None) return", "%.4f\", \"s1\": \"%.4f, %.4f, %.4f\", \"s2\": \"%.4f, %.4f, %.4f\", \"shoebox\":", "f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str = f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str =", "expt.crystal is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc = flex.vec3_double()", "for k in intensity_keys: keys_to_print.add(k) if show_profile_fit: for k in", "\"%.4f, %.4f, %.4f\", \"s1\": \"%.4f, %.4f, %.4f\", \"s2\": \"%.4f, %.4f,", "is m: row.append(\"x\") else: row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return text", "expt.goniometer is not None: text.append(show_goniometer(expt.goniometer)) if expt.crystal is not None:", "\"\"\", process_includes=True, ) def beam_centre_mm(detector, s0): x, y = (None,", "x_px + offset[0], y_px + offset[1] def show_beam(detector, beam): #", "text.append(f\" Average unit cell: {mean_unit_cell}\") if expt.profile is not None:", "keys: columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing %i of", "[options] models.expt | image_*.cbf\" parser = OptionParser( usage=usage, phil=phil_scope, read_experiments=True,", "(\"%%%is\" % max_element_lengths[j]) % c_strings[j][i] for j in range(len(c_strings)) )", "c.as_string(format_strings[i].strip()) for i, c in enumerate(data.as_vec3_double().parts()) ] elif isinstance(data, flex.size_t):", "formats.get(k, \"%s\") % flex.mean(fore_valid), ] ) text.append(tabulate(rows, headers=\"firstrow\")) if show_flags:", "in range(len(c_strings)) ) ) return column if keys_to_print: keys =", "'summary' flags. # A summary flag is any flag which", "+= ( \" Setting rotation sampled at \" + str(goniometer.num_scan_points)", "e in experiments): sys.exit(\"Error: experiment has no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying))", "panel.get_ray_intersection(s0) except RuntimeError: continue else: if panel.is_coord_valid_mm((x, y)): break else:", ") = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c)) angles.append((alpha, beta, gamma)) a,", "entries that match each flag numpy_flags = table[\"flags\"].as_numpy_array() flag_count =", "(flex.double, flex.int, flex.size_t): if type(col) in (flex.int, flex.size_t): col =", "# add static model beam centres panel_id, (x, y) =", "of the formatted flags table \"\"\" # Calculate the counts", "So we have to reinstatiate # the experiment list here", "text.append(f\"Reflection list contains {len(rlist)} reflections\") if len(rlist) == 0: continue", "= bool .help = \"Show which models are linked to", "of values in each raw image\" } max_reflections = None", "= zip(*xy) # convert to pixels xy = [detector[pnl].millimeter_to_pixel(e) for", "if getattr(e, model) is m: row.append(\"x\") else: row.append(\".\") rows.append(row) text.append(tabulate(rows,", ">= 0 and x is not None and y is", "show_flags=False, max_reflections=None, show_identifiers=False, ): text = [] from orderedset import", "for i_expt, expt in enumerate(experiments): for i in range(len(expt.imageset)): identifier", "if not isinstance(pnl_data, tuple): pnl_data = (pnl_data,) flat_data = pnl_data[0].as_1d()", "% flex.mean(si), ] ) x1, x2, y1, y2, z1, z2", "show_profile_fit = False .type = bool show_flags = False .type", "in a reflection table. :param table: A reflection table :returns:", "y1, y2, z1, z2 = data.bounding_boxes().parts() bbox_sizes = ((z2 -", "summed I\", formats.get(k, \"%s\") % flex.min(si), formats.get(k, \"%s\") % flex.max(si),", "| image_*.cbf\" parser = OptionParser( usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True,", "{:.1f} Q1: {:.1f} Med: {:.1f} Q3: {:.1f} Max: {:.1f}\".format( identifier,", "[ \" N valid foreground pix\", formats.get(k, \"%s\") % flex.min(fore_valid),", "text.append(str(expt.scan)) if expt.goniometer is not None: text.append(show_goniometer(expt.goniometer)) if expt.crystal is", "and (last_flag.real & flag.real): indent = \" \" last_flag =", "= len(rlist) columns = [] for k in keys: columns.append(", "\"Show experiment identifiers map if set\" image_statistics{ show_corrected = False", "{mean_unit_cell}\") if expt.profile is not None: text.append(str(expt.profile)) if expt.scaling_model is", "flag_count[flag] / len(table):5.01f}\", ] ) # Build the array of", "b, c, alpha, beta, gamma)) text.append(f\" Average unit cell: {mean_unit_cell}\")", "formats.get(k, \"%s\"), ] ) elif type(col) in (flex.double, flex.int, flex.size_t):", "( \"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", )", "beam_centre_mm_str = \" mm: panel %i, (%.2f,%.2f)\" % (panel_id, x,", ") ) def model_connectivity(experiments): def model_connectivity_impl(experiments, model): text = [\"\"]", "formatted flags table \"\"\" # Calculate the counts of entries", ") x1, x2, y1, y2, z1, z2 = col.bounding_boxes().parts() bbox_sizes", "elif type(col) in (flex.double, flex.int, flex.size_t): if type(col) in (flex.int,", "summary table of reflection flags\" show_identifiers = False .type =", "= [[\"\"] + [str(j) for j in range(len(models))]] for j,", "= \"\" beam_centre_raw_mm_str = \"\" s += \"\\nBeam centre: \\n\"", "%.4e, %.4e\", \"xyzobs.px.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\",", "the actual table flag_rows = [[\"Flag\", \"Count\", \"%\"]] max_count_len =", "x1, x2, y1, y2, z1, z2 = col.bounding_boxes().parts() bbox_sizes =", "% (panel_id, x, y) beam_centre_px_str = \" px: panel %i,", "of values in each corrected image\" show_raw = False .type", "if len(experiments) == 0 and len(reflections) == 0: parser.print_help() exit()", "point.\" show_shared_models = False .type = bool .help = \"Show", "%i of %i reflections:\" % (max_reflections, len(rlist))) line = []", "flex.miller_index): if isinstance(col, flex.miller_index): col = col.as_vec3_double() rows.append( [ k,", "enumerate(experiments): for i in range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if raw:", "model_connectivity(experiments): def model_connectivity_impl(experiments, model): text = [\"\"] text.append(f\"{model.capitalize()}:\") models =", "\"Show statistics on the distribution of values in each corrected", "e: raise Sorry( f\"Unable to read image data. Please check", "str(beam.num_scan_points) + \" scan points\\n\" # add static model beam", "params.show_shared_models: print() print(model_connectivity(experiments)) if len(reflections): print( show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit,", "for e in experiments): sys.exit(\"Error: experiment has no beam\") print(show_experiments(experiments,", "i in range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data =", "flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text) def show_reflections( reflections, show_intensities=False, show_profile_fit=False,", "y = (None, None) for panel_id, panel in enumerate(detector): try:", "a hint for reading, indent any 'summary' flags. # A", "\"\"\"Generate a summary table of flag values in a reflection", "0: parser.print_help() exit() if len(experiments): if not all(e.detector for e", "\"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\",", "standard static beam model string s = str(beam) # report", "[ k, formats.get(k, \"%s\"), formats.get(k, \"%s\"), formats.get(k, \"%s\"), ] )", "beam_centre_mm(detector, s0): x, y = (None, None) for panel_id, panel", "%.4f\", \"zeta\": \"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\":", "is not None and y is not None: x_px, y_px", "def show_beam(detector, beam): # standard static beam model string s", "centres if beam.num_scan_points > 0: # get scan-varying beam centres,", "\"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\":", "headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers: if rlist.experiment_identifiers(): text.append( \"\"\"Experiment", "individual reflections\" show_intensities = False .type = bool show_centroids =", "= min(len(rlist), max_reflections) else: max_reflections = len(rlist) columns = []", "\"%.2f, %.2f, %.2f\", \"xyzcal.px\": \"%.2f, %.2f, %.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\":", "A string of the formatted flags table \"\"\" # Calculate", "def model_connectivity(experiments): def model_connectivity_impl(experiments, model): text = [\"\"] text.append(f\"{model.capitalize()}:\") models", "= \"\" s += \"\\nBeam centre: \\n\" s += beam_centre_mm_str", "resolution (at corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max resolution", "return \"\\n\".join(text) def show_reflections( reflections, show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False,", "x is not None and y is not None: x_px,", ") ) ) intensity_keys = ( \"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\",", "if expt.scan is not None: text.append(str(expt.scan)) if expt.goniometer is not", "in xy] x_px, y_px = zip(*xy) s += \"Beam centre", "] ) elif type(col) in (flex.vec3_double, flex.miller_index): if isinstance(col, flex.miller_index):", "\"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\":", "whether the goniometer is scan-varying if goniometer.num_scan_points > 0: s", "detector\") if not all(e.beam for e in experiments): sys.exit(\"Error: experiment", ".type = bool show_flags = False .type = bool .help", "(x, y) = beam_centre_mm(detector, beam.get_s0()) if panel_id >= 0 and", "for k in formats: keys_to_print.add(k) def format_column(key, data, format_strings=None): if", "( \" Setting rotation sampled at \" + str(goniometer.num_scan_points) +", "x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) ) beam_centre_raw_mm_str = \"", "sv_s0 = beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector, s0) for s0 in", "panel_id, panel in enumerate(detector): try: x, y = panel.get_ray_intersection(s0) except", "options = parser.parse_args(args=args, show_diff_phil=True) reflections, experiments = reflections_and_experiments_from_files( params.input.reflections, params.input.experiments", "reflections: from dials.algorithms.shoebox import MaskCode foreground_valid = MaskCode.Valid | MaskCode.Foreground", "show_scan_varying=False): text = [] for i_expt, expt in enumerate(experiments): text.append(\"Experiment", "y_px, ) x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str = \"", "ValueError(f\"Unknown im_type: {im_type}\") # To show image statistics, check_format has", "\"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\":", "\"%s\") % flex.min(col), formats.get(k, \"%s\") % flex.max(col), formats.get(k, \"%s\") %", "\"\\n\" # report range of scan-varying model beam centres if", "model string s = str(beam) # report whether the beam", "width = max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" % width % key) text.append(\"", "# Build the array of output strings text = []", "in centroid_keys: keys_to_print.add(k) if show_all_reflection_data: for k in formats: keys_to_print.add(k)", "None: max_reflections = min(len(rlist), max_reflections) else: max_reflections = len(rlist) columns", "beam.num_scan_points > 0: # get scan-varying beam centres, ensuring all", "x_px, y_px, ) x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str =", "formats.get(k, \"%s\"), formats.get(k, \"%s\"), ] ) elif type(col) in (flex.double,", "y_px = zip(*xy) s += \"Beam centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format(", "- x1)).as_double() rows.append( [ \" N pix\", formats.get(k, \"%s\") %", "len(rlist) columns = [] for k in keys: columns.append( format_column(k,", "which overlaps with the previous one. if last_flag and (last_flag.real", "\"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print = OrderedSet() if show_intensities: for k", "\"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\",", "* (y2 - y1) * (x2 - x1)).as_double() c_strings =", "if len(experiments) == 1: return \"\" text = [] text.append(\"Experiment", "% (max_reflections, len(rlist))) line = [] for j in range(len(columns)):", "+= \"\\nBeam centre: \\n\" s += beam_centre_mm_str + \"\\n\" +", "a, b, c = abc.mean() alpha, beta, gamma = angles.mean()", "return panel_id, (x, y) def beam_centre_raw_image_px(detector, s0): panel_id, (x, y)", "y) = beam_centre_mm(detector, beam.get_s0()) if panel_id >= 0 and x", "y) = beam_centre_mm(detector, s0) panel = detector[panel_id] x_px, y_px =", "is not None: text.append(str(expt.scan)) if expt.goniometer is not None: text.append(show_goniometer(expt.goniometer))", "entries that wouldn't make sense rows.append( [ k, formats.get(k, \"%s\"),", "formats.get(k, \"%s\") % flex.mean(bbox_sizes), ] ) fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append(", "y2, z1, z2 = col.bounding_boxes().parts() bbox_sizes = ((z2 - z1)", "\"corrected\") if params.show_shared_models: print() print(model_connectivity(experiments)) if len(reflections): print( show_reflections( reflections,", "expt.beam)) if expt.scan is not None: text.append(str(expt.scan)) if expt.goniometer is", "show_experiments(experiments, show_scan_varying=False): text = [] for i_expt, expt in enumerate(experiments):", "im_type == \"raw\": raw = True elif im_type == \"corrected\":", "beam_centre_mm_str = f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str = f\" px: ({x_px:.2f},{y_px:.2f})\"", "if len(detector) > 1: beam_centre_mm_str = \" mm: panel %i,", "scan points\\n\" ) return s @dials.util.show_mail_handle_errors() def run(args=None): import dials.util.log", "\"Max resolution (inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector, expt.beam))", "pix\", formats.get(k, \"%s\") % flex.min(bbox_sizes), formats.get(k, \"%s\") % flex.max(bbox_sizes), formats.get(k,", "= [detector[pnl].millimeter_to_pixel(e) for e in xy] x_px, y_px = zip(*xy)", "None: text.append(str(expt.scaling_model)) return \"\\n\".join(text) def show_image_statistics(experiments, im_type): if im_type ==", "= flex.vec3_double() for n in range(expt.crystal.num_scan_points): ( a, b, c,", "= { flag: np.sum(numpy_flags & value != 0) for value,", "text.append(show_beam(expt.detector, expt.beam)) if expt.scan is not None: text.append(str(expt.scan)) if expt.goniometer", "the experiment list here try: experiments = ExperimentListFactory.from_json( experiments.as_json(), check_format=True", "\"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\",", "\"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", } for rlist in", "= [ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.parts()) ] elif", "str(goniometer) # report whether the goniometer is scan-varying if goniometer.num_scan_points", "{:.1f} Med: {:.1f} Q3: {:.1f} Max: {:.1f}\".format( identifier, *fns )", "\"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\",", "\"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\",", "+= \" (N pix)\" else: c_strings = [data.as_string(format_strings[0].strip())] column =", "[] for j in range(len(columns)): key = keys[j] if key", "import numpy as np import iotbx.phil from cctbx import uctbx", "offset[1] def show_beam(detector, beam): # standard static beam model string", "angles.append((alpha, beta, gamma)) a, b, c = abc.mean() alpha, beta,", "] ) text.append(tabulate(rows, headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers: if", "mm: ({x:.2f},{y:.2f})\" beam_centre_px_str = f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\"", "sorted(table.flags.values.values(), key=lambda x: x.real) # Build the actual table flag_rows", "flex.mean(col), ] ) elif type(col) in (flex.vec3_double, flex.miller_index): if isinstance(col,", "col = col.as_vec3_double() rows.append( [ k, formats.get(k, \"%s\") % col.min(),", "in range(len(models))]] for j, e in enumerate(experiments): row = [\"Experiment", "for j, e in enumerate(experiments): row = [\"Experiment %d\" %", "indent = \" \" last_flag = flag # Add the", "reflections, experiments = reflections_and_experiments_from_files( params.input.reflections, params.input.experiments ) if len(experiments) ==", "1 or min(uniq_pnls) < 0: return s if any(e ==", "for c in columns) text.append(\" \".join(line)) return \"\\n\".join(text) if __name__", "\"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print =", "try: template = expt.imageset.get_template() except AttributeError: template = None if", "= ( \"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\",", ") profile_fit_keys = (\"miller_index\", \"d\") centroid_keys = ( \"miller_index\", \"d\",", "Calculate the counts of entries that match each flag numpy_flags", "in experiments): sys.exit(\"Error: experiment has no detector\") if not all(e.beam", "in (flex.double, flex.int, flex.size_t): if type(col) in (flex.int, flex.size_t): col", ":param table: A reflection table :returns: A string of the", "has to be true. So we have to reinstatiate #", "template = expt.imageset.get_template() except AttributeError: template = None if template:", "\"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\", \"xyzobs.px.value\": \"%.2f,", "/ Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text)", ") intensity_keys = ( \"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\",", "== \"raw\": raw = True elif im_type == \"corrected\": raw", "+= beam_centre_mm_str + \"\\n\" + beam_centre_px_str + \"\\n\" if beam_centre_raw_mm_str:", "N pix\", formats.get(k, \"%s\") % flex.min(bbox_sizes), formats.get(k, \"%s\") % flex.max(bbox_sizes),", "= detector[panel_id].millimeter_to_pixel((x, y)) if len(detector) > 1: beam_centre_mm_str = \"", "tuple): pnl_data = (pnl_data,) flat_data = pnl_data[0].as_1d() for p in", "MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list contains {len(rlist)} reflections\") if len(rlist) ==", "z2 = data.bounding_boxes().parts() bbox_sizes = ((z2 - z1) * (y2", ") print(f\"Five number summary of the {im_type} images\") for i_expt,", "\"\"\" Examples:: dials.show models.expt dials.show image_*.cbf dials.show observations.refl \"\"\" phil_scope", "= [] for i_expt, expt in enumerate(experiments): text.append(\"Experiment %i:\" %", ".help = \"Show which models are linked to which experiments\"", "+ \"\\n\" # report range of scan-varying model beam centres", ".type = bool .help = \"Whether or not to show", "not None: max_reflections = min(len(rlist), max_reflections) else: max_reflections = len(rlist)", "\"Limit the number of reflections in the output.\" \"\"\", process_includes=True,", "if expt.profile is not None: text.append(str(expt.profile)) if expt.scaling_model is not", "\" N valid foreground pix\", formats.get(k, \"%s\") % flex.min(fore_valid), formats.get(k,", "== 0: continue rows = [[\"Column\", \"min\", \"max\", \"mean\"]] for", "= f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str = f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str", "= str(goniometer) # report whether the goniometer is scan-varying if", ") text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if expt.scan is not None: text.append(str(expt.scan))", "Please check {e.filename} is accessible\" ) print(f\"Five number summary of", "x_raw_mm, y_raw_mm, ) else: beam_centre_mm_str = f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str", "observations.refl \"\"\" phil_scope = iotbx.phil.parse( \"\"\"\\ show_scan_varying = False .type", "report whether the beam is scan-varying if beam.num_scan_points > 0:", "columns[j].max_element_length()) line.append(\"%%%is\" % width % key) text.append(\" \".join(line)) for i", "= table[\"flags\"].as_numpy_array() flag_count = { flag: np.sum(numpy_flags & value !=", "on same panel sv_s0 = beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector, s0)", "scan-varying model beam centres if beam.num_scan_points > 0: # get", "identifiers map if set\" image_statistics{ show_corrected = False .type =", "the output.\" \"\"\", process_includes=True, ) def beam_centre_mm(detector, s0): x, y", "[] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text) def show_reflections( reflections,", "experiments\" show_all_reflection_data = False .type = bool .help = \"Whether", "(x2 - x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key += \" (N", "= expt.imageset.get_template() except AttributeError: template = None if template: text.append(f\"Image", "c_strings] for i in range(len(c_strings[0])): column.append( f\"%{len(key)}s\" % \", \".join(", "params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if params.show_shared_models: print() print(model_connectivity(experiments)) if len(reflections): print(", "strings text = [] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text)", "= \"Limit the number of reflections in the output.\" \"\"\",", "len(rlist) == 0: continue rows = [[\"Column\", \"min\", \"max\", \"mean\"]]", "formats.get(k, \"%s\"): # Allow blanking out of entries that wouldn't", "= [bbox_sizes.as_string(format_strings[0].strip())] key += \" (N pix)\" else: c_strings =", "profile_fit_keys: keys_to_print.add(k) if show_centroids: for k in centroid_keys: keys_to_print.add(k) if", "last_flag = None for flag in flag_order: indent = \"\"", "reflection flags\" show_identifiers = False .type = bool .help =", "text.append(\"Experiment %i:\" % i_expt) format_class = expt.imageset.get_format_class() if format_class.__name__ !=", "* (x2 - x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key += \"", "if expt.goniometer is not None: text.append(show_goniometer(expt.goniometer)) if expt.crystal is not", "parser.parse_args(args=args, show_diff_phil=True) reflections, experiments = reflections_and_experiments_from_files( params.input.reflections, params.input.experiments ) if", "= panel.get_raw_image_offset() return x_px + offset[0], y_px + offset[1] def", "( a, b, c, alpha, beta, gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters()", "scan-varying if beam.num_scan_points > 0: s += \" s0 sampled", "e in experiments): sys.exit(\"Error: experiment has no detector\") if not", "import five_number_summary import dials.util from dials.array_family import flex from dials.util", "row to the table we're building flag_rows.append( [ indent +", "col in rlist.cols(): if k in formats and \"%\" not", "+= \" (N pix)\" width = max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" %", "expt.imageset.get_corrected_data(i) if not isinstance(pnl_data, tuple): pnl_data = (pnl_data,) flat_data =", "def show_image_statistics(experiments, im_type): if im_type == \"raw\": raw = True", "table flag_rows = [[\"Flag\", \"Count\", \"%\"]] max_count_len = max(5, len(str(max(flag_count.values()))))", "c_strings[j][i] for j in range(len(c_strings)) ) ) return column if", "beta, gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c)) angles.append((alpha, beta,", "show_identifiers=False, ): text = [] from orderedset import OrderedSet formats", "f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str = \"\" s", "\".join(line)) for i in range(max_reflections): line = (c[i] for c", "(last_flag.real & flag.real): indent = \" \" last_flag = flag", "template = None if template: text.append(f\"Image template: {template}\") text.append(str(expt.detector)) text.append(", "flex.vec3_double() angles = flex.vec3_double() for n in range(expt.crystal.num_scan_points): ( a,", "as e: raise Sorry( f\"Unable to read image data. Please", "+ offset[1] def show_beam(detector, beam): # standard static beam model", "= False .type = bool .help = \"Show a summary", "= None for flag in flag_order: indent = \"\" #", "= \" px: panel %i, (%.2f,%.2f)\" % ( panel_id, x_px,", "convert to pixels xy = [detector[pnl].millimeter_to_pixel(e) for e in xy]", "= beam_centre_mm(detector, s0) panel = detector[panel_id] x_px, y_px = panel.millimeter_to_pixel((x,", "min(y_mm), max(y_mm), ) s += \"Beam centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format(", "\"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", } for", "s def show_goniometer(goniometer): # standard static goniometer model string s", "\"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys", "expt.imageset.get_template() except AttributeError: template = None if template: text.append(f\"Image template:", ") fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append( [ \" N valid foreground", "%.2f, %.2f\", \"xyzcal.px\": \"%.2f, %.2f, %.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\",", "enumerate(detector): try: x, y = panel.get_ray_intersection(s0) except RuntimeError: continue else:", "rlist] if max_reflections is not None: max_reflections = min(len(rlist), max_reflections)", "False .type = bool show_profile_fit = False .type = bool", "max_reflections = None .type = int .help = \"Limit the", "return \"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate a summary table of flag", "text.append(tabulate(rows, headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers: if rlist.experiment_identifiers(): text.append(", "last_flag and (last_flag.real & flag.real): indent = \" \" last_flag", "= iotbx.phil.parse( \"\"\"\\ show_scan_varying = False .type = bool .help", "\"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\":", "centres, ensuring all on same panel sv_s0 = beam.get_s0_at_scan_points() impacts", "b, c, alpha, beta, gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b,", "np.sum(numpy_flags & value != 0) for value, flag in table.flags.values.items()", "\"panel\": \"%i\", \"flags\": \"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\",", "y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str = \" px, raw image:", "\"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e,", "k in rlist.experiment_identifiers().keys() ) ) ) intensity_keys = ( \"miller_index\",", "y = (None, None) return panel_id, (x, y) def beam_centre_raw_image_px(detector,", "\"imageset_id\": \"%i\", \"panel\": \"%i\", \"flags\": \"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\",", "scan point.\" show_shared_models = False .type = bool .help =", "if type(col) in (flex.int, flex.size_t): col = col.as_double() rows.append( [", "= ((z2 - z1) * (y2 - y1) * (x2", "the goniometer is scan-varying if goniometer.num_scan_points > 0: s +=", "dials.show models.expt dials.show image_*.cbf dials.show observations.refl \"\"\" phil_scope = iotbx.phil.parse(", "-> experiment identifier:\" + str(rlist.experiment_identifiers()[k]) for k in rlist.experiment_identifiers().keys() )", "return column if keys_to_print: keys = [k for k in", "= [data.as_string(format_strings[0].strip())] column = flex.std_string() max_element_lengths = [c.max_element_length() for c", "the crystal at each scan point.\" show_shared_models = False .type", "flex.max(fore_valid), formats.get(k, \"%s\") % flex.mean(fore_valid), ] ) text.append(tabulate(rows, headers=\"firstrow\")) if", "show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False, ): text =", "+ \"\\n\" if beam_centre_raw_px_str: s += beam_centre_raw_px_str + \"\\n\" #", "static goniometer model string s = str(goniometer) # report whether", "bool .help = \"Whether or not to show the crystal", "# Allow blanking out of entries that wouldn't make sense", "panel_id, (x, y) = beam_centre_mm(detector, s0) panel = detector[panel_id] x_px,", "flex.vec3_double() for n in range(expt.crystal.num_scan_points): ( a, b, c, alpha,", "min(len(rlist), max_reflections) else: max_reflections = len(rlist) columns = [] for", "rlist in reflections: from dials.algorithms.shoebox import MaskCode foreground_valid = MaskCode.Valid", "rlist.cols(): if k in formats and \"%\" not in formats.get(k,", "\"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print = OrderedSet() if show_intensities:", "xy): return s pnl = list(uniq_pnls)[0] x_mm, y_mm = zip(*xy)", "text = [] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text) def", "= int .help = \"Limit the number of reflections in", "add static model beam centres panel_id, (x, y) = beam_centre_mm(detector,", "or not to show the crystal at each scan point.\"", "if expt.crystal is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc =", "in columns) text.append(\" \".join(line)) return \"\\n\".join(text) if __name__ == \"__main__\":", "({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str = \"\" s += \"\\nBeam", "format_strings=None): if isinstance(data, flex.vec3_double): c_strings = [ c.as_string(format_strings[i].strip()) for i,", "summary table of flag values in a reflection table. :param", "def _create_flag_count_table(table): \"\"\"Generate a summary table of flag values in", "\"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print = OrderedSet()", "0 and x is not None and y is not", "- z1) * (y2 - y1) * (x2 - x1)).as_double()", "images\") for i_expt, expt in enumerate(experiments): for i in range(len(expt.imageset)):", "\"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\", \"partiality\": \"%.4f\", \"profile.correlation\":", "enumerate(data.parts()) ] elif isinstance(data, flex.miller_index): c_strings = [ c.as_string(format_strings[i].strip()) for", "len(reflections) == 0: parser.print_help() exit() if len(experiments): if not all(e.detector", "format_class.__name__ != \"Format\": text.append(f\"Format class: {format_class.__name__}\") if expt.identifier != \"\":", "the numeric-value order of the flags flag_order = sorted(table.flags.values.values(), key=lambda", "hint for reading, indent any 'summary' flags. # A summary", "dials.util.log dials.util.log.print_banner() from dials.util.options import OptionParser, reflections_and_experiments_from_files usage = \"dials.show", "= False .type = bool .help = \"Show which models", "y_px + offset[1] def show_beam(detector, beam): # standard static beam", "\"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\", \"xyzobs.px.value\": \"%.2f, %.2f,", "x_px, y_px = panel.millimeter_to_pixel((x, y)) offset = panel.get_raw_image_offset() return x_px", "elif im_type == \"corrected\": raw = False else: raise ValueError(f\"Unknown", "Med: {:.1f} Q3: {:.1f} Max: {:.1f}\".format( identifier, *fns ) )", "check_format=True ) except OSError as e: raise Sorry( f\"Unable to", "k, formats.get(k, \"%s\") % col.min(), formats.get(k, \"%s\") % col.max(), formats.get(k,", "> 0: s += ( \" Setting rotation sampled at", "of scan-varying model beam centres if beam.num_scan_points > 0: #", "rows.append([k, \"\", \"\", \"\"]) si = col.summed_intensity().observed_value() rows.append( [ \"", "usage = \"dials.show [options] models.expt | image_*.cbf\" parser = OptionParser(", "numpy as np import iotbx.phil from cctbx import uctbx from", "alpha, beta, gamma = angles.mean() mean_unit_cell = uctbx.unit_cell((a, b, c,", "make sense rows.append( [ k, formats.get(k, \"%s\"), formats.get(k, \"%s\"), formats.get(k,", "text.append( \"\"\"Experiment identifiers id-map values:\\n%s\"\"\" % ( \"\\n\".join( \"id:\" +", "keys_to_print.add(k) if show_profile_fit: for k in profile_fit_keys: keys_to_print.add(k) if show_centroids:", "= getattr(experiments, f\"{model}s\")() rows = [[\"\"] + [str(j) for j", "0: # get scan-varying beam centres, ensuring all on same", "= [ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.as_vec3_double().parts()) ] elif", "are linked to which experiments\" show_all_reflection_data = False .type =", "[ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.as_vec3_double().parts()) ] elif isinstance(data,", "0: s += \" s0 sampled at \" + str(beam.num_scan_points)", "list here try: experiments = ExperimentListFactory.from_json( experiments.as_json(), check_format=True ) except", "i, c in enumerate(data.as_vec3_double().parts()) ] elif isinstance(data, flex.size_t): c_strings =", "& flag.real): indent = \" \" last_flag = flag #", "{format_class.__name__}\") if expt.identifier != \"\": text.append(f\"Experiment identifier: {expt.identifier}\") try: template", "isinstance(col, flex.miller_index): col = col.as_vec3_double() rows.append( [ k, formats.get(k, \"%s\")", "= bool .help = \"Whether or not to show the", "at each scan point.\" show_shared_models = False .type = bool", "standard static goniometer model string s = str(goniometer) # report", "y)) offset = panel.get_raw_image_offset() return x_px + offset[0], y_px +", "1: beam_centre_mm_str = \" mm: panel %i, (%.2f,%.2f)\" % (panel_id,", ") if len(experiments) == 0 and len(reflections) == 0: parser.print_help()", "None: text.append(show_goniometer(expt.goniometer)) if expt.crystal is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points:", "flex.std_string() max_element_lengths = [c.max_element_length() for c in c_strings] for i", "show_beam(detector, beam): # standard static beam model string s =", "k, col in rlist.cols(): if k in formats and \"%\"", "= col.summed_intensity().observed_value() rows.append( [ \" summed I\", formats.get(k, \"%s\") %", "(None, None) return panel_id, (x, y) def beam_centre_raw_image_px(detector, s0): panel_id,", "\"\\n\".join( \"id:\" + str(k) + \" -> experiment identifier:\" +", "0) for value, flag in table.flags.values.items() } # Work out", "show_centroids: for k in centroid_keys: keys_to_print.add(k) if show_all_reflection_data: for k", "(panel_id, x, y) beam_centre_px_str = \" px: panel %i, (%.2f,%.2f)\"", "y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) ) beam_centre_raw_mm_str = \" mm,", "indent = \"\" # As a hint for reading, indent", "get scan-varying beam centres, ensuring all on same panel sv_s0", "% flex.min(bbox_sizes), formats.get(k, \"%s\") % flex.max(bbox_sizes), formats.get(k, \"%s\") % flex.mean(bbox_sizes),", "\"zeta\": \"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\",", "A summary flag is any flag which overlaps with the", "try: experiments = ExperimentListFactory.from_json( experiments.as_json(), check_format=True ) except OSError as", "from dials.algorithms.shoebox import MaskCode foreground_valid = MaskCode.Valid | MaskCode.Foreground text.append(\"\")", "x, y = (None, None) for panel_id, panel in enumerate(detector):", "in keys: columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing %i", "n in range(expt.crystal.num_scan_points): ( a, b, c, alpha, beta, gamma,", "= MaskCode.Valid | MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list contains {len(rlist)} reflections\")", "fns = five_number_summary(flat_data) print( \"{}: Min: {:.1f} Q1: {:.1f} Med:", "keys = [k for k in keys_to_print if k in", "text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text) def show_reflections( reflections, show_intensities=False, show_profile_fit=False, show_centroids=False,", "image\" show_raw = False .type = bool .help = \"Show", "% width % key) text.append(\" \".join(line)) for i in range(max_reflections):", "table of flag values in a reflection table. :param table:", "[ k, formats.get(k, \"%s\") % flex.min(col), formats.get(k, \"%s\") % flex.max(col),", "beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector, s0) for s0 in sv_s0] pnl,", "line = (c[i] for c in columns) text.append(\" \".join(line)) return", "show_intensities: for k in intensity_keys: keys_to_print.add(k) if show_profile_fit: for k", "for i in range(max_reflections): line = (c[i] for c in", "%i, (%.2f,%.2f)\" % ( panel_id, x_px, y_px, ) x_raw_px, y_raw_px", "sv_s0] pnl, xy = zip(*impacts) uniq_pnls = set(pnl) if len(uniq_pnls)", "flex.size_t): if type(col) in (flex.int, flex.size_t): col = col.as_double() rows.append(", "[] from orderedset import OrderedSet formats = { \"miller_index\": \"%i,", "isinstance(col, flex.shoebox): rows.append([k, \"\", \"\", \"\"]) si = col.summed_intensity().observed_value() rows.append(", "wouldn't make sense rows.append( [ k, formats.get(k, \"%s\"), formats.get(k, \"%s\"),", "None) for e in xy): return s pnl = list(uniq_pnls)[0]", "show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False, ): text = []", "and y is not None: x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y))", "show the crystal at each scan point.\" show_shared_models = False", "flag_rows = [[\"Flag\", \"Count\", \"%\"]] max_count_len = max(5, len(str(max(flag_count.values())))) last_flag", "k in profile_fit_keys: keys_to_print.add(k) if show_centroids: for k in centroid_keys:", "] ) elif type(col) in (flex.double, flex.int, flex.size_t): if type(col)", "flag which overlaps with the previous one. if last_flag and", "col.as_vec3_double() rows.append( [ k, formats.get(k, \"%s\") % col.min(), formats.get(k, \"%s\")", "goniometer is scan-varying if goniometer.num_scan_points > 0: s += (", "sampled at \" + str(goniometer.num_scan_points) + \" scan points\\n\" )", "bool .help = \"Show which models are linked to which", "pnl, xy = zip(*impacts) uniq_pnls = set(pnl) if len(uniq_pnls) >", "beam_centre_raw_px_str + \"\\n\" # report range of scan-varying model beam", "rows = [[\"Column\", \"min\", \"max\", \"mean\"]] for k, col in", "c in columns) text.append(\" \".join(line)) return \"\\n\".join(text) if __name__ ==", "\"xyzcal.px\": \"%.2f, %.2f, %.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\",", "if beam.num_scan_points > 0: s += \" s0 sampled at", "= col.as_double() rows.append( [ k, formats.get(k, \"%s\") % flex.min(col), formats.get(k,", "accessible\" ) print(f\"Five number summary of the {im_type} images\") for", "\"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys = (\"miller_index\", \"d\") centroid_keys", "beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str = \"\" s += \"\\nBeam centre:", ".help = \"Whether or not to show the crystal at", "flex.max(col), formats.get(k, \"%s\") % flex.mean(col), ] ) elif type(col) in", "no detector\") if not all(e.beam for e in experiments): sys.exit(\"Error:", "return s pnl = list(uniq_pnls)[0] x_mm, y_mm = zip(*xy) #", "\"corrected\": raw = False else: raise ValueError(f\"Unknown im_type: {im_type}\") #", "panel.millimeter_to_pixel((x, y)) offset = panel.get_raw_image_offset() return x_px + offset[0], y_px", "k, formats.get(k, \"%s\"), formats.get(k, \"%s\"), formats.get(k, \"%s\"), ] ) elif", "summary flag is any flag which overlaps with the previous", "getattr(e, model) is m: row.append(\"x\") else: row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\"))", "p in pnl_data[1:]: flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data) print( \"{}: Min:", "MaskCode foreground_valid = MaskCode.Valid | MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list contains", "% flex.min(fore_valid), formats.get(k, \"%s\") % flex.max(fore_valid), formats.get(k, \"%s\") % flex.mean(fore_valid),", "k in intensity_keys: keys_to_print.add(k) if show_profile_fit: for k in profile_fit_keys:", "formats.get(k, \"%s\") % col.min(), formats.get(k, \"%s\") % col.max(), formats.get(k, \"%s\")", "s += beam_centre_raw_px_str + \"\\n\" # report range of scan-varying", "if len(uniq_pnls) > 1 or min(uniq_pnls) < 0: return s", "key += \" (N pix)\" else: c_strings = [data.as_string(format_strings[0].strip())] column", "[] for k in keys: columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\")) )", "} # Work out the numeric-value order of the flags", "As a hint for reading, indent any 'summary' flags. #", "for flag in flag_order: indent = \"\" # As a", "= None .type = int .help = \"Limit the number", "show_all_reflection_data: for k in formats: keys_to_print.add(k) def format_column(key, data, format_strings=None):", "s0) for s0 in sv_s0] pnl, xy = zip(*impacts) uniq_pnls", "else: c_strings = [data.as_string(format_strings[0].strip())] column = flex.std_string() max_element_lengths = [c.max_element_length()", "read_reflections=True, check_format=False, epilog=help_message, ) params, options = parser.parse_args(args=args, show_diff_phil=True) reflections,", "\"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\",", "keys_to_print.add(k) if show_centroids: for k in centroid_keys: keys_to_print.add(k) if show_all_reflection_data:", "= \"Show a summary table of reflection flags\" show_identifiers =", "the table we're building flag_rows.append( [ indent + flag.name, \"{:{:d}d}\".format(flag_count[flag],", "match each flag numpy_flags = table[\"flags\"].as_numpy_array() flag_count = { flag:", "table.flags.values.items() } # Work out the numeric-value order of the", "dials.array_family import flex from dials.util import Sorry, tabulate help_message =", "panel_id, x_px, y_px, ) x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str", "for i_expt, expt in enumerate(experiments): text.append(\"Experiment %i:\" % i_expt) format_class", "if len(reflections): print( show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags,", ") ) return column if keys_to_print: keys = [k for", "we have to reinstatiate # the experiment list here try:", "experiments): sys.exit(\"Error: experiment has no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw:", "int .help = \"Limit the number of reflections in the", "\"qe\": \"%.3f\", \"dqe\": \"%.3f\", \"id\": \"%i\", \"imageset_id\": \"%i\", \"panel\": \"%i\",", "\"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\":", "im_type): if im_type == \"raw\": raw = True elif im_type", "max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" % width % key) text.append(\" \".join(line)) for", ".type = bool .help = \"Show a summary table of", "flag.real): indent = \" \" last_flag = flag # Add", "max(x_px), min(y_px), max(y_px), ) return s def show_goniometer(goniometer): # standard", "foreground_valid = MaskCode.Valid | MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list contains {len(rlist)}", "min(x_px), max(x_px), min(y_px), max(y_px), ) return s def show_goniometer(goniometer): #", "template: text.append(f\"Image template: {template}\") text.append(str(expt.detector)) text.append( \"Max resolution (at corners):", "class: {format_class.__name__}\") if expt.identifier != \"\": text.append(f\"Experiment identifier: {expt.identifier}\") try:", "flags flag_order = sorted(table.flags.values.values(), key=lambda x: x.real) # Build the", "angles.mean() mean_unit_cell = uctbx.unit_cell((a, b, c, alpha, beta, gamma)) text.append(f\"", "\"xyzcal.mm\": \"%.2f, %.2f, %.2f\", \"xyzcal.px\": \"%.2f, %.2f, %.2f\", \"delpsical.rad\": \"%.3f\",", "= bool .help = \"Whether or not to print individual", "flag_order: indent = \"\" # As a hint for reading,", "previous one. if last_flag and (last_flag.real & flag.real): indent =", "\"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f, %.2f\", \"xyzcal.px\": \"%.2f, %.2f, %.2f\",", "} for rlist in reflections: from dials.algorithms.shoebox import MaskCode foreground_valid", "if show_profile_fit: for k in profile_fit_keys: keys_to_print.add(k) if show_centroids: for", "\"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys = (\"miller_index\", \"d\")", "text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text) def show_reflections( reflections, show_intensities=False,", "model_connectivity_impl(experiments, model): text = [\"\"] text.append(f\"{model.capitalize()}:\") models = getattr(experiments, f\"{model}s\")()", "= zip(*xy) s += \"Beam centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm),", "k in keys: columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing", "dials.util.options import OptionParser, reflections_and_experiments_from_files usage = \"dials.show [options] models.expt |", "z1) * (y2 - y1) * (x2 - x1)).as_double() rows.append(", "experiments = ExperimentListFactory.from_json( experiments.as_json(), check_format=True ) except OSError as e:", "the formatted flags table \"\"\" # Calculate the counts of", "e in xy): return s pnl = list(uniq_pnls)[0] x_mm, y_mm", "columns.append( format_column(k, rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing %i of %i", "import dials.util from dials.array_family import flex from dials.util import Sorry,", "any flag which overlaps with the previous one. if last_flag", "panel sv_s0 = beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector, s0) for s0", "rotation sampled at \" + str(goniometer.num_scan_points) + \" scan points\\n\"", "= True elif im_type == \"corrected\": raw = False else:", "set\" image_statistics{ show_corrected = False .type = bool .help =", "is any flag which overlaps with the previous one. if", "Average unit cell: {mean_unit_cell}\") if expt.profile is not None: text.append(str(expt.profile))", "reinstatiate # the experiment list here try: experiments = ExperimentListFactory.from_json(", "[] for i_expt, expt in enumerate(experiments): text.append(\"Experiment %i:\" % i_expt)", "points\\n\" ) return s @dials.util.show_mail_handle_errors() def run(args=None): import dials.util.log dials.util.log.print_banner()", "\" (N pix)\" width = max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" % width", "zip(*xy) s += \"Beam centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm),", "formats.get(k, \"%s\") % col.mean(), ] ) elif isinstance(col, flex.shoebox): rows.append([k,", "for k, col in rlist.cols(): if k in formats and", "key = keys[j] if key == \"shoebox\": key += \"", "dials.util from dials.array_family import flex from dials.util import Sorry, tabulate", "range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data = expt.imageset.get_raw_data(i) else:", "%.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\", \"s1\": \"%.4f, %.4f, %.4f\",", "if any(e == (None, None) for e in xy): return", "+ str(k) + \" -> experiment identifier:\" + str(rlist.experiment_identifiers()[k]) for", "the flags flag_order = sorted(table.flags.values.values(), key=lambda x: x.real) # Build", "% (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if expt.scan is not", "\"s2\": \"%.4f, %.4f, %.4f\", \"shoebox\": \"%.1f\", \"rlp\": \"%.4f, %.4f, %.4f\",", "+= \"Beam centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px), max(y_px),", "= [c.max_element_length() for c in c_strings] for i in range(len(c_strings[0])):", "def beam_centre_raw_image_px(detector, s0): panel_id, (x, y) = beam_centre_mm(detector, s0) panel", "% c_strings[j][i] for j in range(len(c_strings)) ) ) return column", "\"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\":", "text = [] for i_expt, expt in enumerate(experiments): text.append(\"Experiment %i:\"", "dials.util import Sorry, tabulate help_message = \"\"\" Examples:: dials.show models.expt", "one. if last_flag and (last_flag.real & flag.real): indent = \"", "= [] text.append(\"Reflection flags:\") text.append(tabulate(flag_rows, headers=\"firstrow\")) return \"\\n\".join(text) def show_reflections(", "keys_to_print if k in rlist] if max_reflections is not None:", "each corrected image\" show_raw = False .type = bool .help", "line.append(\"%%%is\" % width % key) text.append(\" \".join(line)) for i in", "to the table we're building flag_rows.append( [ indent + flag.name,", "bool show_centroids = False .type = bool show_profile_fit = False", "+ str(goniometer.num_scan_points) + \" scan points\\n\" ) return s @dials.util.show_mail_handle_errors()", "in models: if getattr(e, model) is m: row.append(\"x\") else: row.append(\".\")", "[ \" summed I\", formats.get(k, \"%s\") % flex.min(si), formats.get(k, \"%s\")", "the row to the table we're building flag_rows.append( [ indent", "import dials.util.log dials.util.log.print_banner() from dials.util.options import OptionParser, reflections_and_experiments_from_files usage =", "not all(e.beam for e in experiments): sys.exit(\"Error: experiment has no", "\"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\", \"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\",", "range of scan-varying model beam centres if beam.num_scan_points > 0:", "k in centroid_keys: keys_to_print.add(k) if show_all_reflection_data: for k in formats:", "= set(pnl) if len(uniq_pnls) > 1 or min(uniq_pnls) < 0:", "number of reflections in the output.\" \"\"\", process_includes=True, ) def", "in reflections: from dials.algorithms.shoebox import MaskCode foreground_valid = MaskCode.Valid |", "iotbx.phil.parse( \"\"\"\\ show_scan_varying = False .type = bool .help =", "= beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector, s0) for s0 in sv_s0]", "pnl_data[0].as_1d() for p in pnl_data[1:]: flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data) print(", "None for flag in flag_order: indent = \"\" # As", "\", \".join( (\"%%%is\" % max_element_lengths[j]) % c_strings[j][i] for j in", "\"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\",", "\"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f, %.2f\", \"xyzcal.px\": \"%.2f, %.2f,", "in table.flags.values.items() } # Work out the numeric-value order of", "if panel.is_coord_valid_mm((x, y)): break else: x, y = (None, None)", "{im_type} images\") for i_expt, expt in enumerate(experiments): for i in", "linked to which experiments\" show_all_reflection_data = False .type = bool", "in enumerate(experiments): text.append(\"Experiment %i:\" % i_expt) format_class = expt.imageset.get_format_class() if", "abc = flex.vec3_double() angles = flex.vec3_double() for n in range(expt.crystal.num_scan_points):", "x1)).as_double() rows.append( [ \" N pix\", formats.get(k, \"%s\") % flex.min(bbox_sizes),", "for e in experiments): sys.exit(\"Error: experiment has no detector\") if", "gamma)) text.append(f\" Average unit cell: {mean_unit_cell}\") if expt.profile is not", "str(rlist.experiment_identifiers()[k]) for k in rlist.experiment_identifiers().keys() ) ) ) intensity_keys =", "(y2 - y1) * (x2 - x1)).as_double() rows.append( [ \"", "None and y is not None: x_px, y_px = detector[panel_id].millimeter_to_pixel((x,", "(N pix)\" width = max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" % width %", "bool .help = \"Show a summary table of reflection flags\"", "\" px: panel %i, (%.2f,%.2f)\" % ( panel_id, x_px, y_px,", "text = [] text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\"))", "rows.append( [ k, formats.get(k, \"%s\") % col.min(), formats.get(k, \"%s\") %", ":returns: A string of the formatted flags table \"\"\" #", "zip(*xy) # convert to pixels xy = [detector[pnl].millimeter_to_pixel(e) for e", "= max(5, len(str(max(flag_count.values())))) last_flag = None for flag in flag_order:", "detector[panel_id] x_px, y_px = panel.millimeter_to_pixel((x, y)) offset = panel.get_raw_image_offset() return", "= \"\" # As a hint for reading, indent any", "\"Show which models are linked to which experiments\" show_all_reflection_data =", "in each raw image\" } max_reflections = None .type =", "keys_to_print.add(k) if show_all_reflection_data: for k in formats: keys_to_print.add(k) def format_column(key,", "not None: text.append(str(expt.profile)) if expt.scaling_model is not None: text.append(str(expt.scaling_model)) return", "({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, ) else: beam_centre_mm_str = f\" mm: ({x:.2f},{y:.2f})\"", "= \"dials.show [options] models.expt | image_*.cbf\" parser = OptionParser( usage=usage,", "\"\" # As a hint for reading, indent any 'summary'", "all(e.detector for e in experiments): sys.exit(\"Error: experiment has no detector\")", "string of the formatted flags table \"\"\" # Calculate the", "if max_reflections is not None: max_reflections = min(len(rlist), max_reflections) else:", "for j in range(len(models))]] for j, e in enumerate(experiments): row", "col.max(), formats.get(k, \"%s\") % col.mean(), ] ) elif isinstance(col, flex.shoebox):", "if template: text.append(f\"Image template: {template}\") text.append(str(expt.detector)) text.append( \"Max resolution (at", "if expt.scaling_model is not None: text.append(str(expt.scaling_model)) return \"\\n\".join(text) def show_image_statistics(experiments,", ".type = bool show_centroids = False .type = bool show_profile_fit", "reflections in the output.\" \"\"\", process_includes=True, ) def beam_centre_mm(detector, s0):", "image_*.cbf dials.show observations.refl \"\"\" phil_scope = iotbx.phil.parse( \"\"\"\\ show_scan_varying =", "\"%s\") % flex.mean(bbox_sizes), ] ) fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append( [", "text.append(f\"Format class: {format_class.__name__}\") if expt.identifier != \"\": text.append(f\"Experiment identifier: {expt.identifier}\")", "\"profile.rmsd\", ) profile_fit_keys = (\"miller_index\", \"d\") centroid_keys = ( \"miller_index\",", "text.append(\"\") text.append(f\"Reflection list contains {len(rlist)} reflections\") if len(rlist) == 0:", "= col.as_vec3_double() rows.append( [ k, formats.get(k, \"%s\") % col.min(), formats.get(k,", "range(len(c_strings[0])): column.append( f\"%{len(key)}s\" % \", \".join( (\"%%%is\" % max_element_lengths[j]) %", "\"xyzobs.px.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\", \"s1\": \"%.4f,", "z2 = col.bounding_boxes().parts() bbox_sizes = ((z2 - z1) * (y2", "((z2 - z1) * (y2 - y1) * (x2 -", "show_goniometer(goniometer): # standard static goniometer model string s = str(goniometer)", "the distribution of values in each raw image\" } max_reflections", "print(f\"Five number summary of the {im_type} images\") for i_expt, expt", "s pnl = list(uniq_pnls)[0] x_mm, y_mm = zip(*xy) # convert", "reflections\") if len(rlist) == 0: continue rows = [[\"Column\", \"min\",", "if isinstance(col, flex.miller_index): col = col.as_vec3_double() rows.append( [ k, formats.get(k,", "s += \"\\nBeam centre: \\n\" s += beam_centre_mm_str + \"\\n\"", "to read image data. Please check {e.filename} is accessible\" )", "False .type = bool show_centroids = False .type = bool", "+ \"\\n\" + beam_centre_px_str + \"\\n\" if beam_centre_raw_mm_str: s +=", "%f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if expt.scan is", "\"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\":", "help_message = \"\"\" Examples:: dials.show models.expt dials.show image_*.cbf dials.show observations.refl", "N valid foreground pix\", formats.get(k, \"%s\") % flex.min(fore_valid), formats.get(k, \"%s\")", "bool .help = \"Show statistics on the distribution of values", "# Calculate the counts of entries that match each flag", "mean_unit_cell = uctbx.unit_cell((a, b, c, alpha, beta, gamma)) text.append(f\" Average", "flag in flag_order: indent = \"\" # As a hint", "_create_flag_count_table(table): \"\"\"Generate a summary table of flag values in a", "that wouldn't make sense rows.append( [ k, formats.get(k, \"%s\"), formats.get(k,", "= \" \" last_flag = flag # Add the row", "import OptionParser, reflections_and_experiments_from_files usage = \"dials.show [options] models.expt | image_*.cbf\"", "y) def beam_centre_raw_image_px(detector, s0): panel_id, (x, y) = beam_centre_mm(detector, s0)", "beam): # standard static beam model string s = str(beam)", "if format_class.__name__ != \"Format\": text.append(f\"Format class: {format_class.__name__}\") if expt.identifier !=", "(N pix)\" else: c_strings = [data.as_string(format_strings[0].strip())] column = flex.std_string() max_element_lengths", ") def beam_centre_mm(detector, s0): x, y = (None, None) for", "flex.vec3_double): c_strings = [ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.parts())", "if last_flag and (last_flag.real & flag.real): indent = \" \"", "y_raw_mm, ) else: beam_centre_mm_str = f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str =", "f\"%{len(key)}s\" % \", \".join( (\"%%%is\" % max_element_lengths[j]) % c_strings[j][i] for", "in enumerate(data.as_vec3_double().parts()) ] elif isinstance(data, flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())] elif", "= flex.vec3_double() angles = flex.vec3_double() for n in range(expt.crystal.num_scan_points): (", "in xy): return s pnl = list(uniq_pnls)[0] x_mm, y_mm =", "pixels xy = [detector[pnl].millimeter_to_pixel(e) for e in xy] x_px, y_px", "\"%s\"), formats.get(k, \"%s\"), ] ) elif type(col) in (flex.double, flex.int,", "] ) x1, x2, y1, y2, z1, z2 = col.bounding_boxes().parts()", "px, raw image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, ) x_raw_mm, y_raw_mm =", "string s = str(goniometer) # report whether the goniometer is", "Sorry, tabulate help_message = \"\"\" Examples:: dials.show models.expt dials.show image_*.cbf", "= expt.imageset.get_raw_data(i) else: pnl_data = expt.imageset.get_corrected_data(i) if not isinstance(pnl_data, tuple):", "show_image_statistics(experiments, \"corrected\") if params.show_shared_models: print() print(model_connectivity(experiments)) if len(reflections): print( show_reflections(", "or min(uniq_pnls) < 0: return s if any(e == (None,", "show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) ) def show_experiments(experiments, show_scan_varying=False): text", "values in a reflection table. :param table: A reflection table", "+ \" -> experiment identifier:\" + str(rlist.experiment_identifiers()[k]) for k in", "= (None, None) return panel_id, (x, y) def beam_centre_raw_image_px(detector, s0):", "\"\"\"\\ show_scan_varying = False .type = bool .help = \"Whether", "\"%\" not in formats.get(k, \"%s\"): # Allow blanking out of", "from cctbx import uctbx from dxtbx.model.experiment_list import ExperimentListFactory from scitbx.math", "\"%.3f\", \"kapton_absorption_correction_sigmas\": \"%.3f\", \"inverse_scale_factor\": \"%.3f\", \"inverse_scale_factor_variance\": \"%.3f\", } for rlist", "\"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\",", "(inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if expt.scan", "has no beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if", "= False .type = bool show_profile_fit = False .type =", "true. So we have to reinstatiate # the experiment list", "profile_fit_keys = (\"miller_index\", \"d\") centroid_keys = ( \"miller_index\", \"d\", \"xyzcal.mm\",", "c_strings = [ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.as_vec3_double().parts()) ]", "col.as_double() rows.append( [ k, formats.get(k, \"%s\") % flex.min(col), formats.get(k, \"%s\")", "= expt.imageset.get_corrected_data(i) if not isinstance(pnl_data, tuple): pnl_data = (pnl_data,) flat_data", "dxtbx.model.experiment_list import ExperimentListFactory from scitbx.math import five_number_summary import dials.util from", "Q3: {:.1f} Max: {:.1f}\".format( identifier, *fns ) ) def model_connectivity(experiments):", "format_column(key, data, format_strings=None): if isinstance(data, flex.vec3_double): c_strings = [ c.as_string(format_strings[i].strip())", "col.summed_intensity().observed_value() rows.append( [ \" summed I\", formats.get(k, \"%s\") % flex.min(si),", "else: max_reflections = len(rlist) columns = [] for k in", "formats.get(k, \"%s\") % col.max(), formats.get(k, \"%s\") % col.mean(), ] )", "goniometer model string s = str(goniometer) # report whether the", "bbox_sizes = ((z2 - z1) * (y2 - y1) *", "% flex.mean(fore_valid), ] ) text.append(tabulate(rows, headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist)) if", "[k for k in keys_to_print if k in rlist] if", "beam_centre_mm(detector, beam.get_s0()) if panel_id >= 0 and x is not", "pnl_data = (pnl_data,) flat_data = pnl_data[0].as_1d() for p in pnl_data[1:]:", "flag: np.sum(numpy_flags & value != 0) for value, flag in", "col.bounding_boxes().parts() bbox_sizes = ((z2 - z1) * (y2 - y1)", "text.append(_create_flag_count_table(rlist)) if show_identifiers: if rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers id-map values:\\n%s\"\"\"", "if show_centroids: for k in centroid_keys: keys_to_print.add(k) if show_all_reflection_data: for", "order of the flags flag_order = sorted(table.flags.values.values(), key=lambda x: x.real)", "rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return text if len(experiments) == 1: return", "\"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\", \"profile.correlation\", \"profile.rmsd\", )", "beam_centre_raw_px_str = \" px, raw image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, )", "\"\"\" # Calculate the counts of entries that match each", "\"miller_index\": \"%i, %i, %i\", \"d\": \"%.2f\", \"qe\": \"%.3f\", \"dqe\": \"%.3f\",", "{len(rlist)} reflections\") if len(rlist) == 0: continue rows = [[\"Column\",", "flex.miller_index): c_strings = [ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.as_vec3_double().parts())", "import os import sys import numpy as np import iotbx.phil", "[data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox): x1, x2, y1, y2, z1, z2", "reflection table :returns: A string of the formatted flags table", "\"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\", \"lp\": \"%.3f\",", "values:\\n%s\"\"\" % ( \"\\n\".join( \"id:\" + str(k) + \" ->", "for c in c_strings] for i in range(len(c_strings[0])): column.append( f\"%{len(key)}s\"", "y2, z1, z2 = data.bounding_boxes().parts() bbox_sizes = ((z2 - z1)", "if not all(e.detector for e in experiments): sys.exit(\"Error: experiment has", "image\" } max_reflections = None .type = int .help =", "expt.imageset.get_raw_data(i) else: pnl_data = expt.imageset.get_corrected_data(i) if not isinstance(pnl_data, tuple): pnl_data", "beam.num_scan_points > 0: s += \" s0 sampled at \"", "= \"Whether or not to show the crystal at each", "= bool .help = \"Show experiment identifiers map if set\"", "j, e in enumerate(experiments): row = [\"Experiment %d\" % j]", "elif isinstance(data, flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox): x1,", "m: row.append(\"x\") else: row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return text if", "\"Max resolution (at corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max", "flex.max(si), formats.get(k, \"%s\") % flex.mean(si), ] ) x1, x2, y1,", "os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data = expt.imageset.get_raw_data(i) else: pnl_data = expt.imageset.get_corrected_data(i)", "show_intensities = False .type = bool show_centroids = False .type", "\" + str(beam.num_scan_points) + \" scan points\\n\" # add static", "models are linked to which experiments\" show_all_reflection_data = False .type", "text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return", "flag is any flag which overlaps with the previous one.", "beam centres panel_id, (x, y) = beam_centre_mm(detector, beam.get_s0()) if panel_id", "\"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\":", "identifier, *fns ) ) def model_connectivity(experiments): def model_connectivity_impl(experiments, model): text", "j in range(len(c_strings)) ) ) return column if keys_to_print: keys", "beta, gamma)) a, b, c = abc.mean() alpha, beta, gamma", "if len(rlist) == 0: continue rows = [[\"Column\", \"min\", \"max\",", "= flag # Add the row to the table we're", "enumerate(experiments): text.append(\"Experiment %i:\" % i_expt) format_class = expt.imageset.get_format_class() if format_class.__name__", "pix)\" else: c_strings = [data.as_string(format_strings[0].strip())] column = flex.std_string() max_element_lengths =", "+= \" s0 sampled at \" + str(beam.num_scan_points) + \"", "= (None, None) for panel_id, panel in enumerate(detector): try: x,", "e in xy] x_px, y_px = zip(*xy) s += \"Beam", "a summary table of flag values in a reflection table.", "number summary of the {im_type} images\") for i_expt, expt in", "= [] from orderedset import OrderedSet formats = { \"miller_index\":", "None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc = flex.vec3_double() angles = flex.vec3_double()", "flex.max(bbox_sizes), formats.get(k, \"%s\") % flex.mean(bbox_sizes), ] ) fore_valid = col.count_mask_values(foreground_valid).as_double()", "show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False, ): text = [] from", "\"%s\") % flex.mean(fore_valid), ] ) text.append(tabulate(rows, headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist))", "== \"corrected\": raw = False else: raise ValueError(f\"Unknown im_type: {im_type}\")", "table[\"flags\"].as_numpy_array() flag_count = { flag: np.sum(numpy_flags & value != 0)", "RuntimeError: continue else: if panel.is_coord_valid_mm((x, y)): break else: x, y", "# convert to pixels xy = [detector[pnl].millimeter_to_pixel(e) for e in", "the beam is scan-varying if beam.num_scan_points > 0: s +=", "(%.2f,%.2f)\" % (panel_id, x, y) beam_centre_px_str = \" px: panel", "\"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\",", "summary of the {im_type} images\") for i_expt, expt in enumerate(experiments):", "not None: text.append(show_goniometer(expt.goniometer)) if expt.crystal is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if", "( panel_id, x_px, y_px, ) x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0())", "\"%s\") % col.mean(), ] ) elif isinstance(col, flex.shoebox): rows.append([k, \"\",", "range(len(c_strings)) ) ) return column if keys_to_print: keys = [k", "Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text) def", "valid foreground pix\", formats.get(k, \"%s\") % flex.min(fore_valid), formats.get(k, \"%s\") %", "% flex.mean(col), ] ) elif type(col) in (flex.vec3_double, flex.miller_index): if", "i in range(len(c_strings[0])): column.append( f\"%{len(key)}s\" % \", \".join( (\"%%%is\" %", "= expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c)) angles.append((alpha, beta, gamma)) a, b,", "read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message, ) params, options = parser.parse_args(args=args,", "\"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\",", "string s = str(beam) # report whether the beam is", "pnl = list(uniq_pnls)[0] x_mm, y_mm = zip(*xy) # convert to", "\"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\":", "the previous one. if last_flag and (last_flag.real & flag.real): indent", "if show_identifiers: if rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers id-map values:\\n%s\"\"\" %", "\"%.2f, %.2f, %.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\", \"s1\": \"%.4f, %.4f,", "rows.append( [ k, formats.get(k, \"%s\"), formats.get(k, \"%s\"), formats.get(k, \"%s\"), ]", "\"\": text.append(f\"Experiment identifier: {expt.identifier}\") try: template = expt.imageset.get_template() except AttributeError:", "dials.util.log.print_banner() from dials.util.options import OptionParser, reflections_and_experiments_from_files usage = \"dials.show [options]", "expt.profile is not None: text.append(str(expt.profile)) if expt.scaling_model is not None:", "max_reflections) else: max_reflections = len(rlist) columns = [] for k", "uniq_pnls = set(pnl) if len(uniq_pnls) > 1 or min(uniq_pnls) <", "statistics on the distribution of values in each raw image\"", "# standard static beam model string s = str(beam) #", "for reading, indent any 'summary' flags. # A summary flag", "m in models: if getattr(e, model) is m: row.append(\"x\") else:", "\"%s\"): # Allow blanking out of entries that wouldn't make", "beam_centre_raw_mm_str = \" mm, raw image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, )", "\"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\", \"partial_id\": \"%i\", \"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\",", "data. Please check {e.filename} is accessible\" ) print(f\"Five number summary", "reflections_and_experiments_from_files usage = \"dials.show [options] models.expt | image_*.cbf\" parser =", "format_column(k, rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing %i of %i reflections:\"", "to print individual reflections\" show_intensities = False .type = bool", "if im_type == \"raw\": raw = True elif im_type ==", ") params, options = parser.parse_args(args=args, show_diff_phil=True) reflections, experiments = reflections_and_experiments_from_files(", "\"Ih_values\": \"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\",", ") ) def show_experiments(experiments, show_scan_varying=False): text = [] for i_expt,", "c_strings = [data.as_string(format_strings[0].strip())] column = flex.std_string() max_element_lengths = [c.max_element_length() for", "abc.append((a, b, c)) angles.append((alpha, beta, gamma)) a, b, c =", "def model_connectivity_impl(experiments, model): text = [\"\"] text.append(f\"{model.capitalize()}:\") models = getattr(experiments,", "Setting rotation sampled at \" + str(goniometer.num_scan_points) + \" scan", "\"%i\", \"imageset_id\": \"%i\", \"panel\": \"%i\", \"flags\": \"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\":", "= OptionParser( usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message, )", "row.append(\"x\") else: row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return text if len(experiments)", "f\"{100 * flag_count[flag] / len(table):5.01f}\", ] ) # Build the", "scan-varying beam centres, ensuring all on same panel sv_s0 =", "= \" mm, raw image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, ) else:", "if expt.crystal.num_scan_points: abc = flex.vec3_double() angles = flex.vec3_double() for n", "+ beam_centre_px_str + \"\\n\" if beam_centre_raw_mm_str: s += beam_centre_raw_mm_str +", "continue else: if panel.is_coord_valid_mm((x, y)): break else: x, y =", "flex.shoebox): x1, x2, y1, y2, z1, z2 = data.bounding_boxes().parts() bbox_sizes", "counts of entries that match each flag numpy_flags = table[\"flags\"].as_numpy_array()", "(\"miller_index\", \"d\") centroid_keys = ( \"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\",", "[beam_centre_mm(detector, s0) for s0 in sv_s0] pnl, xy = zip(*impacts)", "\"Show a summary table of reflection flags\" show_identifiers = False", "j in range(len(columns)): key = keys[j] if key == \"shoebox\":", "s += \"Beam centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm),", "= zip(*impacts) uniq_pnls = set(pnl) if len(uniq_pnls) > 1 or", "reflections_and_experiments_from_files( params.input.reflections, params.input.experiments ) if len(experiments) == 0 and len(reflections)", "([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px), max(y_px), ) return s def show_goniometer(goniometer):", "of the flags flag_order = sorted(table.flags.values.values(), key=lambda x: x.real) #", "(expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max resolution (inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) )", "if len(experiments): if not all(e.detector for e in experiments): sys.exit(\"Error:", "+ [str(j) for j in range(len(models))]] for j, e in", "== 1: return \"\" text = [] text.append(\"Experiment / Models\")", "col.mean(), ] ) elif isinstance(col, flex.shoebox): rows.append([k, \"\", \"\", \"\"])", "text.append(str(expt.scaling_model)) return \"\\n\".join(text) def show_image_statistics(experiments, im_type): if im_type == \"raw\":", "= \"\"\" Examples:: dials.show models.expt dials.show image_*.cbf dials.show observations.refl \"\"\"", "y_raw_px, ) x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px, y_raw_px) ) beam_centre_raw_mm_str", "intensity_keys = ( \"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\", \"intensity.sum.variance\", \"background.mean\",", "def show_experiments(experiments, show_scan_varying=False): text = [] for i_expt, expt in", "= reflections_and_experiments_from_files( params.input.reflections, params.input.experiments ) if len(experiments) == 0 and", "\"%s\") % flex.min(fore_valid), formats.get(k, \"%s\") % flex.max(fore_valid), formats.get(k, \"%s\") %", "in rlist.cols(): if k in formats and \"%\" not in", "\"%i\", \"partial_id\": \"%i\", \"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\":", "beam is scan-varying if beam.num_scan_points > 0: s += \"", "%d\" % j] for m in models: if getattr(e, model)", "\"\", \"\"]) si = col.summed_intensity().observed_value() rows.append( [ \" summed I\",", "cell: {mean_unit_cell}\") if expt.profile is not None: text.append(str(expt.profile)) if expt.scaling_model", "if show_intensities: for k in intensity_keys: keys_to_print.add(k) if show_profile_fit: for", "show_all_reflection_data = False .type = bool .help = \"Whether or", "\"%s\") % col.min(), formats.get(k, \"%s\") % col.max(), formats.get(k, \"%s\") %", "k in keys_to_print if k in rlist] if max_reflections is", "\"\\n\" if beam_centre_raw_mm_str: s += beam_centre_raw_mm_str + \"\\n\" if beam_centre_raw_px_str:", "rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers id-map values:\\n%s\"\"\" % ( \"\\n\".join( \"id:\"", "== 0 and len(reflections) == 0: parser.print_help() exit() if len(experiments):", "\"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\", \"intensity.sum.value\": \"%.1f\", \"intensity.sum.variance\": \"%.1f\", \"intensity.cor.value\": \"%.1f\",", "x.real) # Build the actual table flag_rows = [[\"Flag\", \"Count\",", "= (\"miller_index\", \"d\") centroid_keys = ( \"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\",", "np import iotbx.phil from cctbx import uctbx from dxtbx.model.experiment_list import", "= uctbx.unit_cell((a, b, c, alpha, beta, gamma)) text.append(f\" Average unit", "% ( panel_id, x_px, y_px, ) x_raw_px, y_raw_px = beam_centre_raw_image_px(detector,", "unit cell: {mean_unit_cell}\") if expt.profile is not None: text.append(str(expt.profile)) if", "= [\"Experiment %d\" % j] for m in models: if", "\"%.1f\", \"rlp\": \"%.4f, %.4f, %.4f\", \"zeta\": \"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\":", "print( show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers,", ") def show_experiments(experiments, show_scan_varying=False): text = [] for i_expt, expt", "formats.get(k, \"%s\") % flex.max(si), formats.get(k, \"%s\") % flex.mean(si), ] )", "i_expt) format_class = expt.imageset.get_format_class() if format_class.__name__ != \"Format\": text.append(f\"Format class:", "of the {im_type} images\") for i_expt, expt in enumerate(experiments): for", "return s if any(e == (None, None) for e in", "= data.bounding_boxes().parts() bbox_sizes = ((z2 - z1) * (y2 -", "reflections, show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False, ): text", "not None: text.append(str(expt.scaling_model)) return \"\\n\".join(text) def show_image_statistics(experiments, im_type): if im_type", "show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) ) def show_experiments(experiments,", "{expt.identifier}\") try: template = expt.imageset.get_template() except AttributeError: template = None", "flex.size_t): col = col.as_double() rows.append( [ k, formats.get(k, \"%s\") %", "range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm), max(y_mm), ) s +=", "expt.imageset.get_format_class() if format_class.__name__ != \"Format\": text.append(f\"Format class: {format_class.__name__}\") if expt.identifier", "in (flex.vec3_double, flex.miller_index): if isinstance(col, flex.miller_index): col = col.as_vec3_double() rows.append(", "id-map values:\\n%s\"\"\" % ( \"\\n\".join( \"id:\" + str(k) + \"", "text = [\"\"] text.append(f\"{model.capitalize()}:\") models = getattr(experiments, f\"{model}s\")() rows =", "is not None: x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y)) if len(detector)", "%.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e, %.4e\", \"xyzobs.px.value\": \"%.2f, %.2f, %.2f\",", "in enumerate(detector): try: x, y = panel.get_ray_intersection(s0) except RuntimeError: continue", "table: A reflection table :returns: A string of the formatted", "= False .type = bool show_flags = False .type =", "is accessible\" ) print(f\"Five number summary of the {im_type} images\")", "template: {template}\") text.append(str(expt.detector)) text.append( \"Max resolution (at corners): %f\" %", "in sv_s0] pnl, xy = zip(*impacts) uniq_pnls = set(pnl) if", "%.4f, %.4f\", \"s1\": \"%.4f, %.4f, %.4f\", \"s2\": \"%.4f, %.4f, %.4f\",", "models.expt dials.show image_*.cbf dials.show observations.refl \"\"\" phil_scope = iotbx.phil.parse( \"\"\"\\", "len(experiments): if not all(e.detector for e in experiments): sys.exit(\"Error: experiment", "\" summed I\", formats.get(k, \"%s\") % flex.min(si), formats.get(k, \"%s\") %", "any 'summary' flags. # A summary flag is any flag", "% flex.max(si), formats.get(k, \"%s\") % flex.mean(si), ] ) x1, x2,", "\"%s\") % flex.max(bbox_sizes), formats.get(k, \"%s\") % flex.mean(bbox_sizes), ] ) fore_valid", "\"\" text = [] text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments,", "% col.min(), formats.get(k, \"%s\") % col.max(), formats.get(k, \"%s\") % col.mean(),", "all on same panel sv_s0 = beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector,", "\".join( (\"%%%is\" % max_element_lengths[j]) % c_strings[j][i] for j in range(len(c_strings))", "= False .type = bool .help = \"Whether or not", "not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc = flex.vec3_double() angles =", "beam_centre_raw_mm_str + \"\\n\" if beam_centre_raw_px_str: s += beam_centre_raw_px_str + \"\\n\"", "last_flag = flag # Add the row to the table", "c in c_strings] for i in range(len(c_strings[0])): column.append( f\"%{len(key)}s\" %", "for s0 in sv_s0] pnl, xy = zip(*impacts) uniq_pnls =", "not in formats.get(k, \"%s\"): # Allow blanking out of entries", "for p in pnl_data[1:]: flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data) print( \"{}:", "rows = [[\"\"] + [str(j) for j in range(len(models))]] for", "\"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate a summary table of flag values", "def format_column(key, data, format_strings=None): if isinstance(data, flex.vec3_double): c_strings = [", "to which experiments\" show_all_reflection_data = False .type = bool .help", "\"background.mean\", \"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys = (\"miller_index\", \"d\") centroid_keys =", "ExperimentListFactory from scitbx.math import five_number_summary import dials.util from dials.array_family import", "(y2 - y1) * (x2 - x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())]", "% j] for m in models: if getattr(e, model) is", "in formats and \"%\" not in formats.get(k, \"%s\"): # Allow", "map if set\" image_statistics{ show_corrected = False .type = bool", "% \", \".join( (\"%%%is\" % max_element_lengths[j]) % c_strings[j][i] for j", "experiments = reflections_and_experiments_from_files( params.input.reflections, params.input.experiments ) if len(experiments) == 0", "% flex.mean(bbox_sizes), ] ) fore_valid = col.count_mask_values(foreground_valid).as_double() rows.append( [ \"", "formats.get(k, \"%s\") % flex.min(si), formats.get(k, \"%s\") % flex.max(si), formats.get(k, \"%s\")", "zip(*impacts) uniq_pnls = set(pnl) if len(uniq_pnls) > 1 or min(uniq_pnls)", "\"%.4f, %.4f, %.4f\", \"shoebox\": \"%.1f\", \"rlp\": \"%.4f, %.4f, %.4f\", \"zeta\":", "k in formats and \"%\" not in formats.get(k, \"%s\"): #", "# Add the row to the table we're building flag_rows.append(", "= ExperimentListFactory.from_json( experiments.as_json(), check_format=True ) except OSError as e: raise", "[ k, formats.get(k, \"%s\") % col.min(), formats.get(k, \"%s\") % col.max(),", "s @dials.util.show_mail_handle_errors() def run(args=None): import dials.util.log dials.util.log.print_banner() from dials.util.options import", "[[\"\"] + [str(j) for j in range(len(models))]] for j, e", "identifiers id-map values:\\n%s\"\"\" % ( \"\\n\".join( \"id:\" + str(k) +", "key += \" (N pix)\" width = max(len(key), columns[j].max_element_length()) line.append(\"%%%is\"", "indent + flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 * flag_count[flag] / len(table):5.01f}\",", "[data.as_string(format_strings[0].strip())] column = flex.std_string() max_element_lengths = [c.max_element_length() for c in", "params, options = parser.parse_args(args=args, show_diff_phil=True) reflections, experiments = reflections_and_experiments_from_files( params.input.reflections,", "if key == \"shoebox\": key += \" (N pix)\" width", "[\"Experiment %d\" % j] for m in models: if getattr(e,", "line = [] for j in range(len(columns)): key = keys[j]", "s0 sampled at \" + str(beam.num_scan_points) + \" scan points\\n\"", "import MaskCode foreground_valid = MaskCode.Valid | MaskCode.Foreground text.append(\"\") text.append(f\"Reflection list", ") return column if keys_to_print: keys = [k for k", "process_includes=True, ) def beam_centre_mm(detector, s0): x, y = (None, None)", "s0) panel = detector[panel_id] x_px, y_px = panel.millimeter_to_pixel((x, y)) offset", "# report range of scan-varying model beam centres if beam.num_scan_points", "] ) elif isinstance(col, flex.shoebox): rows.append([k, \"\", \"\", \"\"]) si", "= flex.std_string() max_element_lengths = [c.max_element_length() for c in c_strings] for", "reflection table. :param table: A reflection table :returns: A string", "* (x2 - x1)).as_double() rows.append( [ \" N pix\", formats.get(k,", "formats.get(k, \"%s\") % flex.min(bbox_sizes), formats.get(k, \"%s\") % flex.max(bbox_sizes), formats.get(k, \"%s\")", "isinstance(data, flex.miller_index): c_strings = [ c.as_string(format_strings[i].strip()) for i, c in", "c, alpha, beta, gamma)) text.append(f\" Average unit cell: {mean_unit_cell}\") if", "+ str(beam.num_scan_points) + \" scan points\\n\" # add static model", "y_mm = zip(*xy) # convert to pixels xy = [detector[pnl].millimeter_to_pixel(e)", "list(uniq_pnls)[0] x_mm, y_mm = zip(*xy) # convert to pixels xy", "each flag numpy_flags = table[\"flags\"].as_numpy_array() flag_count = { flag: np.sum(numpy_flags", "flex.miller_index): col = col.as_vec3_double() rows.append( [ k, formats.get(k, \"%s\") %", "flag in table.flags.values.items() } # Work out the numeric-value order", ".type = bool .help = \"Whether or not to print", "str(goniometer.num_scan_points) + \" scan points\\n\" ) return s @dials.util.show_mail_handle_errors() def", "print( \"{}: Min: {:.1f} Q1: {:.1f} Med: {:.1f} Q3: {:.1f}", "we're building flag_rows.append( [ indent + flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100", "any(e == (None, None) for e in xy): return s", "show_shared_models = False .type = bool .help = \"Show which", "is not None: text.append(str(expt.profile)) if expt.scaling_model is not None: text.append(str(expt.scaling_model))", "\"Count\", \"%\"]] max_count_len = max(5, len(str(max(flag_count.values())))) last_flag = None for", "& value != 0) for value, flag in table.flags.values.items() }", "uctbx.unit_cell((a, b, c, alpha, beta, gamma)) text.append(f\" Average unit cell:", "has no detector\") if not all(e.beam for e in experiments):", "beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str = \" px, raw image: ({:.2f},{:.2f})\".format( x_raw_px,", "a reflection table. :param table: A reflection table :returns: A", "experiment identifier:\" + str(rlist.experiment_identifiers()[k]) for k in rlist.experiment_identifiers().keys() ) )", "if k in rlist] if max_reflections is not None: max_reflections", "experiment has no detector\") if not all(e.beam for e in", "x: x.real) # Build the actual table flag_rows = [[\"Flag\",", "crystal at each scan point.\" show_shared_models = False .type =", "centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px), max(y_px), ) return", "same panel sv_s0 = beam.get_s0_at_scan_points() impacts = [beam_centre_mm(detector, s0) for", "%i, %i\", \"d\": \"%.2f\", \"qe\": \"%.3f\", \"dqe\": \"%.3f\", \"id\": \"%i\",", "Examples:: dials.show models.expt dials.show image_*.cbf dials.show observations.refl \"\"\" phil_scope =", "formats.get(k, \"%s\"), formats.get(k, \"%s\"), formats.get(k, \"%s\"), ] ) elif type(col)", "\"mean\"]] for k, col in rlist.cols(): if k in formats", "intensity_keys: keys_to_print.add(k) if show_profile_fit: for k in profile_fit_keys: keys_to_print.add(k) if", "return text if len(experiments) == 1: return \"\" text =", "sys import numpy as np import iotbx.phil from cctbx import", "= panel.millimeter_to_pixel((x, y)) offset = panel.get_raw_image_offset() return x_px + offset[0],", "is not None: text.append(show_goniometer(expt.goniometer)) if expt.crystal is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying))", "reading, indent any 'summary' flags. # A summary flag is", "raw image\" } max_reflections = None .type = int .help", "return s @dials.util.show_mail_handle_errors() def run(args=None): import dials.util.log dials.util.log.print_banner() from dials.util.options", "show image statistics, check_format has to be true. So we", "= \"Show experiment identifiers map if set\" image_statistics{ show_corrected =", "check_format has to be true. So we have to reinstatiate", "sys.exit(\"Error: experiment has no detector\") if not all(e.beam for e", "= sorted(table.flags.values.values(), key=lambda x: x.real) # Build the actual table", "(px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px), max(y_px), ) return s def", "= bool show_centroids = False .type = bool show_profile_fit =", "min(uniq_pnls) < 0: return s if any(e == (None, None)", "len(experiments) == 0 and len(reflections) == 0: parser.print_help() exit() if", "= angles.mean() mean_unit_cell = uctbx.unit_cell((a, b, c, alpha, beta, gamma))", "import ExperimentListFactory from scitbx.math import five_number_summary import dials.util from dials.array_family", "%.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f,", "formats.get(k, \"%s\") % flex.mean(col), ] ) elif type(col) in (flex.vec3_double,", "[ \" N pix\", formats.get(k, \"%s\") % flex.min(bbox_sizes), formats.get(k, \"%s\")", "read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message, ) params, options = parser.parse_args(args=args, show_diff_phil=True)", "> 0: s += \" s0 sampled at \" +", "True elif im_type == \"corrected\": raw = False else: raise", "# As a hint for reading, indent any 'summary' flags.", "(pnl_data,) flat_data = pnl_data[0].as_1d() for p in pnl_data[1:]: flat_data.extend(p.as_1d()) fns", "\"shoebox\": \"%.1f\", \"rlp\": \"%.4f, %.4f, %.4f\", \"zeta\": \"%.3f\", \"x_resid\": \"%.3f\",", "flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data) print( \"{}: Min: {:.1f} Q1: {:.1f}", "[c.max_element_length() for c in c_strings] for i in range(len(c_strings[0])): column.append(", ") elif isinstance(col, flex.shoebox): rows.append([k, \"\", \"\", \"\"]) si =", "flat_data = pnl_data[0].as_1d() for p in pnl_data[1:]: flat_data.extend(p.as_1d()) fns =", "if rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers id-map values:\\n%s\"\"\" % ( \"\\n\".join(", "if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if params.show_shared_models:", ") def model_connectivity(experiments): def model_connectivity_impl(experiments, model): text = [\"\"] text.append(f\"{model.capitalize()}:\")", "\"min\", \"max\", \"mean\"]] for k, col in rlist.cols(): if k", "\"beam\")) return \"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate a summary table of", "): text = [] from orderedset import OrderedSet formats =", "in enumerate(data.parts()) ] elif isinstance(data, flex.miller_index): c_strings = [ c.as_string(format_strings[i].strip())", "reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) )", "len(experiments) == 1: return \"\" text = [] text.append(\"Experiment /", "orderedset import OrderedSet formats = { \"miller_index\": \"%i, %i, %i\",", "is scan-varying if beam.num_scan_points > 0: s += \" s0", "getattr(experiments, f\"{model}s\")() rows = [[\"\"] + [str(j) for j in", "(x_raw_px, y_raw_px) ) beam_centre_raw_mm_str = \" mm, raw image: ({:.2f},{:.2f})\".format(", "im_type == \"corrected\": raw = False else: raise ValueError(f\"Unknown im_type:", "numpy_flags = table[\"flags\"].as_numpy_array() flag_count = { flag: np.sum(numpy_flags & value", "format_class = expt.imageset.get_format_class() if format_class.__name__ != \"Format\": text.append(f\"Format class: {format_class.__name__}\")", "xy] x_px, y_px = zip(*xy) s += \"Beam centre range", "if show_all_reflection_data: for k in formats: keys_to_print.add(k) def format_column(key, data,", "flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox): x1, x2, y1,", "[\"\"] text.append(f\"{model.capitalize()}:\") models = getattr(experiments, f\"{model}s\")() rows = [[\"\"] +", "centre: \\n\" s += beam_centre_mm_str + \"\\n\" + beam_centre_px_str +", "def run(args=None): import dials.util.log dials.util.log.print_banner() from dials.util.options import OptionParser, reflections_and_experiments_from_files", "\"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print = OrderedSet() if show_intensities: for", "(flex.vec3_double, flex.miller_index): if isinstance(col, flex.miller_index): col = col.as_vec3_double() rows.append( [", "{:.1f}\".format( identifier, *fns ) ) def model_connectivity(experiments): def model_connectivity_impl(experiments, model):", "s if any(e == (None, None) for e in xy):", "text if len(experiments) == 1: return \"\" text = []", "reflections\" show_intensities = False .type = bool show_centroids = False", ") s += \"Beam centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px),", "\"%s\"), formats.get(k, \"%s\"), formats.get(k, \"%s\"), ] ) elif type(col) in", "resolution (inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0())) ) text.append(\"\") text.append(show_beam(expt.detector, expt.beam)) if", "show_scan_varying = False .type = bool .help = \"Whether or", "row.append(\".\") rows.append(row) text.append(tabulate(rows, tablefmt=\"plain\")) return text if len(experiments) == 1:", "panel in enumerate(detector): try: x, y = panel.get_ray_intersection(s0) except RuntimeError:", "from orderedset import OrderedSet formats = { \"miller_index\": \"%i, %i,", "tablefmt=\"plain\")) return text if len(experiments) == 1: return \"\" text", "- x1)).as_double() c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key += \" (N pix)\"", "len(str(max(flag_count.values())))) last_flag = None for flag in flag_order: indent =", "] elif isinstance(data, flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data, flex.shoebox):", "[ c.as_string(format_strings[i].strip()) for i, c in enumerate(data.parts()) ] elif isinstance(data,", "\"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\":", "experiment list here try: experiments = ExperimentListFactory.from_json( experiments.as_json(), check_format=True )", "text = [] from orderedset import OrderedSet formats = {", "check_format=False, epilog=help_message, ) params, options = parser.parse_args(args=args, show_diff_phil=True) reflections, experiments", "\" \" last_flag = flag # Add the row to", "\"Beam centre range (mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm), max(y_mm), )", ") ) intensity_keys = ( \"miller_index\", \"d\", \"intensity.prf.value\", \"intensity.prf.variance\", \"intensity.sum.value\",", "max_element_lengths = [c.max_element_length() for c in c_strings] for i in", "== (None, None) for e in xy): return s pnl", "models.expt | image_*.cbf\" parser = OptionParser( usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True,", "columns) text.append(\" \".join(line)) return \"\\n\".join(text) if __name__ == \"__main__\": run()", "flag values in a reflection table. :param table: A reflection", "] ) # Build the array of output strings text", "%.2f\", \"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\", \"s1\": \"%.4f, %.4f, %.4f\", \"s2\":", "statistics on the distribution of values in each corrected image\"", "\"Show statistics on the distribution of values in each raw", "gamma, ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters() abc.append((a, b, c)) angles.append((alpha, beta, gamma))", "+ \"\\n\" if beam_centre_raw_mm_str: s += beam_centre_raw_mm_str + \"\\n\" if", "for k in keys_to_print if k in rlist] if max_reflections", "format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing %i of %i reflections:\" % (max_reflections,", "a summary table of reflection flags\" show_identifiers = False .type", "s = str(beam) # report whether the beam is scan-varying", "# report whether the beam is scan-varying if beam.num_scan_points >", "model beam centres panel_id, (x, y) = beam_centre_mm(detector, beam.get_s0()) if", "px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str = \"\" s +=", "\"\\n\" if beam_centre_raw_px_str: s += beam_centre_raw_px_str + \"\\n\" # report", "%.4f, %.4f\", \"shoebox\": \"%.1f\", \"rlp\": \"%.4f, %.4f, %.4f\", \"zeta\": \"%.3f\",", ") else: beam_centre_mm_str = f\" mm: ({x:.2f},{y:.2f})\" beam_centre_px_str = f\"", "# standard static goniometer model string s = str(goniometer) #", "\"%.4f, %.4f, %.4f\", \"zeta\": \"%.3f\", \"x_resid\": \"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\":", "c in enumerate(data.parts()) ] elif isinstance(data, flex.miller_index): c_strings = [", "report whether the goniometer is scan-varying if goniometer.num_scan_points > 0:", "= beam_centre_mm(detector, beam.get_s0()) if panel_id >= 0 and x is", "dials.algorithms.shoebox import MaskCode foreground_valid = MaskCode.Valid | MaskCode.Foreground text.append(\"\") text.append(f\"Reflection", "Build the array of output strings text = [] text.append(\"Reflection", "(x2 - x1)).as_double() rows.append( [ \" N pix\", formats.get(k, \"%s\")", "panel_id, (x, y) def beam_centre_raw_image_px(detector, s0): panel_id, (x, y) =", "\"%.1f\", \"intensity.cor.value\": \"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\":", "each raw image\" } max_reflections = None .type = int", "len(uniq_pnls) > 1 or min(uniq_pnls) < 0: return s if", "not to print individual reflections\" show_intensities = False .type =", "y)): break else: x, y = (None, None) return panel_id,", "mm, raw image: ({:.2f},{:.2f})\".format( x_raw_mm, y_raw_mm, ) else: beam_centre_mm_str =", "= [] for j in range(len(columns)): key = keys[j] if", "= [] text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments,", "None: text.append(str(expt.scan)) if expt.goniometer is not None: text.append(show_goniometer(expt.goniometer)) if expt.crystal", "\"%s\") % col.max(), formats.get(k, \"%s\") % col.mean(), ] ) elif", "col = col.as_double() rows.append( [ k, formats.get(k, \"%s\") % flex.min(col),", "%f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max resolution (inscribed): %f\" %", "usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message, ) params, options", "\"xyzobs.px.variance\": \"%.4f, %.4f, %.4f\", \"s1\": \"%.4f, %.4f, %.4f\", \"s2\": \"%.4f,", "= (pnl_data,) flat_data = pnl_data[0].as_1d() for p in pnl_data[1:]: flat_data.extend(p.as_1d())", "\"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\": \"%i\",", "table \"\"\" # Calculate the counts of entries that match", "len(table):5.01f}\", ] ) # Build the array of output strings", "text.append(\"Printing %i of %i reflections:\" % (max_reflections, len(rlist))) line =", "% max_element_lengths[j]) % c_strings[j][i] for j in range(len(c_strings)) ) )", "\"partial_id\": \"%i\", \"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f,", "elif isinstance(data, flex.shoebox): x1, x2, y1, y2, z1, z2 =", "# A summary flag is any flag which overlaps with", "{template}\") text.append(str(expt.detector)) text.append( \"Max resolution (at corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0()))", "% flex.max(col), formats.get(k, \"%s\") % flex.mean(col), ] ) elif type(col)", "Sorry( f\"Unable to read image data. Please check {e.filename} is", "else: if panel.is_coord_valid_mm((x, y)): break else: x, y = (None,", "flex.min(bbox_sizes), formats.get(k, \"%s\") % flex.max(bbox_sizes), formats.get(k, \"%s\") % flex.mean(bbox_sizes), ]", "min(x_mm), max(x_mm), min(y_mm), max(y_mm), ) s += \"Beam centre range", "bool show_profile_fit = False .type = bool show_flags = False", "in (flex.int, flex.size_t): col = col.as_double() rows.append( [ k, formats.get(k,", "= \" mm: panel %i, (%.2f,%.2f)\" % (panel_id, x, y)", "\"flags\": \"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\",", "def show_reflections( reflections, show_intensities=False, show_profile_fit=False, show_centroids=False, show_all_reflection_data=False, show_flags=False, max_reflections=None, show_identifiers=False,", "keys_to_print: keys = [k for k in keys_to_print if k", "five_number_summary import dials.util from dials.array_family import flex from dials.util import", "and \"%\" not in formats.get(k, \"%s\"): # Allow blanking out", "scan points\\n\" # add static model beam centres panel_id, (x,", "%.4f\", \"s2\": \"%.4f, %.4f, %.4f\", \"shoebox\": \"%.1f\", \"rlp\": \"%.4f, %.4f,", "% col.mean(), ] ) elif isinstance(col, flex.shoebox): rows.append([k, \"\", \"\",", "(None, None) for e in xy): return s pnl =", "max_element_lengths[j]) % c_strings[j][i] for j in range(len(c_strings)) ) ) return", "+= beam_centre_raw_mm_str + \"\\n\" if beam_centre_raw_px_str: s += beam_centre_raw_px_str +", "whether the beam is scan-varying if beam.num_scan_points > 0: s", "show_image_statistics(experiments, im_type): if im_type == \"raw\": raw = True elif", "indent any 'summary' flags. # A summary flag is any", "output.\" \"\"\", process_includes=True, ) def beam_centre_mm(detector, s0): x, y =", ") text.append(tabulate(rows, headers=\"firstrow\")) if show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers: if rlist.experiment_identifiers():", "show_flags = False .type = bool .help = \"Show a", "keys_to_print = OrderedSet() if show_intensities: for k in intensity_keys: keys_to_print.add(k)", ") keys_to_print = OrderedSet() if show_intensities: for k in intensity_keys:", "= list(uniq_pnls)[0] x_mm, y_mm = zip(*xy) # convert to pixels", "is not None: text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc = flex.vec3_double() angles", "goniometer.num_scan_points > 0: s += ( \" Setting rotation sampled", "si = col.summed_intensity().observed_value() rows.append( [ \" summed I\", formats.get(k, \"%s\")", ".type = bool .help = \"Show statistics on the distribution", "show_raw = False .type = bool .help = \"Show statistics", "text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying)) if expt.crystal.num_scan_points: abc = flex.vec3_double() angles = flex.vec3_double() for", "k, formats.get(k, \"%s\") % flex.min(col), formats.get(k, \"%s\") % flex.max(col), formats.get(k,", "check {e.filename} is accessible\" ) print(f\"Five number summary of the", "\"%s\") % flex.min(si), formats.get(k, \"%s\") % flex.max(si), formats.get(k, \"%s\") %", "\" N pix\", formats.get(k, \"%s\") % flex.min(bbox_sizes), formats.get(k, \"%s\") %", "(at corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max resolution (inscribed):", "\"profile.correlation\", \"profile.rmsd\", ) profile_fit_keys = (\"miller_index\", \"d\") centroid_keys = (", "not isinstance(pnl_data, tuple): pnl_data = (pnl_data,) flat_data = pnl_data[0].as_1d() for", "%i:\" % i_expt) format_class = expt.imageset.get_format_class() if format_class.__name__ != \"Format\":", "flex.min(col), formats.get(k, \"%s\") % flex.max(col), formats.get(k, \"%s\") % flex.mean(col), ]", "= expt.imageset.get_format_class() if format_class.__name__ != \"Format\": text.append(f\"Format class: {format_class.__name__}\") if", "show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, )", "show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if params.show_shared_models: print() print(model_connectivity(experiments))", "panel %i, (%.2f,%.2f)\" % ( panel_id, x_px, y_px, ) x_raw_px,", "that match each flag numpy_flags = table[\"flags\"].as_numpy_array() flag_count = {", "\"%.3f\", \"x_resid2\": \"%.3f\", \"y_resid\": \"%.3f\", \"y_resid2\": \"%.3f\", \"kapton_absorption_correction\": \"%.3f\", \"kapton_absorption_correction_sigmas\":", "y = panel.get_ray_intersection(s0) except RuntimeError: continue else: if panel.is_coord_valid_mm((x, y)):", "\"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f, %.2f\",", "rlist[k], format_strings=formats[k].split(\",\")) ) text.append(\"\") text.append(\"Printing %i of %i reflections:\" %", "for i in range(len(c_strings[0])): column.append( f\"%{len(key)}s\" % \", \".join( (\"%%%is\"", "= keys[j] if key == \"shoebox\": key += \" (N", "formats.get(k, \"%s\") % flex.min(fore_valid), formats.get(k, \"%s\") % flex.max(fore_valid), formats.get(k, \"%s\")", "Work out the numeric-value order of the flags flag_order =", "raw = True elif im_type == \"corrected\": raw = False", "expt.scan is not None: text.append(str(expt.scan)) if expt.goniometer is not None:", "key=lambda x: x.real) # Build the actual table flag_rows =", "type(col) in (flex.vec3_double, flex.miller_index): if isinstance(col, flex.miller_index): col = col.as_vec3_double()", "= \"Show statistics on the distribution of values in each", "of entries that wouldn't make sense rows.append( [ k, formats.get(k,", "\"%.3f\", \"delpsical.weights\": \"%.3f\", \"xyzobs.mm.value\": \"%.2f, %.2f, %.2f\", \"xyzobs.mm.variance\": \"%.4e, %.4e,", "expt in enumerate(experiments): text.append(\"Experiment %i:\" % i_expt) format_class = expt.imageset.get_format_class()", "y_px = detector[panel_id].millimeter_to_pixel((x, y)) if len(detector) > 1: beam_centre_mm_str =", "flex.int, flex.size_t): if type(col) in (flex.int, flex.size_t): col = col.as_double()", "% flex.min(col), formats.get(k, \"%s\") % flex.max(col), formats.get(k, \"%s\") % flex.mean(col),", "sampled at \" + str(beam.num_scan_points) + \" scan points\\n\" #", "+= beam_centre_raw_px_str + \"\\n\" # report range of scan-varying model", "show_centroids = False .type = bool show_profile_fit = False .type", "{e.filename} is accessible\" ) print(f\"Five number summary of the {im_type}", "of reflections in the output.\" \"\"\", process_includes=True, ) def beam_centre_mm(detector,", "show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) ) def show_experiments(experiments, show_scan_varying=False): text =", "= \" px, raw image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, ) x_raw_mm,", "0: s += ( \" Setting rotation sampled at \"", "rows.append( [ \" N valid foreground pix\", formats.get(k, \"%s\") %", "table. :param table: A reflection table :returns: A string of", "* flag_count[flag] / len(table):5.01f}\", ] ) # Build the array", "\" scan points\\n\" # add static model beam centres panel_id,", "xy = zip(*impacts) uniq_pnls = set(pnl) if len(uniq_pnls) > 1", "False .type = bool .help = \"Show which models are", "beam model string s = str(beam) # report whether the", "s = str(goniometer) # report whether the goniometer is scan-varying", "text.extend(model_connectivity_impl(experiments, \"detector\")) text.extend(model_connectivity_impl(experiments, \"crystal\")) text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text) def _create_flag_count_table(table):", "/ len(table):5.01f}\", ] ) # Build the array of output", "i_expt, expt in enumerate(experiments): for i in range(len(expt.imageset)): identifier =", "x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0()) beam_centre_raw_px_str = \" px, raw", "col.min(), formats.get(k, \"%s\") % col.max(), formats.get(k, \"%s\") % col.mean(), ]", "y1, y2, z1, z2 = col.bounding_boxes().parts() bbox_sizes = ((z2 -", "show_identifiers: if rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers id-map values:\\n%s\"\"\" % (", "show_flags: text.append(_create_flag_count_table(rlist)) if show_identifiers: if rlist.experiment_identifiers(): text.append( \"\"\"Experiment identifiers id-map", "beam_centre_px_str = f\" px: ({x_px:.2f},{y_px:.2f})\" beam_centre_raw_px_str = \"\" beam_centre_raw_mm_str =", "[str(j) for j in range(len(models))]] for j, e in enumerate(experiments):", ".help = \"Show statistics on the distribution of values in", "flex.min(si), formats.get(k, \"%s\") % flex.max(si), formats.get(k, \"%s\") % flex.mean(si), ]", "\"%.1f\", \"Ih_values\": \"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\":", "if keys_to_print: keys = [k for k in keys_to_print if", "is scan-varying if goniometer.num_scan_points > 0: s += ( \"", "image: ({:.2f},{:.2f})\".format( x_raw_px, y_raw_px, ) x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter( (x_raw_px,", "(x, y) = beam_centre_mm(detector, s0) panel = detector[panel_id] x_px, y_px", "([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm), max(y_mm), ) s += \"Beam centre", "rows.append( [ \" summed I\", formats.get(k, \"%s\") % flex.min(si), formats.get(k,", "\"background.mse\": \"%.1f\", \"background.sum.value\": \"%.1f\", \"background.sum.variance\": \"%.1f\", \"intensity.prf.value\": \"%.1f\", \"intensity.prf.variance\": \"%.1f\",", "elif isinstance(col, flex.shoebox): rows.append([k, \"\", \"\", \"\"]) si = col.summed_intensity().observed_value()", "(mm): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_mm), max(x_mm), min(y_mm), max(y_mm), ) s += \"Beam", "be true. So we have to reinstatiate # the experiment", "text.append(str(expt.detector)) text.append( \"Max resolution (at corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) )", "iotbx.phil from cctbx import uctbx from dxtbx.model.experiment_list import ExperimentListFactory from", "params.input.experiments ) if len(experiments) == 0 and len(reflections) == 0:", "%.4f\", \"shoebox\": \"%.1f\", \"rlp\": \"%.4f, %.4f, %.4f\", \"zeta\": \"%.3f\", \"x_resid\":", "formats = { \"miller_index\": \"%i, %i, %i\", \"d\": \"%.2f\", \"qe\":", "column = flex.std_string() max_element_lengths = [c.max_element_length() for c in c_strings]", "%.2f\", \"xyzcal.px\": \"%.2f, %.2f, %.2f\", \"delpsical.rad\": \"%.3f\", \"delpsical2\": \"%.3f\", \"delpsical.weights\":", "keys_to_print.add(k) def format_column(key, data, format_strings=None): if isinstance(data, flex.vec3_double): c_strings =", "text.append(\" \".join(line)) for i in range(max_reflections): line = (c[i] for", "= max(len(key), columns[j].max_element_length()) line.append(\"%%%is\" % width % key) text.append(\" \".join(line))", "= OrderedSet() if show_intensities: for k in intensity_keys: keys_to_print.add(k) if", "statistics, check_format has to be true. So we have to", "\"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\", \"xyzobs.px.variance\", ) keys_to_print = OrderedSet() if", "\" s0 sampled at \" + str(beam.num_scan_points) + \" scan", "return \"\\n\".join(text) def show_image_statistics(experiments, im_type): if im_type == \"raw\": raw", "= pnl_data[0].as_1d() for p in pnl_data[1:]: flat_data.extend(p.as_1d()) fns = five_number_summary(flat_data)", "corrected image\" show_raw = False .type = bool .help =", "\"%.1f\", \"intensity.cor.variance\": \"%.1f\", \"intensity.scale.value\": \"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\", \"lp\":", "for e in xy): return s pnl = list(uniq_pnls)[0] x_mm,", "range(max_reflections): line = (c[i] for c in columns) text.append(\" \".join(line))", "in intensity_keys: keys_to_print.add(k) if show_profile_fit: for k in profile_fit_keys: keys_to_print.add(k)", "import uctbx from dxtbx.model.experiment_list import ExperimentListFactory from scitbx.math import five_number_summary", "\"%i\", \"flags\": \"%i\", \"background.mean\": \"%.1f\", \"background.dispersion\": \"%.1f\", \"background.mse\": \"%.1f\", \"background.sum.value\":", "z1) * (y2 - y1) * (x2 - x1)).as_double() c_strings", "\"%.1f\", \"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\":", "enumerate(data.as_vec3_double().parts()) ] elif isinstance(data, flex.size_t): c_strings = [data.as_int().as_string(format_strings[0].strip())] elif isinstance(data,", "return x_px + offset[0], y_px + offset[1] def show_beam(detector, beam):", "len(reflections): print( show_reflections( reflections, show_intensities=params.show_intensities, show_profile_fit=params.show_profile_fit, show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections,", "for k in profile_fit_keys: keys_to_print.add(k) if show_centroids: for k in", "\"\" beam_centre_raw_mm_str = \"\" s += \"\\nBeam centre: \\n\" s", "beam\") print(show_experiments(experiments, show_scan_varying=params.show_scan_varying)) if params.image_statistics.show_raw: show_image_statistics(experiments, \"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments,", "set(pnl) if len(uniq_pnls) > 1 or min(uniq_pnls) < 0: return", "Q1: {:.1f} Med: {:.1f} Q3: {:.1f} Max: {:.1f}\".format( identifier, *fns", "break else: x, y = (None, None) return panel_id, (x,", "max(y_mm), ) s += \"Beam centre range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px),", "key == \"shoebox\": key += \" (N pix)\" width =", "formats.get(k, \"%s\") % flex.min(col), formats.get(k, \"%s\") % flex.max(col), formats.get(k, \"%s\")", "in range(len(expt.imageset)): identifier = os.path.basename(expt.imageset.get_image_identifier(i)) if raw: pnl_data = expt.imageset.get_raw_data(i)", "corners): %f\" % (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max resolution (inscribed): %f\"", "data, format_strings=None): if isinstance(data, flex.vec3_double): c_strings = [ c.as_string(format_strings[i].strip()) for", "experiments): sys.exit(\"Error: experiment has no detector\") if not all(e.beam for", "\"inverse_scale_factor_variance\": \"%.3f\", } for rlist in reflections: from dials.algorithms.shoebox import", "run(args=None): import dials.util.log dials.util.log.print_banner() from dials.util.options import OptionParser, reflections_and_experiments_from_files usage", "= None if template: text.append(f\"Image template: {template}\") text.append(str(expt.detector)) text.append( \"Max", "isinstance(data, flex.shoebox): x1, x2, y1, y2, z1, z2 = data.bounding_boxes().parts()", "+ str(rlist.experiment_identifiers()[k]) for k in rlist.experiment_identifiers().keys() ) ) ) intensity_keys", "try: x, y = panel.get_ray_intersection(s0) except RuntimeError: continue else: if", "\"%s\") % flex.max(fore_valid), formats.get(k, \"%s\") % flex.mean(fore_valid), ] ) text.append(tabulate(rows,", "have to reinstatiate # the experiment list here try: experiments", "text.extend(model_connectivity_impl(experiments, \"beam\")) return \"\\n\".join(text) def _create_flag_count_table(table): \"\"\"Generate a summary table", "angles = flex.vec3_double() for n in range(expt.crystal.num_scan_points): ( a, b,", "== 0: parser.print_help() exit() if len(experiments): if not all(e.detector for", "actual table flag_rows = [[\"Flag\", \"Count\", \"%\"]] max_count_len = max(5,", "\" mm: panel %i, (%.2f,%.2f)\" % (panel_id, x, y) beam_centre_px_str", "static model beam centres panel_id, (x, y) = beam_centre_mm(detector, beam.get_s0())", "% (expt.detector.get_max_resolution(expt.beam.get_s0())) ) text.append( \"Max resolution (inscribed): %f\" % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0()))", "range(len(models))]] for j, e in enumerate(experiments): row = [\"Experiment %d\"", "centroid_keys = ( \"miller_index\", \"d\", \"xyzcal.mm\", \"xyzcal.px\", \"xyzobs.mm.value\", \"xyzobs.mm.variance\", \"xyzobs.px.value\",", "show_corrected = False .type = bool .help = \"Show statistics", "\"dqe\": \"%.3f\", \"id\": \"%i\", \"imageset_id\": \"%i\", \"panel\": \"%i\", \"flags\": \"%i\",", "flag_rows.append( [ indent + flag.name, \"{:{:d}d}\".format(flag_count[flag], max_count_len), f\"{100 * flag_count[flag]", "\"%.3f\", \"id\": \"%i\", \"imageset_id\": \"%i\", \"panel\": \"%i\", \"flags\": \"%i\", \"background.mean\":", "\" (N pix)\" else: c_strings = [data.as_string(format_strings[0].strip())] column = flex.std_string()", "OptionParser( usage=usage, phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message, ) params,", "False .type = bool show_flags = False .type = bool", "k in rlist] if max_reflections is not None: max_reflections =", "= bool show_profile_fit = False .type = bool show_flags =", "0: return s if any(e == (None, None) for e", "%i reflections:\" % (max_reflections, len(rlist))) line = [] for j", "c_strings = [bbox_sizes.as_string(format_strings[0].strip())] key += \" (N pix)\" else: c_strings", ") elif type(col) in (flex.vec3_double, flex.miller_index): if isinstance(col, flex.miller_index): col", "OSError as e: raise Sorry( f\"Unable to read image data.", "AttributeError: template = None if template: text.append(f\"Image template: {template}\") text.append(str(expt.detector))", "formats and \"%\" not in formats.get(k, \"%s\"): # Allow blanking", "image_statistics{ show_corrected = False .type = bool .help = \"Show", "points\\n\" # add static model beam centres panel_id, (x, y)", "\"%s\") % flex.mean(si), ] ) x1, x2, y1, y2, z1,", "show_centroids=params.show_centroids, show_all_reflection_data=params.show_all_reflection_data, show_flags=params.show_flags, max_reflections=params.max_reflections, show_identifiers=params.show_identifiers, ) ) def show_experiments(experiments, show_scan_varying=False):", "range (px): ([{:.2f},{:.2f}],[{:.2f},{:.2f}])\\n\".format( min(x_px), max(x_px), min(y_px), max(y_px), ) return s", "!= \"Format\": text.append(f\"Format class: {format_class.__name__}\") if expt.identifier != \"\": text.append(f\"Experiment", "y is not None: x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y)) if", "flags. # A summary flag is any flag which overlaps", "phil=phil_scope, read_experiments=True, read_experiments_from_images=True, read_reflections=True, check_format=False, epilog=help_message, ) params, options =", ") return s @dials.util.show_mail_handle_errors() def run(args=None): import dials.util.log dials.util.log.print_banner() from", "\"dials.show [options] models.expt | image_*.cbf\" parser = OptionParser( usage=usage, phil=phil_scope,", "detector[panel_id].millimeter_to_pixel((x, y)) if len(detector) > 1: beam_centre_mm_str = \" mm:", "\"%s\") % flex.max(si), formats.get(k, \"%s\") % flex.mean(si), ] ) x1,", "in enumerate(experiments): row = [\"Experiment %d\" % j] for m", "not to show the crystal at each scan point.\" show_shared_models", "exit() if len(experiments): if not all(e.detector for e in experiments):", "rlist.experiment_identifiers().keys() ) ) ) intensity_keys = ( \"miller_index\", \"d\", \"intensity.prf.value\",", "\"intensity.scale.variance\": \"%.1f\", \"Ih_values\": \"%.1f\", \"lp\": \"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\",", "(%.2f,%.2f)\" % ( panel_id, x_px, y_px, ) x_raw_px, y_raw_px =", "\"%s\") % flex.mean(col), ] ) elif type(col) in (flex.vec3_double, flex.miller_index):", "if raw: pnl_data = expt.imageset.get_raw_data(i) else: pnl_data = expt.imageset.get_corrected_data(i) if", "\"raw\") if params.image_statistics.show_corrected: show_image_statistics(experiments, \"corrected\") if params.show_shared_models: print() print(model_connectivity(experiments)) if", "text.append(f\"Experiment identifier: {expt.identifier}\") try: template = expt.imageset.get_template() except AttributeError: template", "False .type = bool .help = \"Whether or not to", "for j in range(len(c_strings)) ) ) return column if keys_to_print:", "= col.count_mask_values(foreground_valid).as_double() rows.append( [ \" N valid foreground pix\", formats.get(k,", "experiments.as_json(), check_format=True ) except OSError as e: raise Sorry( f\"Unable", "\"lp\": \"%.3f\", \"num_pixels.background\": \"%i\", \"num_pixels.background_used\": \"%i\", \"num_pixels.foreground\": \"%i\", \"num_pixels.valid\": \"%i\",", "\"%i\", \"partiality\": \"%.4f\", \"profile.correlation\": \"%.3f\", \"profile.rmsd\": \"%.3f\", \"xyzcal.mm\": \"%.2f, %.2f,", "1: return \"\" text = [] text.append(\"Experiment / Models\") text.extend(model_connectivity_impl(experiments,", "for i, c in enumerate(data.as_vec3_double().parts()) ] elif isinstance(data, flex.size_t): c_strings" ]
[ "LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE = \"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\")", "\"Capacity\", \"Input\", \"Item\", \"Product\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\",", "PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\",", "\"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\",", "FROM_OPTIONS = 1 SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA", "PipelineType.COMMON, \"dico\": [\"location\", \"opex\", \"unit\", \"currency\", \"output\", \"names\", \"products\"] },", "1 VOLUME = 2 class PipelineType(Enum): COMMON = 0 PRODUCER", "class ScenarioGeneratorType(IntEnum): FROM_PATHS = 0 FROM_OPTIONS = 1 SPECIFIC_SCENARIOS =", "\"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Process\", \"Capacity\",", "FULL_COST = 2 class ScenarioGeneratorType(IntEnum): FROM_PATHS = 0 FROM_OPTIONS =", "= 1 SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA =", "\"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Capacity\", \"Input\", \"Item\", \"Product\", \"Unit\"],", "\"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: {", "[\"Location\", \"Process\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\",", "[\"Location\", \"ProductionSite\", \"Product\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS:", "DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME", "\"ProductionSite\", \"Process\", \"Capacity\", \"Product\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"ProductionSite\", \"Product\",", "{SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION: {", "MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP = 1 MONITORING_NB_PAGE", "= \"172.29.161.208\" MONITORING_PORT = 5002 MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME =", "\"beneficiation_capex\" }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\", \"sap.product\",", "\"dico\": [\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\", \"production\":", "(PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION: { \"url\":", "PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\", \"production\": None,", "\"Capacity\", \"Product\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"ProductionSite\", \"Product\", \"Process\", \"Capacity\",", "APP_NAME = \"mine2farm\" NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE", "class ShuffleLevel(IntEnum): UNDEFINED = 0 SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS =", "\"mining_options\", \"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\" },", "PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"],", "1 SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED = 4", "\"CAPEX\"] }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\", \"OutputQuality\",", "PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\": [\"Process\", \"InputQuality\",", "\"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\",", "PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"ProductionSite\", \"Process\",", "\"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"]", "PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\":", "Unit\", \"Conversion Rate\"] }, } class ShuffleLevel(IntEnum): UNDEFINED = 0", "[\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Upstream\", \"Downstream\",", "{ \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\":", "DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT = 5001 # Results DB_RESULT_NAME =", "ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = { PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"production\": [\"Name\",", "\"Unit\"] }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE, \"columns\": [\"Type\", \"Product\", \"Unit\"]", "(PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\", \"upstream_layer\":", "\"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION = \"--\" class", "\"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"]", "\"Item\", \"Unit\"], \"capex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\",", "= 2031 class PriceParams(Enum): WACC = 0 TENOR = 1", "\"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\", \"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\":", "\"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\"],", "else None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME =", "{ \"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\":", "4 SHUFFLE_LEVELS = { PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED,", "\"Extraction\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER,", "\"Unit\"], \"opex\": [\"Location\", \"Process\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\",", "0 CASH_COST = 1 FULL_COST = 2 class ScenarioGeneratorType(IntEnum): FROM_PATHS", "= \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME =", "= \"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES", "RANDOMIZE_RESULTS = False # RabbitMQ RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME =", "Model MONIKER_SEPARATOR = \"/\" WACC = 0.1 T0 = 2020", "# -*- coding: utf-8 -*- from enum import Enum, IntEnum,", "SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = { PipelineLayer.MINE:", "ShuffleLevel(IntEnum): UNDEFINED = 0 SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS = 2", "COMMON = 0 PRODUCER = 1 TRANSPORT = 2 BALANCE", "PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\":", "class FunctionType(Enum): COST_PV = 0 CASH_COST = 1 FULL_COST =", "@unique class PipelineLayer(IntEnum): UNDEFINED = -1 MINE = 0 BENEFICIATION", "Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" #", "\"type\": PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\",", "0 TENOR = 1 VOLUME = 2 class PipelineType(Enum): COMMON", "= False class HTML_STATUS(IntEnum): ERROR = -1 OK = 0", "Dashboard DB_LOAD_FROM_SERVICE = True # Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER", "= 3 SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS = { PipelineLayer.MINE: ShuffleLevel.UNDEFINED,", "\"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION: {", "PipelineType.SALES, \"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"data\": \"conv_matrix\"", "\"%s_results\" % DB_NAME if DB_NAME is not None else None", "class HTML_STATUS(IntEnum): ERROR = -1 OK = 0 # Model", "\"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\" }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER,", "\"type\": PipelineType.PRICE, \"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES, \"data\":", "COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\":", "ERROR = -1 OK = 0 # Model MONIKER_SEPARATOR =", "PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\", \"Product\", \"Unit\"], \"opex\":", "\"Product\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS: { \"type\":", "COMMON = 9 SALES_PLAN = 10 MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX", "0 FROM_OPTIONS = 1 SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS", "\"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\", \"production\": None, \"opex\":", "= 4 LOGISTICS = 5 RAW_MATERIALS = 8 COMMON =", "\"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP:", "\"columns\": [\"Initial Unit\", \"Uniform Unit\", \"Conversion Rate\"] }, } class", "SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED", "% DB_NAME if DB_NAME is not None else None DB_DETAILED_RESULT_COLLECTION_NAME", "from enum import Enum, IntEnum, unique import os APP_NAME =", "}, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN: {", "= \"best_scenarios_history\" MONITORING_STEP = 1 MONITORING_NB_PAGE = 10 # Mongodb-bi", "RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS = 17 DB_NAME_BITS = 20 RANDOMIZE_RESULTS", "\"Product\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] },", "{ \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\",", "= 5002 MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME =", "None, \"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE,", "False MODE_DEBUG = False GRANUL_RELAX = False class HTML_STATUS(IntEnum): ERROR", "\"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program", "10 # Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" #", "PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\":", "\"Input\", \"Item\", \"Product\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\",", "\"prioritymines\" }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\",", "\"app/log/\" LOG_FILE = \"%(asctime)_\" + APP_NAME + \".log\" OUTPUT_FOLDER =", "\"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\"", "= \"SIMULATE\" RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME =", "= 25 HEAD_DATA_BITS = 17 DB_NAME_BITS = 20 RANDOMIZE_RESULTS =", "= 12 PIPELINE_SCHEMA = { PipelineLayer.COMMON: { \"type\": PipelineType.COMMON, \"dico\":", "PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION = \"--\" class FunctionType(Enum):", "PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\":", "\"mine.capex\"], \"options\": \"mining_options\", \"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\":", "RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH", "= \"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP =", "\"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\", \"production\":", "\"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP = 1 MONITORING_NB_PAGE = 10", "MINE = 0 BENEFICIATION = 1 SAP = 2 PAP", "MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA = { PipelineLayer.COMMON:", "\"Humidity\", \"Unit\"], \"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"], \"capex\": [\"Name\",", "\"capex\": \"pap_capex\", \"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"dico\":", "APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER + \"app/log/\" LOG_FILE", "PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\", \"Quality\", \"Unit\"], \"opex\":", "PipelineType.PRICE, \"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES, \"data\": \"sales_plan\"", "\"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"data\":", "\"Process\", \"Capacity\", \"Input\", \"Item\", \"Product\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\",", "\"production\": [\"Name\", \"Extraction\", \"Quality\", \"Unit\"], \"opex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\",", "\"granulation_options\", \"production\": \"granulation_production\", \"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS: {", "\"Unit\"], \"capex\": [\"Location\", \"ProductionSite\", \"Product\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"]", "None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\"", "}, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"],", "= 5006 DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT = 5001 # Results", "5001 # Results DB_RESULT_NAME = \"%s_results\" % DB_NAME if DB_NAME", "\"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\", \"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\",", "\"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES, \"data\": \"sales_plan\" },", "= \"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH = \"C:\\\\Program", "MODE_DEBUG = False GRANUL_RELAX = False class HTML_STATUS(IntEnum): ERROR =", "\"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Location\",", "\"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER,", "= 0 # Model MONIKER_SEPARATOR = \"/\" WACC = 0.1", "DB_NAME is not None else None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME", "= ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = { PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"production\":", "MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT = 5002 MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME", "{ PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION }", "\"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Capacity\", \"Input\", \"Item\", \"Product\",", "'localhost' MEMCACHED_PORT = 11211 # Dashboard DB_LOAD_FROM_SERVICE = True #", "OUTPUT_FOLDER = \"%s%s\" % (APP_FOLDER, \"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" #", "False # RabbitMQ RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE", "\"production\": \"granulation_production\", \"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS: { \"type\":", "\"type\": PipelineType.COMMON, \"dico\": [\"location\", \"opex\", \"unit\", \"currency\", \"output\", \"names\", \"products\"]", "}, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"columns\": [\"Initial Unit\", \"Uniform Unit\",", "\"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Capacity\", \"Input\",", "[\"Name\", \"Extraction\", \"Quality\", \"Unit\"], \"opex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\"],", "[\"Type\", \"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"columns\": [\"Initial", "PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\",", "}, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\",", "\"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" },", "PipelineType.COMMON, \"data\": \"conv_matrix\" }, } SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL =", "SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = { PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER,", "\"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP = 1", "WACC = 0.1 T0 = 2020 TMAX = 2031 class", "MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP", "+ \"app/log/\" LOG_FILE = \"%(asctime)_\" + APP_NAME + \".log\" OUTPUT_FOLDER", "5006 DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT = 5001 # Results DB_RESULT_NAME", "[\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS:", "is not None else None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME =", "{ \"type\": PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\", \"Product\", \"Unit\"], \"opex\": [\"Location\",", "\"options\": \"mining_options\", \"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\"", "\"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\"", "\"type\": PipelineType.COMMON, \"data\": \"conv_matrix\" }, } SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL", "\"opex\": [\"Location\", \"Process\", \"Capacity\", \"Input\", \"Item\", \"Product\", \"Unit\"], \"capex\": [\"Location\",", "Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT = 5002", "PipelineType(Enum): COMMON = 0 PRODUCER = 1 TRANSPORT = 2", "DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS", "10 MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA = {", "LOG_LEVEL_FILE = \"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER", "= 17 DB_NAME_BITS = 20 RANDOMIZE_RESULTS = False # RabbitMQ", "= 2 PAP = 3 GRANULATION = 4 LOGISTICS =", "RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached", "[\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Capacity\", \"Input\", \"Item\",", "4 SALES = 5 @unique class PipelineLayer(IntEnum): UNDEFINED = -1", "\"granulation_opex\", \"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\",", "Rate\"] }, } class ShuffleLevel(IntEnum): UNDEFINED = 0 SHUFFLE_WITHOUT_PERM =", "2 BALANCE = 3 PRICE = 4 SALES = 5", "\"type\": PipelineType.PRICE, \"columns\": [\"Type\", \"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\":", "= 0 TENOR = 1 VOLUME = 2 class PipelineType(Enum):", "= \"%s_results\" % DB_NAME if DB_NAME is not None else", "DB_HOST = \"172.29.161.208\" DB_PORT = 5006 DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT", "\"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"dico\":", "PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE, \"columns\": [\"Type\", \"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX:", "[\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\", \"production\": \"pap_production\",", "\"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\":", "\"Unit\"], \"capex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"]", "DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE", "{ \"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\",", "\"opex\": [\"Location\", \"ProductionSite\", \"Process\", \"Capacity\", \"Product\", \"Item\", \"Unit\"], \"capex\": [\"Location\",", "= 0 FROM_OPTIONS = 1 SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE =", "= \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP = 1 MONITORING_NB_PAGE =", "COMBO_NODES_SEPARATION = \"--\" class FunctionType(Enum): COST_PV = 0 CASH_COST =", "\"capex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] },", "\"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" #", "PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION: ShuffleLevel.UNDEFINED, PipelineLayer.LOGISTICS: ShuffleLevel.UNDEFINED, PipelineLayer.MINE_BENEFICIATION: ShuffleLevel.UNDEFINED", "[\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION: { \"type\":", "0.1 T0 = 2020 TMAX = 2031 class PriceParams(Enum): WACC", "\"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION: { \"type\":", "\"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\", \"production\": \"granulation_production\", \"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\"", "enum import Enum, IntEnum, unique import os APP_NAME = \"mine2farm\"", "{ \"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\",", "PipelineLayer(IntEnum): UNDEFINED = -1 MINE = 0 BENEFICIATION = 1", "= 3 GRANULATION = 4 LOGISTICS = 5 RAW_MATERIALS =", "Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH", "\"mining_capex\", \"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\",", "# Model MONIKER_SEPARATOR = \"/\" WACC = 0.1 T0 =", "\"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION: {", "\"opex\", \"unit\", \"currency\", \"output\", \"names\", \"products\"] }, PipelineLayer.MINE: { \"type\":", "\"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION: { \"type\":", "= 4 SALES = 5 @unique class PipelineLayer(IntEnum): UNDEFINED =", "}, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\",", "= \"%s%s\" % (APP_FOLDER, \"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" # DB", "3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE", "\"type\": PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE,", "VOLUME = 2 class PipelineType(Enum): COMMON = 0 PRODUCER =", "\"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"production\":", "}, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\",", "\"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"],", "\"sap___power_plant_capex\", \"product_type\": \"sap.product\" }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\",", "UNDEFINED = -1 MINE = 0 BENEFICIATION = 1 SAP", "\"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"data\": \"raw_materials\" },", "}, } SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\":", "\"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT =", "# Results DB_RESULT_NAME = \"%s_results\" % DB_NAME if DB_NAME is", "= { PipelineLayer.COMMON: { \"type\": PipelineType.COMMON, \"dico\": [\"location\", \"opex\", \"unit\",", "= 0 BENEFICIATION = 1 SAP = 2 PAP =", "PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\", \"production\":", "{ \"type\": PipelineType.PRICE, \"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES,", "\"Item\", \"Unit\"], \"capex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] },", "\"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\":", "= False GRANUL_RELAX = False class HTML_STATUS(IntEnum): ERROR = -1", "MEMCACHED_PORT = 11211 # Dashboard DB_LOAD_FROM_SERVICE = True # Monitoring", "{ \"type\": PipelineType.COMMON, \"dico\": [\"location\", \"opex\", \"unit\", \"currency\", \"output\", \"names\",", "= \"172.29.161.208\" DB_PORT = 5006 DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT =", "\"columns\": [\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE, \"columns\": [\"Type\",", "\"granulation_capex\" }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\",", "DB_RESULT_NAME = \"%s_results\" % DB_NAME if DB_NAME is not None", "\"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\",", "RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER", "\"Product\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\",", "\"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\", \"production\": \"mining_specific_production\", \"opex\":", "\"CAPEX\"] }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\", \"Method\",", "\"Uniform Unit\", \"Conversion Rate\"] }, } class ShuffleLevel(IntEnum): UNDEFINED =", "= 5001 # Results DB_RESULT_NAME = \"%s_results\" % DB_NAME if", "[\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\",", "\"%(asctime)_\" + APP_NAME + \".log\" OUTPUT_FOLDER = \"%s%s\" % (APP_FOLDER,", "\"Conversion Rate\"] }, } class ShuffleLevel(IntEnum): UNDEFINED = 0 SHUFFLE_WITHOUT_PERM", "PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\",", "\"Extraction\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\",", "\"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"columns\": [\"Item\",", "\"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\"", "FunctionType(Enum): COST_PV = 0 CASH_COST = 1 FULL_COST = 2", "[\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\",", "{ \"type\": PipelineType.COMMON, \"data\": \"conv_matrix\" }, } SUPPLY_CHAIN = \"mine2port\"", "= 'localhost' MEMCACHED_PORT = 11211 # Dashboard DB_LOAD_FROM_SERVICE = True", "\"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"dico\":", "\"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\", \"production\": \"pap_production\", \"opex\":", "\"Product\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"ProductionSite\", \"Product\", \"Process\", \"Capacity\", \"Item\",", "PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN: {", "\"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER + \"app/log/\" LOG_FILE = \"%(asctime)_\" +", "\"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS = 17", "\"172.29.161.208\" DB_PORT = 5006 DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT = 5001", "= 0 PRODUCER = 1 TRANSPORT = 2 BALANCE =", "= \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT", "= 1 VOLUME = 2 class PipelineType(Enum): COMMON = 0", "= 5 @unique class PipelineLayer(IntEnum): UNDEFINED = -1 MINE =", "PAP = 3 GRANULATION = 4 LOGISTICS = 5 RAW_MATERIALS", "\"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\",", "\"Product\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE,", "TENOR = 1 VOLUME = 2 class PipelineType(Enum): COMMON =", "utf-8 -*- from enum import Enum, IntEnum, unique import os", "= 0 CASH_COST = 1 FULL_COST = 2 class ScenarioGeneratorType(IntEnum):", "\"Process\", \"Capacity\", \"Product\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"ProductionSite\", \"Product\", \"Process\",", "HTML_STATUS(IntEnum): ERROR = -1 OK = 0 # Model MONIKER_SEPARATOR", "\"columns\": [\"Type\", \"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"columns\":", "\"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"columns\": [\"Initial Unit\",", "\"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\" },", "HEAD_DATA_BITS = 17 DB_NAME_BITS = 20 RANDOMIZE_RESULTS = False #", "}, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE, \"columns\": [\"Type\", \"Product\", \"Unit\"] },", "\"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER,", "PipelineLayer.COMMON: { \"type\": PipelineType.COMMON, \"dico\": [\"location\", \"opex\", \"unit\", \"currency\", \"output\",", "DB_NAME_BITS = 20 RANDOMIZE_RESULTS = False # RabbitMQ RABBITMQ_SERVER =", "RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER = 'localhost'", "\"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\": [\"Process\",", "}, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\", \"Product\", \"Unit\"],", "Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT = 11211", "OK = 0 # Model MONIKER_SEPARATOR = \"/\" WACC =", "= RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER", "MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT = 5002 MONITORING_DB_NAME", "PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN: { \"type\":", "\"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"data\": \"conv_matrix\" }, }", "\"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\", \"production\": \"granulation_production\",", "= 1 SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED =", "\"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"production\":", "import Enum, IntEnum, unique import os APP_NAME = \"mine2farm\" NETWORK_NAME", "PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\",", "True # Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT", "[\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\", \"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\",", "\"pap_capex\", \"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\",", "\"sensitivity\" RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS = 17 DB_NAME_BITS = 20", "\"data\": \"conv_matrix\" }, } SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN:", "\"options\": \"logistics_options\", \"production\": None, \"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS:", "\"currency\", \"output\", \"names\", \"products\"] }, PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"dico\":", "SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS = { PipelineLayer.MINE:", "BALANCE = 3 PRICE = 4 SALES = 5 @unique", "SALES = 5 @unique class PipelineLayer(IntEnum): UNDEFINED = -1 MINE", "{ PipelineLayer.COMMON: { \"type\": PipelineType.COMMON, \"dico\": [\"location\", \"opex\", \"unit\", \"currency\",", "{ \"type\": PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN: { \"type\":", "} SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP,", "} } COMBO_NODES_SEPARATION = \"--\" class FunctionType(Enum): COST_PV = 0", "[\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.PAP: { \"type\":", "\"Item\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] },", "BENEFICIATION = 1 SAP = 2 PAP = 3 GRANULATION", "\"output\", \"names\", \"products\"] }, PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\",", "[\"location\", \"opex\", \"unit\", \"currency\", \"output\", \"names\", \"products\"] }, PipelineLayer.MINE: {", "DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES = {", "= 10 MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA =", "= 2020 TMAX = 2031 class PriceParams(Enum): WACC = 0", "= \"%(asctime)_\" + APP_NAME + \".log\" OUTPUT_FOLDER = \"%s%s\" %", "# Dashboard DB_LOAD_FROM_SERVICE = True # Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\"", "PipelineLayer.PAP)} COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE,", "[\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Process\", \"Capacity\", \"Item\",", "\"Unit\"], \"capex\": [\"Name\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.SAP:", "PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION: ShuffleLevel.UNDEFINED,", "\"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\" }, PipelineLayer.PAP: { \"type\":", "= 1 FULL_COST = 2 class ScenarioGeneratorType(IntEnum): FROM_PATHS = 0", "\"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION: {", "\"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"ProductionSite\",", "[\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\":", "4 LOGISTICS = 5 RAW_MATERIALS = 8 COMMON = 9", "IntEnum, unique import os APP_NAME = \"mine2farm\" NETWORK_NAME = \"CenterAxis\"", "{ PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION:", "[\"Location\", \"Process\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Item\", \"Unit\"], \"capex\":", "[\"Location\", \"Process\", \"Capacity\", \"Input\", \"Item\", \"Product\", \"Unit\"], \"capex\": [\"Location\", \"Process\",", "\"type\": PipelineType.COMMON, \"columns\": [\"Initial Unit\", \"Uniform Unit\", \"Conversion Rate\"] },", "{ \"type\": PipelineType.PRICE, \"columns\": [\"Type\", \"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: {", "MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT = 11211 # Dashboard DB_LOAD_FROM_SERVICE =", "\"raw_materials\" }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES, \"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX:", "\"Unit\"], \"opex\": [\"Location\", \"Process\", \"Capacity\", \"Input\", \"Item\", \"Product\", \"Unit\"], \"capex\":", "\"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER,", "\"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\",", "[\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\",", "{ \"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\",", "PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION = \"--\" class FunctionType(Enum): COST_PV =", "NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE = \"INFO\" APP_FOLDER", "20 RANDOMIZE_RESULTS = False # RabbitMQ RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME", "import os APP_NAME = \"mine2farm\" NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE =", "\"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\",", "\"WARNING\" LOG_LEVEL_FILE = \"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER =", "\"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER + \"app/log/\"", "}, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\",", "UNDEFINED = 0 SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS", "}, PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"],", "RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER =", "= os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER + \"app/log/\" LOG_FILE =", "False GRANUL_RELAX = False class HTML_STATUS(IntEnum): ERROR = -1 OK", "PIPELINE_METADATA = { PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\",", "\"Unit\"], \"opex\": [\"Location\", \"ProductionSite\", \"Process\", \"Capacity\", \"Product\", \"Item\", \"Unit\"], \"capex\":", "CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME = None DB_HOST =", "APP_FOLDER + \"app/log/\" LOG_FILE = \"%(asctime)_\" + APP_NAME + \".log\"", "0 SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3", "25 HEAD_DATA_BITS = 17 DB_NAME_BITS = 20 RANDOMIZE_RESULTS = False", "= 1 MONITORING_NB_PAGE = 10 # Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program", "\"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"production\":", "WACC = 0 TENOR = 1 VOLUME = 2 class", "# DB DB_NAME = None DB_HOST = \"172.29.161.208\" DB_PORT =", "\"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\",", "Server\\\\rabbitmq_server-3.8.1\\\\sbin\" # Memcached MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT = 11211 #", "}, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"],", "\"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\",", "{ \"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\", \"pap.product\", \"pap.capex\", \"pap.size[kt]\", \"pap.input\"],", "\"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\",", "RabbitMQ RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE = 3", "= \"172.29.161.208\" DATA_SERVICE_PORT = 5001 # Results DB_RESULT_NAME = \"%s_results\"", "class PriceParams(Enum): WACC = 0 TENOR = 1 VOLUME =", "\"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER,", "(APP_FOLDER, \"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME = None", "LOGISTICS_LP = False MODE_DEBUG = False GRANUL_RELAX = False class", "DB_NAME if DB_NAME is not None else None DB_DETAILED_RESULT_COLLECTION_NAME =", "\"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\":", "DB_NAME = None DB_HOST = \"172.29.161.208\" DB_PORT = 5006 DATA_SERVICE_ADD", "\"Item\", \"Product\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"]", "\"pap.product\" }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\",", "\"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"] },", "\"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"ProductionSite\", \"Process\", \"Capacity\", \"Product\", \"Item\",", "[\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE, \"columns\": [\"Type\", \"Product\",", "\"type\": PipelineType.PRODUCER, \"dico\": [\"beneficiation.name\", \"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\":", "\"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\",", "\"SIMULATE\" RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\"", "# params LOGISTICS_LP = False MODE_DEBUG = False GRANUL_RELAX =", "DB_LOAD_FROM_SERVICE = True # Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER =", "\"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\",", "= \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH =", "os APP_NAME = \"mine2farm\" NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\"", "\"logistics_opex\", \"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"data\": \"raw_materials\"", "\"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\" }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"dico\":", "GRANUL_RELAX = False class HTML_STATUS(IntEnum): ERROR = -1 OK =", "\"ProductionSite\", \"Product\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS: {", "17 DB_NAME_BITS = 20 RANDOMIZE_RESULTS = False # RabbitMQ RABBITMQ_SERVER", "= {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES = { PipelineLayer.MINE_BENEFICIATION:", "2 class ScenarioGeneratorType(IntEnum): FROM_PATHS = 0 FROM_OPTIONS = 1 SPECIFIC_SCENARIOS", "= 4 SHUFFLE_LEVELS = { PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP:", "DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME", "BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP", "PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\", \"production\": \"mining_specific_production\",", "\"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"opex\":", "PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"columns\": [\"Initial Unit\", \"Uniform Unit\", \"Conversion", "= \"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT = 5002 MONITORING_DB_NAME =", "\"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP = False MODE_DEBUG = False", "}, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\",", "MONITORING_PORT = 5002 MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME", "PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES, \"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\":", "PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\"], \"capex\":", "= \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME =", "= 10 # Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\"", "Enum, IntEnum, unique import os APP_NAME = \"mine2farm\" NETWORK_NAME =", "}, } class ShuffleLevel(IntEnum): UNDEFINED = 0 SHUFFLE_WITHOUT_PERM = 1", "FROM_PATHS = 0 FROM_OPTIONS = 1 SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE", "\"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"columns\":", "\"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\"", "PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Item\",", "\"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Process\", \"Capacity\", \"Item\", \"Unit\",", "{ \"type\": PipelineType.TRANSPORT, \"opex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\",", "\"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION =", "\"options\": \"pap_options\", \"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\": \"pap.product\"", "ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION: ShuffleLevel.UNDEFINED, PipelineLayer.LOGISTICS: ShuffleLevel.UNDEFINED, PipelineLayer.MINE_BENEFICIATION:", "[\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"ProductionSite\", \"Process\", \"Capacity\", \"Product\",", "\"172.29.161.208\" MONITORING_PORT = 5002 MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\"", "= \"/\" WACC = 0.1 T0 = 2020 TMAX =", "PRODUCER = 1 TRANSPORT = 2 BALANCE = 3 PRICE", "\"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\":", "\"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\", \"production\": None, \"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\"", "\"type\": PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\", \"Quality\", \"Unit\"], \"opex\": [\"Name\", \"Extraction\",", "\"names\", \"products\"] }, PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\",", "SHUFFLE_LEVELS = { PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP:", "\"/\" WACC = 0.1 T0 = 2020 TMAX = 2031", "{ PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\", \"Quality\", \"Unit\"],", "2 class PipelineType(Enum): COMMON = 0 PRODUCER = 1 TRANSPORT", "\"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER,", "RAW_MATERIALS = 8 COMMON = 9 SALES_PLAN = 10 MINE_BENEFICIATION", "MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH =", "PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\":", "MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP = False MODE_DEBUG", "\"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\",", "= \"WARNING\" LOG_LEVEL_FILE = \"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER", "\"dico\": [\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\",", "\"conv_matrix\" }, } SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE),", "SUPPLY_CHAIN = \"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)}", "\"Process\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Item\", \"Unit\"], \"capex\": [\"Location\",", "ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION: ShuffleLevel.UNDEFINED, PipelineLayer.LOGISTICS: ShuffleLevel.UNDEFINED, PipelineLayer.MINE_BENEFICIATION: ShuffleLevel.UNDEFINED }", "if DB_NAME is not None else None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\"", "\"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"data\": \"raw_materials\" }, PipelineLayer.SALES_PLAN:", "= 2 class ScenarioGeneratorType(IntEnum): FROM_PATHS = 0 FROM_OPTIONS = 1", "= { PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\", \"Quality\",", "5 RAW_MATERIALS = 8 COMMON = 9 SALES_PLAN = 10", "\"logistics.capex\"], \"options\": \"logistics_options\", \"production\": None, \"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\" },", "\"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME = None DB_HOST", "[\"Name\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.SAP: { \"type\":", "\"granulation.input\"], \"options\": \"granulation_options\", \"production\": \"granulation_production\", \"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\" },", "TRANSPORT = 2 BALANCE = 3 PRICE = 4 SALES", "\"Unit\"], \"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Process\",", "= 0 SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS =", "MONIKER_SEPARATOR = \"/\" WACC = 0.1 T0 = 2020 TMAX", "= \"mine2farm\" NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE =", "= 2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = { PipelineLayer.MINE: {", "\"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\": \"pap.product\" }, PipelineLayer.GRANULATION:", "\"%s%s\" % (APP_FOLDER, \"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME", "3 PRICE = 4 SALES = 5 @unique class PipelineLayer(IntEnum):", "PIPELINE_SCHEMA = { PipelineLayer.COMMON: { \"type\": PipelineType.COMMON, \"dico\": [\"location\", \"opex\",", "0 # Model MONIKER_SEPARATOR = \"/\" WACC = 0.1 T0", "\"logistics_options\", \"production\": None, \"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: {", "COST_PV = 0 CASH_COST = 1 FULL_COST = 2 class", "SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS = { PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED,", "= \"--\" class FunctionType(Enum): COST_PV = 0 CASH_COST = 1", "# Mongodb MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP =", "RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME", "9 SALES_PLAN = 10 MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX = 12", "PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\":", "\"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT = 5002 MONITORING_DB_NAME = \"task_history\"", "PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"data\": \"conv_matrix\" }, } SUPPLY_CHAIN =", "= \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME =", "PRICE = 4 SALES = 5 @unique class PipelineLayer(IntEnum): UNDEFINED", "MONITORING_STEP = 1 MONITORING_NB_PAGE = 10 # Mongodb-bi MONGODB_BI_PATH =", "\"mine.extraction\", \"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\", \"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\":", "= 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME = \"SAVE_DETAIL\" RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER =", "= \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS =", "5 @unique class PipelineLayer(IntEnum): UNDEFINED = -1 MINE = 0", "# Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector for BI\\\\2.13\\\\bin\" # Mongodb", "\"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\", \"production\": \"granulation_production\", \"opex\": \"granulation_opex\", \"capex\":", "\"pap_options\", \"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\": \"pap.product\" },", "\"Unit\", \"CAPEX\"] }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\",", "[\"Location\", \"ProductionSite\", \"Process\", \"Capacity\", \"Product\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"ProductionSite\",", "{ \"type\": PipelineType.COMMON, \"columns\": [\"Initial Unit\", \"Uniform Unit\", \"Conversion Rate\"]", "\"CAPEX\"] }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Location\", \"Process\", \"Product\",", "\"OutputQuality\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"]", "11211 # Dashboard DB_LOAD_FROM_SERVICE = True # Monitoring MONITORING_APP_NAME =", "= 2 class PipelineType(Enum): COMMON = 0 PRODUCER = 1", "\"options\": \"granulation_options\", \"production\": \"granulation_production\", \"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS:", "\"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\",", "{ \"type\": PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\", \"Quality\", \"Unit\"], \"opex\": [\"Name\",", "-1 OK = 0 # Model MONIKER_SEPARATOR = \"/\" WACC", "\"capex\": [\"Location\", \"ProductionSite\", \"Product\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] },", "\"best_scenarios_history\" MONITORING_STEP = 1 MONITORING_NB_PAGE = 10 # Mongodb-bi MONGODB_BI_PATH", "= { PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION", "params LOGISTICS_LP = False MODE_DEBUG = False GRANUL_RELAX = False", "1 TRANSPORT = 2 BALANCE = 3 PRICE = 4", "= \"sensitivity\" RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS = 17 DB_NAME_BITS =", "unique import os APP_NAME = \"mine2farm\" NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE", "2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS = {", "5002 MONITORING_DB_NAME = \"task_history\" MONITORING_COLLECTION_HISTORY_NAME = \"task\" MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\"", "\"dico\": [\"location\", \"opex\", \"unit\", \"currency\", \"output\", \"names\", \"products\"] }, PipelineLayer.MINE:", "\"CAPEX\"] }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\",", "= True # Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\"", "11 UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA = { PipelineLayer.COMMON: { \"type\":", "= 11211 # Dashboard DB_LOAD_FROM_SERVICE = True # Monitoring MONITORING_APP_NAME", "\"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION:", "\"Quality\", \"Unit\"], \"opex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Name\",", "\"--\" class FunctionType(Enum): COST_PV = 0 CASH_COST = 1 FULL_COST", "\"production\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\",", "0 BENEFICIATION = 1 SAP = 2 PAP = 3", "\"beneficitation.process\", \"beneficitation.quality\", \"beneficitation.capex\"], \"options\": \"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\":", "\"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\",", "2031 class PriceParams(Enum): WACC = 0 TENOR = 1 VOLUME", "MONITORING_NB_PAGE = 10 # Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector for", "1 SPECIFIC_SCENARIOS = 2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = {", "\"Item\", \"Unit\"], \"capex\": [\"Location\", \"ProductionSite\", \"Product\", \"Process\", \"Capacity\", \"Item\", \"Unit\",", "PipelineType.PRICE, \"columns\": [\"Type\", \"Product\", \"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON,", "SAP = 2 PAP = 3 GRANULATION = 4 LOGISTICS", "\"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"Process\",", "UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA = { PipelineLayer.COMMON: { \"type\": PipelineType.COMMON,", "GRANULATION = 4 LOGISTICS = 5 RAW_MATERIALS = 8 COMMON", "{ \"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\", \"sap.product\", \"sap.capex\", \"sap.capacity[kt]\"], \"options\":", "= \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP = False MODE_DEBUG =", "DB DB_NAME = None DB_HOST = \"172.29.161.208\" DB_PORT = 5006", "\"mine.quality\", \"mine.capex\"], \"options\": \"mining_options\", \"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\",", "PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Capacity\",", "\"opex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Upstream\",", "# Monitoring MONITORING_APP_NAME = \"mine2farm_monitor\" MONITORING_SERVER = \"172.29.161.208\" MONITORING_PORT =", "\"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.RAW_MATERIALS: { \"type\":", "Unit\", \"Uniform Unit\", \"Conversion Rate\"] }, } class ShuffleLevel(IntEnum): UNDEFINED", "os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER + \"app/log/\" LOG_FILE = \"%(asctime)_\"", "Results DB_RESULT_NAME = \"%s_results\" % DB_NAME if DB_NAME is not", "MONITORING_COLLECTION_HISTORY_BEST_NAME = \"best_scenarios_history\" MONITORING_STEP = 1 MONITORING_NB_PAGE = 10 #", "= None DB_HOST = \"172.29.161.208\" DB_PORT = 5006 DATA_SERVICE_ADD =", "\"mine2port\" DEPARTURE_ARRIVAL = {SUPPLY_CHAIN: (PipelineLayer.MINE), \"sap2pap\": (PipelineLayer.SAP, PipelineLayer.PAP)} COMBO_NODES =", "= 3 PRICE = 4 SALES = 5 @unique class", "[\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\", \"production\": None, \"opex\": \"logistics_opex\",", "+ \".log\" OUTPUT_FOLDER = \"%s%s\" % (APP_FOLDER, \"outputs/\") CANVAS_URL =", "\"granulation_production\", \"opex\": \"granulation_opex\", \"capex\": \"granulation_capex\" }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT,", "12 PIPELINE_SCHEMA = { PipelineLayer.COMMON: { \"type\": PipelineType.COMMON, \"dico\": [\"location\",", "PipelineType.PRODUCER, \"production\": [\"Name\", \"Extraction\", \"Quality\", \"Unit\"], \"opex\": [\"Name\", \"Extraction\", \"Capacity\",", "PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION: ShuffleLevel.UNDEFINED, PipelineLayer.LOGISTICS: ShuffleLevel.UNDEFINED,", "\"type\": PipelineType.SALES, \"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"data\":", "RABBITMQ_GLOBAL_RESULT_QUEUE_NAME = \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ", "= 20 RANDOMIZE_RESULTS = False # RabbitMQ RABBITMQ_SERVER = \"localhost\"", "[\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\", \"production\": \"granulation_production\", \"opex\":", "class PipelineLayer(IntEnum): UNDEFINED = -1 MINE = 0 BENEFICIATION =", "} COMBO_NODES_SEPARATION = \"--\" class FunctionType(Enum): COST_PV = 0 CASH_COST", "\"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\",", "= -1 MINE = 0 BENEFICIATION = 1 SAP =", "\"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"ProductionSite\", \"Process\", \"Capacity\",", "\"production\": \"mining_specific_production\", \"opex\": \"mining_opex___specific_consumptions\", \"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION:", "= \"SAVE_GLOBAL\" RABBITMQ_MAX_WORKER = RABBITMQ_CYCLE RABBITMQ_PATH = \"C:\\\\Program Files\\\\RabbitMQ Server\\\\rabbitmq_server-3.8.1\\\\sbin\"", "None DB_HOST = \"172.29.161.208\" DB_PORT = 5006 DATA_SERVICE_ADD = \"172.29.161.208\"", "\"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\", \"production\": None, \"opex\": \"logistics_opex\", \"capex\":", "PipelineType.COMMON, \"columns\": [\"Initial Unit\", \"Uniform Unit\", \"Conversion Rate\"] }, }", "% (APP_FOLDER, \"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME =", "\"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\" }, PipelineLayer.PAP: {", "\"opex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Extraction\", \"Capacity\",", "2 SCENARIO_GEN_TYPE = ScenarioGeneratorType.FROM_OPTIONS PIPELINE_METADATA = { PipelineLayer.MINE: { \"type\":", "\"mine2farm\" NETWORK_NAME = \"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE = \"INFO\"", "\"CAPEX\"] }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\",", "2020 TMAX = 2031 class PriceParams(Enum): WACC = 0 TENOR", "\"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE = 25", "\"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.PAP:", "for BI\\\\2.13\\\\bin\" # Mongodb MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params", "= 1 SAP = 2 PAP = 3 GRANULATION =", "ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.GRANULATION: ShuffleLevel.UNDEFINED, PipelineLayer.LOGISTICS:", "DATA_SERVICE_PORT = 5001 # Results DB_RESULT_NAME = \"%s_results\" % DB_NAME", "= False # RabbitMQ RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\"", "}, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.SALES, \"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: {", "\"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"], \"options\": \"logistics_options\", \"production\":", "\"Product\", \"Unit\"], \"opex\": [\"Location\", \"ProductionSite\", \"Process\", \"Capacity\", \"Product\", \"Item\", \"Unit\"],", "\"unit\", \"currency\", \"output\", \"names\", \"products\"] }, PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER,", "}, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\", \"Product\", \"Unit\"],", "\"sap.product\" }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\", \"pap.product\",", "PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN: { \"type\": PipelineType.PRICE, \"columns\":", "# RabbitMQ RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE =", "\"Process\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"]", "[\"Initial Unit\", \"Uniform Unit\", \"Conversion Rate\"] }, } class ShuffleLevel(IntEnum):", "} class ShuffleLevel(IntEnum): UNDEFINED = 0 SHUFFLE_WITHOUT_PERM = 1 SHUFFLE_WITH_PERMUTATIONS", "\"options\": \"sap___power_plant_options\", \"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\"", "\"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE = \"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\",", "= { PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION: ShuffleLevel.UNDEFINED, PipelineLayer.SAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED, PipelineLayer.PAP: ShuffleLevel.SHUFFLE_WITH_UNNAMED,", "\"capex\": \"mining_capex\", \"priority_mines\": \"prioritymines\" }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"dico\":", "\"production\": [\"Location\", \"Process\", \"Product\", \"Unit\"], \"opex\": [\"Location\", \"Process\", \"Item\", \"Unit\"],", "Mongodb MONGO_SERVER_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP = False", "TMAX = 2031 class PriceParams(Enum): WACC = 0 TENOR =", "8 COMMON = 9 SALES_PLAN = 10 MINE_BENEFICIATION = 11", "2 PAP = 3 GRANULATION = 4 LOGISTICS = 5", "1 FULL_COST = 2 class ScenarioGeneratorType(IntEnum): FROM_PATHS = 0 FROM_OPTIONS", "\"Downstream\", \"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Upstream\", \"Downstream\", \"Method\",", "DB_PORT = 5006 DATA_SERVICE_ADD = \"172.29.161.208\" DATA_SERVICE_PORT = 5001 #", "1 MONITORING_NB_PAGE = 10 # Mongodb-bi MONGODB_BI_PATH = \"C:\\\\Program Files\\\\MongoDB\\\\Connector", "not None else None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\"", "PriceParams(Enum): WACC = 0 TENOR = 1 VOLUME = 2", "\"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION = \"--\"", "\"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\",", "Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\" # params LOGISTICS_LP = False MODE_DEBUG = False GRANUL_RELAX", "\"products\"] }, PipelineLayer.MINE: { \"type\": PipelineType.PRODUCER, \"dico\": [\"mine.name\", \"mine.extraction\", \"mine.quality\",", "\"product_type\": \"sap.product\" }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"pap.name\", \"pap.process\",", "\"production\": \"sap___power_plant_production\", \"opex\": \"sap___power_plant_opex___specific_consumptions\", \"capex\": \"sap___power_plant_capex\", \"product_type\": \"sap.product\" }, PipelineLayer.PAP:", "\"opex\": [\"Location\", \"Process\", \"Item\", \"Unit\"], \"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\",", "= 2 BALANCE = 3 PRICE = 4 SALES =", "= 11 UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA = { PipelineLayer.COMMON: {", "{ \"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION", "= \"CenterAxis\" LOG_LEVEL_CONSOLE = \"WARNING\" LOG_LEVEL_FILE = \"INFO\" APP_FOLDER =", "}, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"data\": \"conv_matrix\" }, } SUPPLY_CHAIN", "0 PRODUCER = 1 TRANSPORT = 2 BALANCE = 3", "= 5 RAW_MATERIALS = 8 COMMON = 9 SALES_PLAN =", "ScenarioGeneratorType(IntEnum): FROM_PATHS = 0 FROM_OPTIONS = 1 SPECIFIC_SCENARIOS = 2", "LOG_FOLDER = APP_FOLDER + \"app/log/\" LOG_FILE = \"%(asctime)_\" + APP_NAME", "PipelineLayer.MINE_BENEFICIATION: { \"url\": \"mining_wp_connections\", \"upstream_layer\": PipelineLayer.MINE, \"downstream_layer\": PipelineLayer.BENEFICIATION } }", "\"pap.size[kt]\", \"pap.input\"], \"options\": \"pap_options\", \"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\",", "coding: utf-8 -*- from enum import Enum, IntEnum, unique import", "T0 = 2020 TMAX = 2031 class PriceParams(Enum): WACC =", "\"Unit\"], \"opex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Name\", \"Extraction\",", "\"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"data\": \"conv_matrix\" },", "# Memcached MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT = 11211 # Dashboard", "3 GRANULATION = 4 LOGISTICS = 5 RAW_MATERIALS = 8", "= \"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME = None DB_HOST = \"172.29.161.208\"", "\"capex\": [\"Location\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.PAP: {", "\"Extraction\", \"Quality\", \"Unit\"], \"opex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\"], \"capex\":", "\"capex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION: {", "LOG_FILE = \"%(asctime)_\" + APP_NAME + \".log\" OUTPUT_FOLDER = \"%s%s\"", "= -1 OK = 0 # Model MONIKER_SEPARATOR = \"/\"", "\"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME = \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\"", "LOGISTICS = 5 RAW_MATERIALS = 8 COMMON = 9 SALES_PLAN", "CASH_COST = 1 FULL_COST = 2 class ScenarioGeneratorType(IntEnum): FROM_PATHS =", "{ \"type\": PipelineType.SALES, \"data\": \"sales_plan\" }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON,", "\"production\": None, \"opex\": \"logistics_opex\", \"capex\": \"logistics_capex\" }, PipelineLayer.RAW_MATERIALS: { \"type\":", "= 9 SALES_PLAN = 10 MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX =", "= 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS =", "\".log\" OUTPUT_FOLDER = \"%s%s\" % (APP_FOLDER, \"outputs/\") CANVAS_URL = \"http://127.0.0.1/canvas.xlsm\"", "= APP_FOLDER + \"app/log/\" LOG_FILE = \"%(asctime)_\" + APP_NAME +", "PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"dico\": [\"granulation.name\", \"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"],", "None else None DB_DETAILED_RESULT_COLLECTION_NAME = \"detailed\" DB_GLOBAL_RESULT_COLLECTION_NAME = \"global\" DB_GLOBAL_BEST_RESULT_COLLECTION_NAME", "\"pap.input\"], \"options\": \"pap_options\", \"production\": \"pap_production\", \"opex\": \"pap_opex___specific_consumptions\", \"capex\": \"pap_capex\", \"product_type\":", "\"OutputQuality\", \"Humidity\", \"Unit\"], \"opex\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Item\", \"Unit\"], \"capex\":", "\"beneficiation_options\", \"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP: {", "= False MODE_DEBUG = False GRANUL_RELAX = False class HTML_STATUS(IntEnum):", "1 SAP = 2 PAP = 3 GRANULATION = 4", "-1 MINE = 0 BENEFICIATION = 1 SAP = 2", "RABBITMQ_SERVER = \"localhost\" RABBITMQ_SIMULATOR_QUEUE_NAME = \"SIMULATE\" RABBITMQ_CYCLE = 3 RABBITMQ_DETAILED_RESULT_QUEUE_NAME", "-*- coding: utf-8 -*- from enum import Enum, IntEnum, unique", "\"Unit\", \"CAPEX\"] }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"Input\",", "APP_NAME + \".log\" OUTPUT_FOLDER = \"%s%s\" % (APP_FOLDER, \"outputs/\") CANVAS_URL", "3 SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS = { PipelineLayer.MINE: ShuffleLevel.UNDEFINED, PipelineLayer.BENEFICIATION:", "\"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER, \"dico\": [\"sap.name\", \"sap.process\",", "SALES_PLAN = 10 MINE_BENEFICIATION = 11 UNIT_CONVERSION_MATRIX = 12 PIPELINE_SCHEMA", "\"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"production\":", "\"http://127.0.0.1/canvas.xlsm\" # DB DB_NAME = None DB_HOST = \"172.29.161.208\" DB_PORT", "\"Item\", \"Unit\"], \"capex\": [\"Name\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] },", "\"production\": \"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP: { \"type\":", "\"Unit\"] }, PipelineLayer.UNIT_CONVERSION_MATRIX: { \"type\": PipelineType.COMMON, \"columns\": [\"Initial Unit\", \"Uniform", "False class HTML_STATUS(IntEnum): ERROR = -1 OK = 0 #", "\"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT,", "= 8 COMMON = 9 SALES_PLAN = 10 MINE_BENEFICIATION =", "[\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION: { \"type\":", "}, PipelineLayer.RAW_MATERIALS: { \"type\": PipelineType.PRICE, \"columns\": [\"Item\", \"Unit\"] }, PipelineLayer.SALES_PLAN:", "= 0.1 T0 = 2020 TMAX = 2031 class PriceParams(Enum):", "+ APP_NAME + \".log\" OUTPUT_FOLDER = \"%s%s\" % (APP_FOLDER, \"outputs/\")", "}, PipelineLayer.LOGISTICS: { \"type\": PipelineType.TRANSPORT, \"dico\": [\"logistics.name\", \"logistics.process\", \"logistics.product\", \"logistics.capex\"],", "-*- from enum import Enum, IntEnum, unique import os APP_NAME", "\"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.GRANULATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\",", "\"granulation.process\", \"granulation.product\", \"granulation.capex\", \"granulation.input\"], \"options\": \"granulation_options\", \"production\": \"granulation_production\", \"opex\": \"granulation_opex\",", "\"Method\", \"Product\", \"Capacity\", \"Item\", \"Unit\"], \"capex\": [\"Upstream\", \"Downstream\", \"Method\", \"Product\",", "= \"INFO\" APP_FOLDER = os.getenv(\"JESA_MINE2FARM_HOME\", \"C:/GitRepos/mine2farm/\") LOG_FOLDER = APP_FOLDER +", "\"Unit\"], \"capex\": [\"Name\", \"Extraction\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.BENEFICIATION:", "class PipelineType(Enum): COMMON = 0 PRODUCER = 1 TRANSPORT =", "= \"global_best\" DB_DETAILED_BEST_RESULT_COLLECTION_NAME = \"detailed_best\" DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE =", "DB_SENSITIVITY_COLLECTION_NAME = \"sensitivity\" RESULT_BATCHES_SIZE = 25 HEAD_DATA_BITS = 17 DB_NAME_BITS", "SHUFFLE_WITH_PERMUTATIONS = 2 SHUFFLE_WITH_PERMUTATIONS_WITH_FILTERS = 3 SHUFFLE_WITH_UNNAMED = 4 SHUFFLE_LEVELS", "\"capex\": [\"Name\", \"Process\", \"Capacity\", \"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.SAP: {", "\"172.29.161.208\" DATA_SERVICE_PORT = 5001 # Results DB_RESULT_NAME = \"%s_results\" %", "\"Item\", \"Unit\", \"CAPEX\"] }, PipelineLayer.PAP: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\",", "\"beneficiation_production\", \"opex\": \"beneficiation_opex___specific_consumptions\", \"capex\": \"beneficiation_capex\" }, PipelineLayer.SAP: { \"type\": PipelineType.PRODUCER,", "= 1 TRANSPORT = 2 BALANCE = 3 PRICE =", "\"downstream_layer\": PipelineLayer.BENEFICIATION } } COMBO_NODES_SEPARATION = \"--\" class FunctionType(Enum): COST_PV", "PipelineLayer.BENEFICIATION: { \"type\": PipelineType.PRODUCER, \"production\": [\"Process\", \"InputQuality\", \"OutputQuality\", \"Humidity\", \"Unit\"],", "Memcached MEMCACHED_SERVER = 'localhost' MEMCACHED_PORT = 11211 # Dashboard DB_LOAD_FROM_SERVICE" ]
[ ": id : int img : str date : int", "Create your models here. class Destination(models.Model) : name = models.CharField(max_length", "here. class Destination(models.Model) : name = models.CharField(max_length = 100) img", "date : int month : str headline : str category", "= False) class News() : id : int img :", "models here. class Destination(models.Model) : name = models.CharField(max_length = 100)", "= models.IntegerField() offer = models.BooleanField(default = False) class News() :", "models.TextField() price = models.IntegerField() offer = models.BooleanField(default = False) class", ": int img : str date : int month :", "class News() : id : int img : str date", "# Create your models here. class Destination(models.Model) : name =", "Destination(models.Model) : name = models.CharField(max_length = 100) img = models.ImageField(upload_to", "= 100) img = models.ImageField(upload_to = 'pics') desc = models.TextField()", "models.ImageField(upload_to = 'pics') desc = models.TextField() price = models.IntegerField() offer", "img = models.ImageField(upload_to = 'pics') desc = models.TextField() price =", "str date : int month : str headline : str", ": name = models.CharField(max_length = 100) img = models.ImageField(upload_to =", "price = models.IntegerField() offer = models.BooleanField(default = False) class News()", "str headline : str category : str desc : str", "desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default =", "models # Create your models here. class Destination(models.Model) : name", "= models.ImageField(upload_to = 'pics') desc = models.TextField() price = models.IntegerField()", "offer = models.BooleanField(default = False) class News() : id :", "'pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default", "import models # Create your models here. class Destination(models.Model) :", "News() : id : int img : str date :", ": str headline : str category : str desc :", "your models here. class Destination(models.Model) : name = models.CharField(max_length =", "100) img = models.ImageField(upload_to = 'pics') desc = models.TextField() price", "= 'pics') desc = models.TextField() price = models.IntegerField() offer =", "id : int img : str date : int month", "img : str date : int month : str headline", "models.IntegerField() offer = models.BooleanField(default = False) class News() : id", "models.BooleanField(default = False) class News() : id : int img", "class Destination(models.Model) : name = models.CharField(max_length = 100) img =", "month : str headline : str category : str desc", "= models.CharField(max_length = 100) img = models.ImageField(upload_to = 'pics') desc", ": int month : str headline : str category :", ": str date : int month : str headline :", "django.db import models # Create your models here. class Destination(models.Model)", "name = models.CharField(max_length = 100) img = models.ImageField(upload_to = 'pics')", "False) class News() : id : int img : str", "int month : str headline : str category : str", "int img : str date : int month : str", "= models.BooleanField(default = False) class News() : id : int", "= models.TextField() price = models.IntegerField() offer = models.BooleanField(default = False)", "models.CharField(max_length = 100) img = models.ImageField(upload_to = 'pics') desc =", "from django.db import models # Create your models here. class" ]
[ "style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw", "y2) image = np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic", "Load DNN model classifier = tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model, image_box=None):", "des fichiers ppm) # fichier base 64 --> image PIL", "but de réaliser des modèles capables de classer des panneaux", "params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL'] # Load DNN", "dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"), html.P( [ 'Cette application à", "# Load DNN model classifier = tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model,", "= yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL =", "html.Div('Uniquement des images svp : {}'.format(content_type)), html.Hr(), html.Div('Raw Content'), html.Pre(contents,", "style=pre_style) ]) # Manage interactions with callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'),", "model: tf/keras classifier Returns ------- class id returned by model", "capables de classer des panneaux de signalisation allemand à partir", "html.Hr(), #html.Div('Raw Content'), #html.Pre(contents, style=pre_style) ]) else: try: # Décodage", "format='PNG') # buffer mémoire --> image base 64 buffer.seek(0) img_bytes", "brand_href=\"#\", color= \"#d90054\", dark=True ) cards = html.Div( [ dbc.Card(", "html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')]) def update_output(contents): if contents", "html.H3('Valeur saisie ici \"{}\"'.format(input_value)) # Start the application if __name__", "model classifier \"\"\" images_list = [] image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT),", "'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center',", ") app.layout = html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer", "manière suivante : vous déposer une image à l\\'emplacement indiqué", "haut à droite vous pouvez sélectionner le modèle que vous", "PIL import Image from constants import CLASSES import yaml with", "import yaml with open('app.yaml') as yaml_data : params = yaml.safe_load(yaml_data)", "content_string = contents.split(',') if 'image' in content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string)))", "import Input, Output import numpy as np import tensorflow as", "open('app.yaml') as yaml_data : params = yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH']", "= [] image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) # box argument", "des images svp : {}'.format(content_type)), html.Hr(), html.Div('Raw Content'), html.Pre(contents, style=pre_style)", "du modèle de classification predicted_class = classify_image(image, classifier)[0] # Affichage", "base 64 --> image PIL image = Image.open(io.BytesIO(base64.b64decode(content_string))) # image", "yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL']", "suivante : vous déposer une image à l\\'emplacement indiqué et", "sélectionner le modèle que vous voulez tester.', ], className='card-text', ),", "model classifier = tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model, image_box=None): \"\"\"Classify image", "io.BytesIO() image.save(buffer, format='PNG') # buffer mémoire --> image base 64", "np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP])", "prédiction du modèle apparait immédiatement en dessous. En haut à", "modèle que vous voulez tester.', ], className='card-text', ), ] ),", "réaliser des modèles capables de classer des panneaux de signalisation", "64 buffer.seek(0) img_bytes = buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii') # Appel", "images_list.append(image) return model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style", "= dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = { 'whiteSpace': 'pre-wrap',", "application layout navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de", ": vous déposer une image à l\\'emplacement indiqué et la", "], className='card-text', ), ] ), className='w-75 mb-3', color='#f1cbd1', outline='Black', style={", "else: try: # Décodage de l'image transmise en base 64", ") cards = html.Div( [ dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"),", "la manière suivante : vous déposer une image à l\\'emplacement", "model Parameters ---------- content: image content model: tf/keras classifier Returns", "image à l\\'emplacement indiqué et la prédiction du modèle apparait", "html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output", "'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace': 'normal' } # Define application", "[] image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) # box argument clips", "tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model, image_box=None): \"\"\"Classify image by model Parameters", "Parameters ---------- content: image content model: tf/keras classifier Returns -------", "de l'image transmise en base 64 (cas des fichiers ppm)", "id returned by model classifier \"\"\" images_list = [] image", "children=html.Div([ 'Cliquer-déposer ou ', html.A('sélectionner une image') ]), style={ 'width':", "color= \"#d90054\", dark=True ) cards = html.Div( [ dbc.Card( dbc.CardBody(", "voulez tester.', ], className='card-text', ), ] ), className='w-75 mb-3', color='#f1cbd1',", "import CLASSES import yaml with open('app.yaml') as yaml_data : params", "base 64 (cas des fichiers ppm) # fichier base 64", "except: return html.Div([ html.Hr(), html.Div('Uniquement des images svp : {}'.format(content_type)),", "Image from constants import CLASSES import yaml with open('app.yaml') as", "immédiatement en dessous. En haut à droite vous pouvez sélectionner", "des panneaux de signalisation allemand à partir d\\'une image. L\\'application", "def update_output(contents): if contents is not None: content_type, content_string =", "'75px'}), html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}),", "'margin-left': '185px'}, ), ] ) app.layout = html.Div([ html.Div([navbar]), html.Div(cards),", "Content'), #html.Pre(contents, style=pre_style) ]) else: try: # Décodage de l'image", "# Décodage de l'image transmise en base 64 (cas des", "ppm) # fichier base 64 --> image PIL image =", "Manage interactions with callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] )", "image') ]), style={ 'width': '50%', 'height': '60px', 'lineHeight': '60px', 'borderWidth':", "content_type, content_string = contents.split(',') if 'image' in content_type: image =", "buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii') # Appel du modèle de classification", "= contents.split(',') if 'image' in content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class", "image base 64 buffer.seek(0) img_bytes = buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii')", "et la prédiction du modèle apparait immédiatement en dessous. En", "import dash_bootstrap_components as dbc from dash.dependencies import Input, Output import", "), ] ), className='w-75 mb-3', color='#f1cbd1', outline='Black', style={ 'margin-top': '75px',", "que vous voulez tester.', ], className='card-text', ), ] ), className='w-75", "base64 import io import dash import dash_core_components as dcc import", "params['PATH_MODEL'] # Load DNN model classifier = tf.keras.models.load_model(PATH_MODEL) def classify_image(image,", "[Input('bouton-chargement', 'contents')]) def update_output(contents): if contents is not None: content_type,", "'wordBreak': 'break-all', 'whiteSpace': 'normal' } # Define application layout navbar", "\"{}\"'.format(input_value)) # Start the application if __name__ == '__main__': app.run_server(debug=True)", "in content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image, classifier)[0] return", "style={'textAlign': 'center'}), html.Hr(), ]) except: return html.Div([ html.Hr(), html.Div('Uniquement des", "modèle apparait immédiatement en dessous. En haut à droite vous", "classer des panneaux de signalisation allemand à partir d\\'une image.", "href=\"#\"), ], nav=True, in_navbar=True, label='Modèle', ), ], brand=\"Menu\", brand_href=\"#\", color=", "html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou ', html.A('sélectionner une image')", "content_string, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(),", "Define application layout navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau", "Returns ------- class id returned by model classifier \"\"\" images_list", "def classify_image(image, model, image_box=None): \"\"\"Classify image by model Parameters ----------", "#html.Div('Raw Content'), #html.Pre(contents, style=pre_style) ]) else: try: # Décodage de", "image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image, classifier)[0] return html.Div([ html.Hr(style={'margin-top':", "ou ', html.A('sélectionner une image') ]), style={ 'width': '50%', 'height':", "IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL'] # Load DNN model", "html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' + content_string, style={'margin-left': '750px'}), html.H4('Classe prédite :", "content: image content model: tf/keras classifier Returns ------- class id", "mémoire buffer = io.BytesIO() image.save(buffer, format='PNG') # buffer mémoire -->", "classifier)[0] # Affichage de l'image return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,'", "classify_image(image, classifier)[0] return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe", "component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] ) def update_output_div(input_value): return html.H3('Valeur saisie ici", "fichier base 64 --> image PIL image = Image.open(io.BytesIO(base64.b64decode(content_string))) #", "de signalisation allemand à partir d\\'une image. L\\'application fonctionne de", "Content'), html.Pre(contents, style=pre_style) ]) # Manage interactions with callbacks @app.callback(", "# image PIL --> conversion PNG --> buffer mémoire buffer", "image PIL --> conversion PNG --> buffer mémoire buffer =", "label='Modèle', ), ], brand=\"Menu\", brand_href=\"#\", color= \"#d90054\", dark=True ) cards", "classifier)[0] return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe prédite", "'normal' } # Define application layout navbar = dbc.NavbarSimple( children=[", "'break-all', 'whiteSpace': 'normal' } # Define application layout navbar =", "'center'}), html.Hr(), ]) except: return html.Div([ html.Hr(), html.Div('Uniquement des images", "= np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic Signs Recognition',", "ici \"{}\"'.format(input_value)) # Start the application if __name__ == '__main__':", "dash_bootstrap_components as dbc from dash.dependencies import Input, Output import numpy", "]) else: try: # Décodage de l'image transmise en base", "return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' + content_string, style={'margin-left': '750px'}), html.H4('Classe", "vous pouvez sélectionner le modèle que vous voulez tester.', ],", "import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies", "le modèle que vous voulez tester.', ], className='card-text', ), ]", "as dbc from dash.dependencies import Input, Output import numpy as", "{ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace': 'normal' } # Define", "]) # Manage interactions with callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte',", "style={ 'margin-top': '75px', 'margin-left': '185px'}, ), ] ) app.layout =", "IMAGE_HEIGHT), box=image_box) # box argument clips image to (x1, y1,", "PIL image = Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL --> conversion PNG", "mémoire --> image base 64 buffer.seek(0) img_bytes = buffer.read() content_string", "dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True, in_navbar=True, label='Modèle', ), ], brand=\"Menu\", brand_href=\"#\",", "'50%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius':", "= classify_image(image, classifier)[0] # Affichage de l'image return html.Div([ html.Hr(style={'margin-top':", "by model Parameters ---------- content: image content model: tf/keras classifier", "= Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image, classifier)[0] return html.Div([ html.Hr(style={'margin-top': '75px'}),", "Output import numpy as np import tensorflow as tf from", "tf/keras classifier Returns ------- class id returned by model classifier", "dash.dependencies import Input, Output import numpy as np import tensorflow", "'1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin-top': '75px', 'margin-left':", "html.Hr(), html.Div('Raw Content'), html.Pre(contents, style=pre_style) ]) # Manage interactions with", "return html.Div([ html.Hr(), html.Div('Uniquement des images svp : {}'.format(content_type)), html.Hr(),", "yaml with open('app.yaml') as yaml_data : params = yaml.safe_load(yaml_data) IMAGE_WIDTH", "] ) app.layout = html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([", "children=[ dbc.DropdownMenuItem('Réseau de Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True, in_navbar=True,", "= html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou ',", "), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')]) def update_output(contents):", "def update_output_div(input_value): return html.H3('Valeur saisie ici \"{}\"'.format(input_value)) # Start the", "interactions with callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] ) def", "mb-3', color='#f1cbd1', outline='Black', style={ 'margin-top': '75px', 'margin-left': '185px'}, ), ]", "y1, x2, y2) image = np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list)) app", "image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) # box argument clips image", "'60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin-top':", "= io.BytesIO() image.save(buffer, format='PNG') # buffer mémoire --> image base", "+ content_string, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}),", "update_output_div(input_value): return html.H3('Valeur saisie ici \"{}\"'.format(input_value)) # Start the application", "'image' in content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image, classifier)[0]", "model, image_box=None): \"\"\"Classify image by model Parameters ---------- content: image", "html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]),", "apparait immédiatement en dessous. En haut à droite vous pouvez", "'Cliquer-déposer ou ', html.A('sélectionner une image') ]), style={ 'width': '50%',", "en base 64 (cas des fichiers ppm) # fichier base", "Input, Output import numpy as np import tensorflow as tf", "import dash import dash_core_components as dcc import dash_html_components as html", "= params['PATH_MODEL'] # Load DNN model classifier = tf.keras.models.load_model(PATH_MODEL) def", "'margin-top': '75px', 'margin-left': '370px', } ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image',", "en dessous. En haut à droite vous pouvez sélectionner le", "as dcc import dash_html_components as html import dash_bootstrap_components as dbc", "\"#d90054\", dark=True ) cards = html.Div( [ dbc.Card( dbc.CardBody( [", "navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de Neurones', header=True),", "by model classifier \"\"\" images_list = [] image = image.resize((IMAGE_WIDTH,", "is not None: content_type, content_string = contents.split(',') if 'image' in", "PNG --> buffer mémoire buffer = io.BytesIO() image.save(buffer, format='PNG') #", "images_list = [] image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) # box", "Affichage de l'image return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' + content_string,", "de classer des panneaux de signalisation allemand à partir d\\'une", "'margin-top': '75px', 'margin-left': '185px'}, ), ] ) app.layout = html.Div([", "return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe prédite :", ": {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), ]) except: return html.Div([ html.Hr(),", "html.H5(\"Présentation\", className=\"card-title\"), html.P( [ 'Cette application à pour but de", "html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), ]) except: return", "image.save(buffer, format='PNG') # buffer mémoire --> image base 64 buffer.seek(0)", "image to (x1, y1, x2, y2) image = np.array(image) images_list.append(image)", "), ] ) app.layout = html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement',", "CLASSES import yaml with open('app.yaml') as yaml_data : params =", "header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True, in_navbar=True, label='Modèle', ), ], brand=\"Menu\",", "l'image transmise en base 64 (cas des fichiers ppm) #", "signalisation allemand à partir d\\'une image. L\\'application fonctionne de la", "'75px', 'margin-left': '185px'}, ), ] ) app.layout = html.Div([ html.Div([navbar]),", "images svp : {}'.format(content_type)), html.Hr(), html.Div('Raw Content'), html.Pre(contents, style=pre_style) ])", "'5px', 'textAlign': 'center', 'margin-top': '75px', 'margin-left': '370px', } ), html.Div(id='mon-image'),", "\"\"\" images_list = [] image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) #", "as np import tensorflow as tf from PIL import Image", "classifier \"\"\" images_list = [] image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box)", "des modèles capables de classer des panneaux de signalisation allemand", "= base64.b64encode(img_bytes).decode('ascii') # Appel du modèle de classification predicted_class =", "nav=True, in_navbar=True, label='Modèle', ), ], brand=\"Menu\", brand_href=\"#\", color= \"#d90054\", dark=True", "html.Pre(contents, style=pre_style) ]) # Manage interactions with callbacks @app.callback( Output(component_id='ma-zone-resultat',", "dcc import dash_html_components as html import dash_bootstrap_components as dbc from", "à partir d\\'une image. L\\'application fonctionne de la manière suivante", "= tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model, image_box=None): \"\"\"Classify image by model", "---------- content: image content model: tf/keras classifier Returns ------- class", "\"\"\"Classify image by model Parameters ---------- content: image content model:", "PATH_MODEL = params['PATH_MODEL'] # Load DNN model classifier = tf.keras.models.load_model(PATH_MODEL)", "buffer.seek(0) img_bytes = buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii') # Appel du", "[ dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"), html.P( [ 'Cette application", "buffer = io.BytesIO() image.save(buffer, format='PNG') # buffer mémoire --> image", "de la manière suivante : vous déposer une image à", "if 'image' in content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image,", "from constants import CLASSES import yaml with open('app.yaml') as yaml_data", "html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(),", "html.Hr(), html.Div('Uniquement des images svp : {}'.format(content_type)), html.Hr(), html.Div('Raw Content'),", "(cas des fichiers ppm) # fichier base 64 --> image", "dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as", "image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) # box argument clips image to (x1,", "outline='Black', style={ 'margin-top': '75px', 'margin-left': '185px'}, ), ] ) app.layout", "'750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), ]) except:", "from PIL import Image from constants import CLASSES import yaml", "vous voulez tester.', ], className='card-text', ), ] ), className='w-75 mb-3',", "'center'}), html.Hr(), #html.Div('Raw Content'), #html.Pre(contents, style=pre_style) ]) else: try: #", "returned by model classifier \"\"\" images_list = [] image =", "tf from PIL import Image from constants import CLASSES import", "'contents')]) def update_output(contents): if contents is not None: content_type, content_string", "à l\\'emplacement indiqué et la prédiction du modèle apparait immédiatement", "'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin-top': '75px', 'margin-left': '370px', }", "'185px'}, ), ] ) app.layout = html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload(", "[Input(component_id='mon-champ-texte', component_property='value')] ) def update_output_div(input_value): return html.H3('Valeur saisie ici \"{}\"'.format(input_value))", "tensorflow as tf from PIL import Image from constants import", "dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou ', html.A('sélectionner une image') ]),", "html.Div('Raw Content'), html.Pre(contents, style=pre_style) ]) # Manage interactions with callbacks", "En haut à droite vous pouvez sélectionner le modèle que", "dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True,", "update_output(contents): if contents is not None: content_type, content_string = contents.split(',')", "html.Hr(), ]) except: return html.Div([ html.Hr(), html.Div('Uniquement des images svp", "pre_style = { 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace': 'normal' }", "None: content_type, content_string = contents.split(',') if 'image' in content_type: image", "image PIL image = Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL --> conversion", "'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin-top': '75px', 'margin-left': '370px',", "Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = { 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace':", "@app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')]) def update_output(contents): if contents is not", "# buffer mémoire --> image base 64 buffer.seek(0) img_bytes =", "} # Define application layout navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu(", "base 64 buffer.seek(0) img_bytes = buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii') #", "as tf from PIL import Image from constants import CLASSES", "panneaux de signalisation allemand à partir d\\'une image. L\\'application fonctionne", "= classify_image(image, classifier)[0] return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left': '750px'}),", "fichiers ppm) # fichier base 64 --> image PIL image", "cards = html.Div( [ dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"), html.P(", "), ], brand=\"Menu\", brand_href=\"#\", color= \"#d90054\", dark=True ) cards =", "Appel du modèle de classification predicted_class = classify_image(image, classifier)[0] #", "dark=True ) cards = html.Div( [ dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\",", "--> buffer mémoire buffer = io.BytesIO() image.save(buffer, format='PNG') # buffer", "'60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign':", ": {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw Content'), #html.Pre(contents, style=pre_style) ])", "np import tensorflow as tf from PIL import Image from", "# Affichage de l'image return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' +", "x2, y2) image = np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list)) app =", "io import dash import dash_core_components as dcc import dash_html_components as", "du modèle apparait immédiatement en dessous. En haut à droite", "to (x1, y1, x2, y2) image = np.array(image) images_list.append(image) return", "model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = {", "de classification predicted_class = classify_image(image, classifier)[0] # Affichage de l'image", "# Appel du modèle de classification predicted_class = classify_image(image, classifier)[0]", "as yaml_data : params = yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT", "la prédiction du modèle apparait immédiatement en dessous. En haut", "------- class id returned by model classifier \"\"\" images_list =", "conversion PNG --> buffer mémoire buffer = io.BytesIO() image.save(buffer, format='PNG')", "params = yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL", "[ 'Cette application à pour but de réaliser des modèles", "[ html.H5(\"Présentation\", className=\"card-title\"), html.P( [ 'Cette application à pour but", "color='#f1cbd1', outline='Black', style={ 'margin-top': '75px', 'margin-left': '185px'}, ), ] )", "import tensorflow as tf from PIL import Image from constants", "contents.split(',') if 'image' in content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class =", "content model: tf/keras classifier Returns ------- class id returned by", "dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"),", "transmise en base 64 (cas des fichiers ppm) # fichier", "dessous. En haut à droite vous pouvez sélectionner le modèle", "déposer une image à l\\'emplacement indiqué et la prédiction du", "clips image to (x1, y1, x2, y2) image = np.array(image)", "'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin-top': '75px',", "as html import dash_bootstrap_components as dbc from dash.dependencies import Input,", "image = np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic Signs", "predicted_class = classify_image(image, classifier)[0] # Affichage de l'image return html.Div([", "box=image_box) # box argument clips image to (x1, y1, x2,", "html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou ', html.A('sélectionner", "style={ 'width': '50%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle':", "classification predicted_class = classify_image(image, classifier)[0] # Affichage de l'image return", "'center', 'margin-top': '75px', 'margin-left': '370px', } ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ])", "# Manage interactions with callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')]", "predicted_class = classify_image(image, classifier)[0] return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left':", "import base64 import io import dash import dash_core_components as dcc", "component_property='value')] ) def update_output_div(input_value): return html.H3('Valeur saisie ici \"{}\"'.format(input_value)) #", "'75px'}), html.Img(src='data:image/png;base64,' + content_string, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]),", "html.A('sélectionner une image') ]), style={ 'width': '50%', 'height': '60px', 'lineHeight':", "de réaliser des modèles capables de classer des panneaux de", "une image') ]), style={ 'width': '50%', 'height': '60px', 'lineHeight': '60px',", "PIL --> conversion PNG --> buffer mémoire buffer = io.BytesIO()", "]), style={ 'width': '50%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px',", "(x1, y1, x2, y2) image = np.array(image) images_list.append(image) return model.predict_classes(np.array(images_list))", "image content model: tf/keras classifier Returns ------- class id returned", "Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL --> conversion PNG --> buffer mémoire", "in_navbar=True, label='Modèle', ), ], brand=\"Menu\", brand_href=\"#\", color= \"#d90054\", dark=True )", "svp : {}'.format(content_type)), html.Hr(), html.Div('Raw Content'), html.Pre(contents, style=pre_style) ]) #", "= html.Div( [ dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"), html.P( [", "Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image, classifier)[0] return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src=contents,", "= { 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace': 'normal' } #", "dash import dash_core_components as dcc import dash_html_components as html import", "dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"), html.P( [ 'Cette application à pour", "{}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), ]) except: return html.Div([ html.Hr(), html.Div('Uniquement", "Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] ) def update_output_div(input_value): return html.H3('Valeur saisie", "]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')]) def update_output(contents): if contents is", "classify_image(image, classifier)[0] # Affichage de l'image return html.Div([ html.Hr(style={'margin-top': '75px'}),", "app.layout = html.Div([ html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou", "image. L\\'application fonctionne de la manière suivante : vous déposer", "'750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw Content'),", "= params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL'] # Load DNN model classifier", "image by model Parameters ---------- content: image content model: tf/keras", "contents is not None: content_type, content_string = contents.split(',') if 'image'", "buffer mémoire --> image base 64 buffer.seek(0) img_bytes = buffer.read()", "modèles capables de classer des panneaux de signalisation allemand à", "import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components", "d\\'une image. L\\'application fonctionne de la manière suivante : vous", "'width': '50%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed',", "modèle de classification predicted_class = classify_image(image, classifier)[0] # Affichage de", "import Image from constants import CLASSES import yaml with open('app.yaml')", "{}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw Content'), #html.Pre(contents, style=pre_style) ]) else:", "classifier Returns ------- class id returned by model classifier \"\"\"", "Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True, in_navbar=True, label='Modèle', ), ],", "= params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL'] # Load", "dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = { 'whiteSpace': 'pre-wrap', 'wordBreak':", "= dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de Neurones', header=True), dbc.DropdownMenuItem('SVM',", "]) except: return html.Div([ html.Hr(), html.Div('Uniquement des images svp :", "constants import CLASSES import yaml with open('app.yaml') as yaml_data :", "# box argument clips image to (x1, y1, x2, y2)", "# fichier base 64 --> image PIL image = Image.open(io.BytesIO(base64.b64decode(content_string)))", "className=\"card-title\"), html.P( [ 'Cette application à pour but de réaliser", "indiqué et la prédiction du modèle apparait immédiatement en dessous.", "L\\'application fonctionne de la manière suivante : vous déposer une", "partir d\\'une image. L\\'application fonctionne de la manière suivante :", "'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px',", "pouvez sélectionner le modèle que vous voulez tester.', ], className='card-text',", "numpy as np import tensorflow as tf from PIL import", "'margin-left': '370px', } ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement',", "--> conversion PNG --> buffer mémoire buffer = io.BytesIO() image.save(buffer,", "= Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL --> conversion PNG --> buffer", "return model.predict_classes(np.array(images_list)) app = dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style =", "html.P( [ 'Cette application à pour but de réaliser des", "yaml_data : params = yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT =", "html.Div([ html.Hr(), html.Div('Uniquement des images svp : {}'.format(content_type)), html.Hr(), html.Div('Raw", "className='w-75 mb-3', color='#f1cbd1', outline='Black', style={ 'margin-top': '75px', 'margin-left': '185px'}, ),", "'Cette application à pour but de réaliser des modèles capables", "--> image base 64 buffer.seek(0) img_bytes = buffer.read() content_string =", "argument clips image to (x1, y1, x2, y2) image =", "allemand à partir d\\'une image. L\\'application fonctionne de la manière", "html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')]) def update_output(contents): if", "de Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True, in_navbar=True, label='Modèle', ),", "= image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), box=image_box) # box argument clips image to", "html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' + content_string, style={'margin-left': '750px'}), html.H4('Classe prédite", "if contents is not None: content_type, content_string = contents.split(',') if", "saisie ici \"{}\"'.format(input_value)) # Start the application if __name__ ==", "64 (cas des fichiers ppm) # fichier base 64 -->", "Décodage de l'image transmise en base 64 (cas des fichiers", "de l'image return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' + content_string, style={'margin-left':", "@app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] ) def update_output_div(input_value): return html.H3('Valeur", "html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw Content'), #html.Pre(contents,", "html.Div( [ dbc.Card( dbc.CardBody( [ html.H5(\"Présentation\", className=\"card-title\"), html.P( [ 'Cette", "try: # Décodage de l'image transmise en base 64 (cas", "image = Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL --> conversion PNG -->", "à pour but de réaliser des modèles capables de classer", "DNN model classifier = tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model, image_box=None): \"\"\"Classify", "IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL'] #", "), className='w-75 mb-3', color='#f1cbd1', outline='Black', style={ 'margin-top': '75px', 'margin-left': '185px'},", "], nav=True, in_navbar=True, label='Modèle', ), ], brand=\"Menu\", brand_href=\"#\", color= \"#d90054\",", "img_bytes = buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii') # Appel du modèle", "from dash.dependencies import Input, Output import numpy as np import", "l\\'emplacement indiqué et la prédiction du modèle apparait immédiatement en", "] ), className='w-75 mb-3', color='#f1cbd1', outline='Black', style={ 'margin-top': '75px', 'margin-left':", "style=pre_style) ]) else: try: # Décodage de l'image transmise en", "content_type: image = Image.open(io.BytesIO(base64.b64decode(content_string))) predicted_class = classify_image(image, classifier)[0] return html.Div([", "layout navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de Neurones',", "#html.Pre(contents, style=pre_style) ]) else: try: # Décodage de l'image transmise", "{}'.format(content_type)), html.Hr(), html.Div('Raw Content'), html.Pre(contents, style=pre_style) ]) # Manage interactions", "'370px', } ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')])", "prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw Content'), #html.Pre(contents, style=pre_style)", "'textAlign': 'center', 'margin-top': '75px', 'margin-left': '370px', } ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat')", "style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), ])", "import io import dash import dash_core_components as dcc import dash_html_components", "', html.A('sélectionner une image') ]), style={ 'width': '50%', 'height': '60px',", "64 --> image PIL image = Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL", "'children'), [Input('bouton-chargement', 'contents')]) def update_output(contents): if contents is not None:", "brand=\"Menu\", brand_href=\"#\", color= \"#d90054\", dark=True ) cards = html.Div( [", "dbc from dash.dependencies import Input, Output import numpy as np", "], brand=\"Menu\", brand_href=\"#\", color= \"#d90054\", dark=True ) cards = html.Div(", "params['IMAGE_HEIGHT'] PATH_MODEL = params['PATH_MODEL'] # Load DNN model classifier =", "tester.', ], className='card-text', ), ] ), className='w-75 mb-3', color='#f1cbd1', outline='Black',", "'75px', 'margin-left': '370px', } ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'),", "dbc.DropdownMenuItem('Réseau de Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ], nav=True, in_navbar=True, label='Modèle',", "dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import", "html.Img(src='data:image/png;base64,' + content_string, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign':", "à droite vous pouvez sélectionner le modèle que vous voulez", "une image à l\\'emplacement indiqué et la prédiction du modèle", "children=[ dbc.DropdownMenu( children=[ dbc.DropdownMenuItem('Réseau de Neurones', header=True), dbc.DropdownMenuItem('SVM', href=\"#\"), ],", "= buffer.read() content_string = base64.b64encode(img_bytes).decode('ascii') # Appel du modèle de", "with open('app.yaml') as yaml_data : params = yaml.safe_load(yaml_data) IMAGE_WIDTH =", "with callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] ) def update_output_div(input_value):", "callbacks @app.callback( Output(component_id='ma-zone-resultat', component_property='children'), [Input(component_id='mon-champ-texte', component_property='value')] ) def update_output_div(input_value): return", ": {}'.format(content_type)), html.Hr(), html.Div('Raw Content'), html.Pre(contents, style=pre_style) ]) # Manage", "--> image PIL image = Image.open(io.BytesIO(base64.b64decode(content_string))) # image PIL -->", ": params = yaml.safe_load(yaml_data) IMAGE_WIDTH = params['IMAGE_WIDTH'] IMAGE_HEIGHT = params['IMAGE_HEIGHT']", "application à pour but de réaliser des modèles capables de", "app = dash.Dash('Traffic Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = { 'whiteSpace':", "box argument clips image to (x1, y1, x2, y2) image", "l'image return html.Div([ html.Hr(style={'margin-top': '75px'}), html.Img(src='data:image/png;base64,' + content_string, style={'margin-left': '750px'}),", "pour but de réaliser des modèles capables de classer des", "return html.H3('Valeur saisie ici \"{}\"'.format(input_value)) # Start the application if", "external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = { 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace': 'normal'", "classify_image(image, model, image_box=None): \"\"\"Classify image by model Parameters ---------- content:", "id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou ', html.A('sélectionner une image') ]), style={", "class id returned by model classifier \"\"\" images_list = []", "} ), html.Div(id='mon-image'), html.Div(id='ma-zone-resultat') ]) @app.callback(Output('mon-image', 'children'), [Input('bouton-chargement', 'contents')]) def", "html.Hr(style={'margin-top': '75px'}), html.Img(src=contents, style={'margin-left': '750px'}), html.H4('Classe prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign':", ") def update_output_div(input_value): return html.H3('Valeur saisie ici \"{}\"'.format(input_value)) # Start", "style={'textAlign': 'center'}), html.Hr(), #html.Div('Raw Content'), #html.Pre(contents, style=pre_style) ]) else: try:", "Signs Recognition', external_stylesheets=[dbc.themes.BOOTSTRAP]) pre_style = { 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all',", "not None: content_type, content_string = contents.split(',') if 'image' in content_type:", "prédite : {}'.format(CLASSES[predicted_class]), style={'textAlign': 'center'}), html.Hr(), ]) except: return html.Div([", "fonctionne de la manière suivante : vous déposer une image", "'whiteSpace': 'normal' } # Define application layout navbar = dbc.NavbarSimple(", "'pre-wrap', 'wordBreak': 'break-all', 'whiteSpace': 'normal' } # Define application layout", "droite vous pouvez sélectionner le modèle que vous voulez tester.',", "html.Div([navbar]), html.Div(cards), dcc.Upload( id='bouton-chargement', children=html.Div([ 'Cliquer-déposer ou ', html.A('sélectionner une", "base64.b64encode(img_bytes).decode('ascii') # Appel du modèle de classification predicted_class = classify_image(image,", "# Define application layout navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[", "className='card-text', ), ] ), className='w-75 mb-3', color='#f1cbd1', outline='Black', style={ 'margin-top':", "vous déposer une image à l\\'emplacement indiqué et la prédiction", "import numpy as np import tensorflow as tf from PIL", "'borderRadius': '5px', 'textAlign': 'center', 'margin-top': '75px', 'margin-left': '370px', } ),", "content_string = base64.b64encode(img_bytes).decode('ascii') # Appel du modèle de classification predicted_class", "buffer mémoire buffer = io.BytesIO() image.save(buffer, format='PNG') # buffer mémoire", "image_box=None): \"\"\"Classify image by model Parameters ---------- content: image content", "classifier = tf.keras.models.load_model(PATH_MODEL) def classify_image(image, model, image_box=None): \"\"\"Classify image by" ]
[ "json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover']", "json.loads(r.text) if data['count'] == 0: return None json_data = {}", "from django.conf import settings class rakuten: def get_json(self, isbn: str)", "import requests from django.conf import settings class rakuten: def get_json(self,", "r = requests.get(url) # decode to json # Check the", "json_data = {} json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher']", "API request template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format", "status code status_code = r.status_code if status_code != 200: #", "data['count'] == 0: return None json_data = {} json_data['isbn'] =", "None json_data = {} json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title']", "api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format get api URL", "status_code = r.status_code if status_code != 200: # if failed", "json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate']", "requests from django.conf import settings class rakuten: def get_json(self, isbn:", "r.status_code if status_code != 200: # if failed return None", "if status_code != 200: # if failed return None data", "the status code status_code = r.status_code if status_code != 200:", "= api.format(isbnjan=isbn, appid=appid) # execute r = requests.get(url) # decode", "= {} json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher'] =", "<gh_stars>1-10 import json import requests from django.conf import settings class", "json # Check the status code status_code = r.status_code if", "Check the status code status_code = r.status_code if status_code !=", "requests.get(url) # decode to json # Check the status code", "return None json_data = {} json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title'] =", "= \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format get api URL url", "# decode to json # Check the status code status_code", "None data = json.loads(r.text) if data['count'] == 0: return None", "class rakuten: def get_json(self, isbn: str) -> dict: appid =", "isbn: str) -> dict: appid = settings.RAKUTEN_APP_ID # API request", "import json import requests from django.conf import settings class rakuten:", "settings.RAKUTEN_APP_ID # API request template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\"", "failed return None data = json.loads(r.text) if data['count'] == 0:", "execute r = requests.get(url) # decode to json # Check", "0: return None json_data = {} json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title']", "template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format get api", "api.format(isbnjan=isbn, appid=appid) # execute r = requests.get(url) # decode to", "# if failed return None data = json.loads(r.text) if data['count']", "appid=appid) # execute r = requests.get(url) # decode to json", "data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover'] = data['Items'][0]['Item']['largeImageUrl']", "return None data = json.loads(r.text) if data['count'] == 0: return", "# execute r = requests.get(url) # decode to json #", "= data['Items'][0]['Item']['salesDate'] json_data['cover'] = data['Items'][0]['Item']['largeImageUrl'] json_data['author'] = data['Items'][0]['Item']['author'] return json_data", "get api URL url = api.format(isbnjan=isbn, appid=appid) # execute r", "= data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate'] =", "decode to json # Check the status code status_code =", "= data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover'] = data['Items'][0]['Item']['largeImageUrl'] json_data['author'] =", "# API request template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" #", "json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover'] = data['Items'][0]['Item']['largeImageUrl'] json_data['author'] = data['Items'][0]['Item']['author'] return", "{} json_data['isbn'] = data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName']", "# format get api URL url = api.format(isbnjan=isbn, appid=appid) #", "= requests.get(url) # decode to json # Check the status", "= data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover'] =", "data['Items'][0]['Item']['isbn'] json_data['title'] = data['Items'][0]['Item']['title'] json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate']", "status_code != 200: # if failed return None data =", "200: # if failed return None data = json.loads(r.text) if", "= settings.RAKUTEN_APP_ID # API request template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\", "rakuten: def get_json(self, isbn: str) -> dict: appid = settings.RAKUTEN_APP_ID", "= r.status_code if status_code != 200: # if failed return", "data = json.loads(r.text) if data['count'] == 0: return None json_data", "api URL url = api.format(isbnjan=isbn, appid=appid) # execute r =", "\"applicationId={appid}\" # format get api URL url = api.format(isbnjan=isbn, appid=appid)", "url = api.format(isbnjan=isbn, appid=appid) # execute r = requests.get(url) #", "\"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format get api URL url = api.format(isbnjan=isbn,", "if failed return None data = json.loads(r.text) if data['count'] ==", "appid = settings.RAKUTEN_APP_ID # API request template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\", "django.conf import settings class rakuten: def get_json(self, isbn: str) ->", "request template api = \"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format get", "!= 200: # if failed return None data = json.loads(r.text)", "\"https://app.rakuten.co.jp/services/api/BooksTotal/\"\\ \"Search/20170404?format=json&isbnjan={isbnjan}&\"\\ \"applicationId={appid}\" # format get api URL url =", "def get_json(self, isbn: str) -> dict: appid = settings.RAKUTEN_APP_ID #", "data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover'] = data['Items'][0]['Item']['largeImageUrl'] json_data['author'] = data['Items'][0]['Item']['author']", "# Check the status code status_code = r.status_code if status_code", "to json # Check the status code status_code = r.status_code", "= json.loads(r.text) if data['count'] == 0: return None json_data =", "URL url = api.format(isbnjan=isbn, appid=appid) # execute r = requests.get(url)", "settings class rakuten: def get_json(self, isbn: str) -> dict: appid", "if data['count'] == 0: return None json_data = {} json_data['isbn']", "code status_code = r.status_code if status_code != 200: # if", "json_data['publisher'] = data['Items'][0]['Item']['publisherName'] json_data['pubdate'] = data['Items'][0]['Item']['salesDate'] json_data['cover'] = data['Items'][0]['Item']['largeImageUrl'] json_data['author']", "json import requests from django.conf import settings class rakuten: def", "dict: appid = settings.RAKUTEN_APP_ID # API request template api =", "== 0: return None json_data = {} json_data['isbn'] = data['Items'][0]['Item']['isbn']", "import settings class rakuten: def get_json(self, isbn: str) -> dict:", "get_json(self, isbn: str) -> dict: appid = settings.RAKUTEN_APP_ID # API", "str) -> dict: appid = settings.RAKUTEN_APP_ID # API request template", "format get api URL url = api.format(isbnjan=isbn, appid=appid) # execute", "-> dict: appid = settings.RAKUTEN_APP_ID # API request template api" ]
[]
[ "role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, can_delegate: Optional[bool]", "Optional[List[str]] = None, not_data_actions: Optional[List[str]] = None, **kwargs ): super(Permission,", "The error message. :vartype message: str :ivar target: The error", "'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'},", ":type type: str :param display_name: The provider display name. :type", "= next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables are only populated", "Role assignment list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The URL", "'canDelegate', 'type': 'bool'}, } def __init__( self, *, principal_id: Optional[str]", "} def __init__( self, *, principal_id: Optional[str] = None, can_delegate:", "Optional[str] = None, permissions: Optional[List[\"Permission\"]] = None, assignable_scopes: Optional[List[str]] =", "self.is_data_action = is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata. :param id:", "is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata. :param id: The provider", "'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List[\"Permission\"]]", "None, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id", "'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key':", "info type. :vartype type: str :ivar info: The additional info.", "def __init__( self, *, role_name: Optional[str] = None, description: Optional[str]", "type operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'name':", "request. :ivar type: The additional info type. :vartype type: str", "name. :type role_name: str :param type: Returns role definition with", "{'key': 'resourceTypes', 'type': '[ResourceType]'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, }", ":param value: Role assignment list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link:", "not_data_actions: list[str] \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type':", "self, *, actions: Optional[List[str]] = None, not_actions: Optional[List[str]] = None,", ":vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation = { 'code': {'readonly': True},", "code: The error code. :vartype code: str :ivar message: The", "'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'role_name': {'key':", "{ 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True},", "ErrorDetail(msrest.serialization.Model): \"\"\"The error detail. Variables are only populated by the", "array of permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The URL", "= None, type: Optional[str] = None, display_name: Optional[str] = None,", ":type can_delegate: bool \"\"\" _validation = { 'id': {'readonly': True},", "role assignment name. :vartype name: str :ivar type: The role", "{'key': 'type', 'type': 'str'}, 'info': {'key': 'info', 'type': 'object'}, }", "delegation flag used for creating a role assignment. :type can_delegate:", "= { 'value': {'key': 'value', 'type': '[Permission]'}, 'next_link': {'key': 'nextLink',", "regenerated. # -------------------------------------------------------------------------- from typing import Any, List, Optional from", "True}, 'target': {'readonly': True}, 'details': {'readonly': True}, 'additional_info': {'readonly': True},", "True}, 'additional_info': {'readonly': True}, } _attribute_map = { 'code': {'key':", "populated by the server, and will be ignored when sending", "= principal_id self.can_delegate = can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter.", "= None, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.error = error class", "None, **kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value = value self.next_link =", ":type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'name': {'key': 'name',", "resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The provider operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation]", "role assignment scope. :type scope: str :param role_definition_id: The role", "request. :ivar code: The error code. :vartype code: str :ivar", "type: str :ivar info: The additional info. :vartype info: any", "self.details = None self.additional_info = None class ErrorResponse(msrest.serialization.Model): \"\"\"Common error", "name self.display_name = display_name self.description = description self.origin = origin", "= not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param value: An array", "self.name = name self.display_name = display_name self.operations = operations class", "{'key': 'notActions', 'type': '[str]'}, 'data_actions': {'key': 'dataActions', 'type': '[str]'}, 'not_data_actions':", "by the server, and will be ignored when sending a", "id: The role assignment ID. :vartype id: str :ivar name:", "): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id = id self.name = name self.type", "str :param resource_types: The provider resource types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType]", "display_name: The provider display name. :type display_name: str :param resource_types:", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'},", "(This also follows the OData error response format.). :param error:", "principal_id: str, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs)", "= { 'role_definition_id': {'required': True}, 'principal_id': {'required': True}, } _attribute_map", "when sending a request. :ivar type: The additional info type.", "self).__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate", ":param assignable_scopes: Role definition assignable scopes. :type assignable_scopes: list[str] \"\"\"", "super(RoleDefinition, self).__init__(**kwargs) self.id = None self.name = None self.type =", ":type not_data_actions: list[str] \"\"\" _attribute_map = { 'actions': {'key': 'actions',", "self, *, scope: Optional[str] = None, role_definition_id: Optional[str] = None,", "All required parameters must be populated in order to send", "resource_types self.operations = operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata list.", "use for getting the next set of results. :type next_link:", "can_delegate: The delegation flag used for creating a role assignment.", "'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'},", "name. :type name: str :param display_name: The operation display name.", "operation type. :type is_data_action: bool \"\"\" _attribute_map = { 'name':", "super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id = id self.name = name self.type =", "definition ID. :type role_definition_id: str :param principal_id: The principal ID.", "value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The URL to use for getting", "class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter. :param principal_id: Returns role assignment", "self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate class", "parameters must be populated in order to send to Azure.", "'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *,", "self).__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role", "{'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorDetail]'}, 'additional_info':", "'display_name': {'key': 'displayName', 'type': 'str'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'},", "the role assignment. :type can_delegate: bool \"\"\" _attribute_map = {", "'description', 'type': 'str'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key':", "{'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type':", "self.properties = properties self.is_data_action = is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations", "role_definition_id: Required. The role definition ID used in the role", "self.type = None self.info = None class ErrorDetail(msrest.serialization.Model): \"\"\"The error", "None, description: Optional[str] = None, role_type: Optional[str] = None, permissions:", "class ErrorDetail(msrest.serialization.Model): \"\"\"The error detail. Variables are only populated by", "scope self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate", "'str'}, 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes', 'type':", "\"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link':", "name: Optional[str] = None, display_name: Optional[str] = None, operations: Optional[List[\"ProviderOperation\"]]", "also follows the OData error response format.). :param error: The", "name. :type display_name: str :param description: The operation description. :type", "True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'},", "next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name: The operation name. :type", "type name. :type name: str :param display_name: The resource type", ":param origin: The operation origin. :type origin: str :param properties:", ":type origin: str :param properties: The operation properties. :type properties:", "= { 'actions': {'key': 'actions', 'type': '[str]'}, 'not_actions': {'key': 'notActions',", "'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'resource_types': {'key': 'resourceTypes', 'type':", "'type': 'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId',", "'str'}, 'details': {'key': 'details', 'type': '[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo', 'type':", "is regenerated. # -------------------------------------------------------------------------- from typing import Any, List, Optional", "role definition ID. :type role_definition_id: str :param principal_id: The principal", "= not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions class PermissionGetResult(msrest.serialization.Model):", "Definitions filter. :param role_name: Returns role definition with the specific", "= next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param name: The resource", "value self.next_link = next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name: The", "error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map = { 'error': {'key': 'error', 'type':", "= name self.type = type self.display_name = display_name self.resource_types =", "'str'}, } def __init__( self, *, role_name: Optional[str] = None,", "Variables are only populated by the server, and will be", "= { 'error': {'key': 'error', 'type': 'ErrorDetail'}, } def __init__(", "by Microsoft (R) AutoRest Code Generator. # Changes may cause", "all Azure Resource Manager APIs to return error details for", "= None self.info = None class ErrorDetail(msrest.serialization.Model): \"\"\"The error detail.", "} def __init__( self, *, role_name: Optional[str] = None, type:", "ID inside the Active Directory. It can point to a", "{ 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type':", "The list of providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The", "None, **kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id = principal_id self.can_delegate =", "= None, name: Optional[str] = None, type: Optional[str] = None,", "str, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id", "'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'},", "'[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self,", "str :param display_name: The operation display name. :type display_name: str", "role_type: Optional[str] = None, permissions: Optional[List[\"Permission\"]] = None, assignable_scopes: Optional[List[str]]", "permissions: Optional[List[\"Permission\"]] = None, assignable_scopes: Optional[List[str]] = None, **kwargs ):", "permissions: Role definition permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role", "The error additional info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation =", "sending a request. :ivar type: The additional info type. :vartype", "self.additional_info = None class ErrorResponse(msrest.serialization.Model): \"\"\"Common error response for all", "): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class", "'type': 'object'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, } def __init__(", "can_delegate: bool \"\"\" _validation = { 'role_definition_id': {'required': True}, 'principal_id':", "role assignment. :type can_delegate: bool \"\"\" _validation = { 'id':", "next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables are only populated by", "Assignments filter. :param principal_id: Returns role assignment of the specific", "{'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, 'is_data_action':", "'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, } def __init__( self, *,", "assignment. :type can_delegate: bool \"\"\" _validation = { 'role_definition_id': {'required':", "'actions', 'type': '[str]'}, 'not_actions': {'key': 'notActions', 'type': '[str]'}, 'data_actions': {'key':", ":param role_type: The role type. :type role_type: str :param permissions:", "= value self.next_link = next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param", "*, value: Optional[List[\"Permission\"]] = None, next_link: Optional[str] = None, **kwargs", "'[RoleAssignment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self,", "message. :vartype message: str :ivar target: The error target. :vartype", "'principal_id': {'key': 'principalId', 'type': 'str'}, 'can_delegate': {'key': 'canDelegate', 'type': 'bool'},", "Optional[bool] = None, **kwargs ): super(RoleAssignment, self).__init__(**kwargs) self.id = None", "The role definition ID. :vartype id: str :ivar name: The", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation = { 'code': {'readonly': True}, 'message': {'readonly':", "List, Optional from azure.core.exceptions import HttpResponseError import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model):", "principal_id self.can_delegate = can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create parameters.", "\"\"\"Role definition permissions. :param actions: Allowed actions. :type actions: list[str]", "'type': 'str'}, 'role_name': {'key': 'properties.roleName', 'type': 'str'}, 'description': {'key': 'properties.description',", "description: str :param role_type: The role type. :type role_type: str", "The error target. :vartype target: str :ivar details: The error", "} def __init__( self, *, role_definition_id: str, principal_id: str, can_delegate:", "assignable_scopes: Optional[List[str]] = None, **kwargs ): super(RoleDefinition, self).__init__(**kwargs) self.id =", "role_name: str :param description: The role definition description. :type description:", "principal_id: Required. The principal ID assigned to the role. This", "definition permissions. :param actions: Allowed actions. :type actions: list[str] :param", "origin: The operation origin. :type origin: str :param properties: The", "'[str]'}, 'data_actions': {'key': 'dataActions', 'type': '[str]'}, 'not_data_actions': {'key': 'notDataActions', 'type':", "format.). :param error: The error object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\"", "a request. :ivar type: The additional info type. :vartype type:", "The dataAction flag to specify the operation type. :type is_data_action:", "name: The resource type name. :type name: str :param display_name:", "creating a role assignment. :type can_delegate: bool \"\"\" _validation =", "= None, **kwargs ): super(RoleDefinition, self).__init__(**kwargs) self.id = None self.name", "Optional[str] = None, properties: Optional[Any] = None, is_data_action: Optional[bool] =", "operation result. :param value: Role definition list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition]", "type: The additional info type. :vartype type: str :ivar info:", "origin: Optional[str] = None, properties: Optional[Any] = None, is_data_action: Optional[bool]", "'info': {'key': 'info', 'type': 'object'}, } def __init__( self, **kwargs", "*, scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id:", "The delegation flag used for creating a role assignment. :type", "'type': '[ProviderOperation]'}, } def __init__( self, *, id: Optional[str] =", "_validation = { 'role_definition_id': {'required': True}, 'principal_id': {'required': True}, }", "be lost if the code is regenerated. # -------------------------------------------------------------------------- from", "Delegation flag for the role assignment. :type can_delegate: bool \"\"\"", "'notDataActions', 'type': '[str]'}, } def __init__( self, *, actions: Optional[List[str]]", "permissions self.assignable_scopes = assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter. :param", "'info', 'type': 'object'}, } def __init__( self, **kwargs ): super(ErrorAdditionalInfo,", "assignment name. :vartype name: str :ivar type: The role assignment", "'role_definition_id': {'required': True}, 'principal_id': {'required': True}, } _attribute_map = {", "display_name: Optional[str] = None, description: Optional[str] = None, origin: Optional[str]", "will be ignored when sending a request. :ivar code: The", "): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name = role_name self.type = type class", "actions: Allowed actions. :type actions: list[str] :param not_actions: Denied actions.", ":type name: str :param display_name: The operation display name. :type", "'str'}, 'description': {'key': 'description', 'type': 'str'}, 'origin': {'key': 'origin', 'type':", "'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__( self, *,", "assignment of the specific principal. :type principal_id: str :param can_delegate:", "def __init__( self, *, value: Optional[List[\"RoleDefinition\"]] = None, next_link: Optional[str]", "operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id =", "when sending a request. :ivar id: The role definition ID.", "{'key': 'properties.type', 'type': 'str'}, 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes':", "Optional[str] = None, principal_id: Optional[str] = None, can_delegate: Optional[bool] =", "_attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key':", "'str'}, } def __init__( self, *, value: Optional[List[\"RoleDefinition\"]] = None,", "'displayName', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'origin': {'key':", "error code. :vartype code: str :ivar message: The error message.", "def __init__( self, *, scope: Optional[str] = None, role_definition_id: Optional[str]", "OData error response format.). :param error: The error object. :type", "type. :type role_type: str :param permissions: Role definition permissions. :type", "name self.display_name = display_name self.operations = operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role", "= description self.origin = origin self.properties = properties self.is_data_action =", "} def __init__( self, *, id: Optional[str] = None, name:", "{'required': True}, 'principal_id': {'required': True}, } _attribute_map = { 'role_definition_id':", "to use for getting the next set of results. :type", "*, name: Optional[str] = None, display_name: Optional[str] = None, description:", "of providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The URL to", "The resource type display name. :type display_name: str :param operations:", "list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The URL to use", "{'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'description':", "the ID inside the Active Directory. It can point to", "for license information. # Code generated by Microsoft (R) AutoRest", "\"\"\"Role assignment create parameters. All required parameters must be populated", "None self.details = None self.additional_info = None class ErrorResponse(msrest.serialization.Model): \"\"\"Common", "'details': {'key': 'details', 'type': '[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'},", "None, name: Optional[str] = None, type: Optional[str] = None, display_name:", "for the role assignment. :type can_delegate: bool \"\"\" _attribute_map =", "Optional[str] = None, description: Optional[str] = None, role_type: Optional[str] =", "next set of results. :type next_link: str \"\"\" _attribute_map =", ":type role_definition_id: str :param principal_id: Required. The principal ID assigned", "_attribute_map = { 'role_name': {'key': 'roleName', 'type': 'str'}, 'type': {'key':", "create parameters. All required parameters must be populated in order", "a request. :ivar id: The role definition ID. :vartype id:", ":vartype type: str :ivar info: The additional info. :vartype info:", "# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", ":type principal_id: str :param can_delegate: The delegation flag used for", "self).__init__(**kwargs) self.value = value self.next_link = next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation.", "'str'}, } def __init__( self, *, value: Optional[List[\"Permission\"]] = None,", "= can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create parameters. All required", ":param role_definition_id: The role definition ID. :type role_definition_id: str :param", "ignored when sending a request. :ivar type: The additional info", "the OData error response format.). :param error: The error object.", "\"\"\"Provider Operations metadata. :param id: The provider id. :type id:", "self).__init__(**kwargs) self.code = None self.message = None self.target = None", "'details', 'type': '[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def", "'type': '[Permission]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(", "= None, **kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id = principal_id self.can_delegate", "Optional[str] = None, **kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name = role_name", "id: The role definition ID. :vartype id: str :ivar name:", "set of results. :type next_link: str \"\"\" _attribute_map = {", "role name. :type role_name: str :param description: The role definition", "_attribute_map = { 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key':", "self.actions = actions self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions", "can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id =", "filter. :param role_name: Returns role definition with the specific name.", "True}, 'principal_id': {'required': True}, } _attribute_map = { 'role_definition_id': {'key':", "None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None, can_delegate:", ":ivar name: The role definition name. :vartype name: str :ivar", "**kwargs ): super(PermissionGetResult, self).__init__(**kwargs) self.value = value self.next_link = next_link", "role. This maps to the ID inside the Active Directory.", "None, description: Optional[str] = None, origin: Optional[str] = None, properties:", "The error code. :vartype code: str :ivar message: The error", "not_actions: list[str] :param data_actions: Allowed Data actions. :type data_actions: list[str]", "principal_id: The principal ID. :type principal_id: str :param can_delegate: The", "'str'}, 'role_type': {'key': 'properties.type', 'type': 'str'}, 'permissions': {'key': 'properties.permissions', 'type':", "when sending a request. :ivar id: The role assignment ID.", "*, name: Optional[str] = None, display_name: Optional[str] = None, operations:", "Optional[List[str]] = None, data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]] =", ":type assignable_scopes: list[str] \"\"\" _validation = { 'id': {'readonly': True},", "target. :vartype target: str :ivar details: The error details. :vartype", "in the project root for license information. # Code generated", "type. :type type: str :param display_name: The provider display name.", "'description': {'key': 'properties.description', 'type': 'str'}, 'role_type': {'key': 'properties.type', 'type': 'str'},", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "self.code = None self.message = None self.target = None self.details", "None, role_type: Optional[str] = None, permissions: Optional[List[\"Permission\"]] = None, assignable_scopes:", "def __init__( self, *, id: Optional[str] = None, name: Optional[str]", "can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id =", "'[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__( self,", "None, **kwargs ): super(ProviderOperation, self).__init__(**kwargs) self.name = name self.display_name =", "str :param role_definition_id: The role definition ID. :type role_definition_id: str", "The operation name. :type name: str :param display_name: The operation", "\"\"\"Role Definitions filter. :param role_name: Returns role definition with the", "'[str]'}, 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, } def __init__( self,", "ID assigned to the role. This maps to the ID", "\"\"\"Permissions information. :param value: An array of permissions. :type value:", "'str'}, 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, } def __init__( self,", "HttpResponseError import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management error additional", "to a user, service principal, or security group. :type principal_id:", "additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation = { 'code': {'readonly': True}, 'message':", "None, next_link: Optional[str] = None, **kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs) self.value", "_attribute_map = { 'value': {'key': 'value', 'type': '[RoleAssignment]'}, 'next_link': {'key':", "None, not_data_actions: Optional[List[str]] = None, **kwargs ): super(Permission, self).__init__(**kwargs) self.actions", "permissions. :param actions: Allowed actions. :type actions: list[str] :param not_actions:", "'type': 'object'}, } def __init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs)", "*, role_definition_id: str, principal_id: str, can_delegate: Optional[bool] = None, **kwargs", "= None, next_link: Optional[str] = None, **kwargs ): super(PermissionGetResult, self).__init__(**kwargs)", "True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'},", "} def __init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type =", "{ 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type':", "self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info =", "= None, type: Optional[str] = None, **kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs)", "\"\"\" _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name':", ":param data_actions: Allowed Data actions. :type data_actions: list[str] :param not_data_actions:", "{'key': 'principalId', 'type': 'str'}, 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, }", "'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, } def __init__( self, *,", "True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key':", "will be ignored when sending a request. :ivar type: The", ":type not_actions: list[str] :param data_actions: Allowed Data actions. :type data_actions:", "not_data_actions: Denied Data actions. :type not_data_actions: list[str] \"\"\" _attribute_map =", "_attribute_map = { 'actions': {'key': 'actions', 'type': '[str]'}, 'not_actions': {'key':", "= None, next_link: Optional[str] = None, **kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs)", "\"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[Permission]'}, 'next_link':", "__init__( self, *, actions: Optional[List[str]] = None, not_actions: Optional[List[str]] =", ":param type: Returns role definition with the specific type. :type", "= None self.details = None self.additional_info = None class ErrorResponse(msrest.serialization.Model):", "{ 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId', 'type':", "= None, next_link: Optional[str] = None, **kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs)", "role definition with the specific name. :type role_name: str :param", "role definition description. :type description: str :param role_type: The role", "operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'id': {'key': 'id', 'type':", "license information. # Code generated by Microsoft (R) AutoRest Code", "Optional[str] = None, **kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value = value", "scope. :type scope: str :param role_definition_id: The role definition ID.", "= { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly':", "Code generated by Microsoft (R) AutoRest Code Generator. # Changes", "scope: str :param role_definition_id: The role definition ID. :type role_definition_id:", "id. :type id: str :param name: The provider name. :type", "'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'},", "def __init__( self, *, role_name: Optional[str] = None, type: Optional[str]", ":param name: The operation name. :type name: str :param display_name:", "\"\"\"Resource Type. :param name: The resource type name. :type name:", "Required. The principal ID assigned to the role. This maps", "**kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id", "} def __init__( self, *, error: Optional[\"ErrorDetail\"] = None, **kwargs", "can point to a user, service principal, or security group.", ":type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'id': {'key': 'id',", "name: Optional[str] = None, type: Optional[str] = None, display_name: Optional[str]", "RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter. :param role_name: Returns role definition with", "if the code is regenerated. # -------------------------------------------------------------------------- from typing import", "'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'description': {'key': 'description',", "Azure Resource Manager APIs to return error details for failed", "assignment. :type role_definition_id: str :param principal_id: Required. The principal ID", "self, *, role_definition_id: str, principal_id: str, can_delegate: Optional[bool] = None,", "{'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map", "None self.name = None self.type = None self.scope = scope", "The role name. :type role_name: str :param description: The role", "= description self.role_type = role_type self.permissions = permissions self.assignable_scopes =", "ID used in the role assignment. :type role_definition_id: str :param", "type: str \"\"\" _attribute_map = { 'role_name': {'key': 'roleName', 'type':", "'type': {'key': 'type', 'type': 'str'}, 'scope': {'key': 'properties.scope', 'type': 'str'},", "definition list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The URL to", "value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The URL to use for getting", "value self.next_link = next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables are", ":vartype code: str :ivar message: The error message. :vartype message:", "'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key':", "= None self.scope = scope self.role_definition_id = role_definition_id self.principal_id =", "Licensed under the MIT License. See License.txt in the project", "role_name: str :param type: Returns role definition with the specific", "assignment scope. :type scope: str :param role_definition_id: The role definition", "type: Optional[str] = None, **kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name =", "code is regenerated. # -------------------------------------------------------------------------- from typing import Any, List,", "'properties.canDelegate', 'type': 'bool'}, } def __init__( self, *, role_definition_id: str,", "'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, } def __init__( self, *,", "= None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ResourceType, self).__init__(**kwargs)", "target: str :ivar details: The error details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail]", "True}, 'info': {'readonly': True}, } _attribute_map = { 'type': {'key':", "**kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info = None", "self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment", "{'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details':", "assignment. :type can_delegate: bool \"\"\" _validation = { 'id': {'readonly':", "ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param name: The resource type name. :type", "{'key': 'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, }", "'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List[\"RoleDefinition\"]]", "Active Directory. It can point to a user, service principal,", "_attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key':", "assignment type. :vartype type: str :param scope: The role assignment", "None, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs", "with the specific name. :type role_name: str :param type: Returns", "= { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly':", "Optional[bool] = None, **kwargs ): super(ProviderOperation, self).__init__(**kwargs) self.name = name", "ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata list. :param value: The list of", "data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]] = None, **kwargs ):", "'[ProviderOperation]'}, } def __init__( self, *, id: Optional[str] = None,", "Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link: Optional[str] = None, **kwargs ): super(ProviderOperationsMetadataListResult,", "principal_id: Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs ):", ":type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The URL to use for", "\"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[RoleDefinition]'}, 'next_link':", "import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management error additional info.", "None class ErrorResponse(msrest.serialization.Model): \"\"\"Common error response for all Azure Resource", "*, value: Optional[List[\"RoleAssignment\"]] = None, next_link: Optional[str] = None, **kwargs", "'scope': {'key': 'properties.scope', 'type': 'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'},", "must be populated in order to send to Azure. :param", "class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list operation result. :param value: Role", ":vartype message: str :ivar target: The error target. :vartype target:", "inside the Active Directory. It can point to a user,", "assignable_scopes: Role definition assignable scopes. :type assignable_scopes: list[str] \"\"\" _validation", "typing import Any, List, Optional from azure.core.exceptions import HttpResponseError import", "the specific name. :type role_name: str :param type: Returns role", "parameters. All required parameters must be populated in order to", "The error object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map = {", "= None, is_data_action: Optional[bool] = None, **kwargs ): super(ProviderOperation, self).__init__(**kwargs)", "} def __init__( self, *, value: Optional[List[\"RoleDefinition\"]] = None, next_link:", "operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ResourceType, self).__init__(**kwargs) self.name =", "'[ProviderOperation]'}, } def __init__( self, *, name: Optional[str] = None,", "Returns role definition with the specific name. :type role_name: str", "\"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name':", "'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs ): super(ErrorDetail,", "type. :type type: str \"\"\" _attribute_map = { 'role_name': {'key':", "list operation result. :param value: Role assignment list. :type value:", "None, next_link: Optional[str] = None, **kwargs ): super(PermissionGetResult, self).__init__(**kwargs) self.value", "= None self.target = None self.details = None self.additional_info =", "self.display_name = display_name self.resource_types = resource_types self.operations = operations class", ":param name: The resource type name. :type name: str :param", "permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The URL to use", "None, **kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name = role_name self.type =", "'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'role_type': {'key': 'properties.type',", "The role assignment name. :vartype name: str :ivar type: The", "AutoRest Code Generator. # Changes may cause incorrect behavior and", "None, next_link: Optional[str] = None, **kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value", "super(ErrorDetail, self).__init__(**kwargs) self.code = None self.message = None self.target =", ":vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The error additional info. :vartype", "The role definition ID. :type role_definition_id: str :param principal_id: The", "None, type: Optional[str] = None, display_name: Optional[str] = None, resource_types:", "the Active Directory. It can point to a user, service", "self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions class", "type: The provider type. :type type: str :param display_name: The", "super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name = role_name self.type = type class RoleDefinitionListResult(msrest.serialization.Model):", "a role assignment. :type can_delegate: bool \"\"\" _validation = {", "= None self.message = None self.target = None self.details =", "Optional[str] = None, description: Optional[str] = None, origin: Optional[str] =", "Optional[str] = None, display_name: Optional[str] = None, operations: Optional[List[\"ProviderOperation\"]] =", "value: Optional[List[\"Permission\"]] = None, next_link: Optional[str] = None, **kwargs ):", "name: str :ivar type: The role assignment type. :vartype type:", "= None, next_link: Optional[str] = None, **kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs)", "Optional[Any] = None, is_data_action: Optional[bool] = None, **kwargs ): super(ProviderOperation,", "assignment list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The URL to", "display_name: The resource type display name. :type display_name: str :param", "Optional[str] = None, type: Optional[str] = None, display_name: Optional[str] =", ":param value: An array of permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param", "ID. :vartype id: str :ivar name: The role definition name.", "value self.next_link = next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param name:", "None, **kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id = id self.name =", ":param principal_id: The principal ID. :type principal_id: str :param can_delegate:", "None, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.error = error class Permission(msrest.serialization.Model):", "value: An array of permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link:", "True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True},", "'principal_id': {'required': True}, } _attribute_map = { 'role_definition_id': {'key': 'properties.roleDefinitionId',", "\"\"\" _validation = { 'id': {'readonly': True}, 'name': {'readonly': True},", "'type': 'str'}, 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, 'can_delegate': {'key': 'properties.canDelegate',", "None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ResourceType, self).__init__(**kwargs) self.name", "URL to use for getting the next set of results.", "*, actions: Optional[List[str]] = None, not_actions: Optional[List[str]] = None, data_actions:", "operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'name': {'key': 'name', 'type':", "description. :type description: str :param origin: The operation origin. :type", "# -------------------------------------------------------------------------- from typing import Any, List, Optional from azure.core.exceptions", "self, *, id: Optional[str] = None, name: Optional[str] = None,", "= resource_types self.operations = operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata", "'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details':", "with the specific type. :type type: str \"\"\" _attribute_map =", "value: The list of providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link:", "super(PermissionGetResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class ProviderOperation(msrest.serialization.Model):", "**kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.error = error class Permission(msrest.serialization.Model): \"\"\"Role", "= error class Permission(msrest.serialization.Model): \"\"\"Role definition permissions. :param actions: Allowed", "class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter. :param role_name: Returns role definition", "'role_name': {'key': 'properties.roleName', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'},", "description: str :param origin: The operation origin. :type origin: str", "service principal, or security group. :type principal_id: str :param can_delegate:", "'object'}, } def __init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type", "operation properties. :type properties: any :param is_data_action: The dataAction flag", "{'key': 'value', 'type': '[RoleDefinition]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, }", "_attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDetail'}, } def", "The additional info. :vartype info: any \"\"\" _validation = {", "return error details for failed operations. (This also follows the", "str :param operations: The resource type operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation]", "\"\"\" _attribute_map = { 'role_name': {'key': 'roleName', 'type': 'str'}, 'type':", "not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param value: An array of", "list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The URL to use", "Optional[str] = None, origin: Optional[str] = None, properties: Optional[Any] =", "providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The URL to use", "request. :ivar id: The role assignment ID. :vartype id: str", "'type': 'str'}, 'scope': {'key': 'properties.scope', 'type': 'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId',", "__init__( self, *, role_name: Optional[str] = None, type: Optional[str] =", "The provider name. :type name: str :param type: The provider", "role assignment. :type can_delegate: bool \"\"\" _attribute_map = { 'principal_id':", "'details': {'readonly': True}, 'additional_info': {'readonly': True}, } _attribute_map = {", "{'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type':", "msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management error additional info. Variables", "= None self.type = None self.role_name = role_name self.description =", "info. :vartype info: any \"\"\" _validation = { 'type': {'readonly':", "**kwargs ): super(Permission, self).__init__(**kwargs) self.actions = actions self.not_actions = not_actions", ":param scope: The role assignment scope. :type scope: str :param", "} def __init__( self, **kwargs ): super(ErrorDetail, self).__init__(**kwargs) self.code =", "description. :type description: str :param role_type: The role type. :type", "= None, **kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs) self.value = value self.next_link", "*, value: Optional[List[\"RoleDefinition\"]] = None, next_link: Optional[str] = None, **kwargs", "ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name: The operation name. :type name: str", "The resource type name. :type name: str :param display_name: The", "provider operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'id':", "Required. The role definition ID used in the role assignment.", "\"\"\" _validation = { 'role_definition_id': {'required': True}, 'principal_id': {'required': True},", ":type actions: list[str] :param not_actions: Denied actions. :type not_actions: list[str]", "{'key': 'description', 'type': 'str'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties':", "Changes may cause incorrect behavior and will be lost if", ":ivar name: The role assignment name. :vartype name: str :ivar", "type: The role assignment type. :vartype type: str :param scope:", "flag for the role assignment. :type can_delegate: bool \"\"\" _validation", ":param can_delegate: The Delegation flag for the role assignment. :type", "'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, 'is_data_action': {'key': 'isDataAction',", "Returns role definition with the specific type. :type type: str", "Optional from azure.core.exceptions import HttpResponseError import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The", "str :ivar name: The role definition name. :vartype name: str", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type':", ":param role_definition_id: Required. The role definition ID used in the", "send to Azure. :param role_definition_id: Required. The role definition ID", "data_actions: Allowed Data actions. :type data_actions: list[str] :param not_data_actions: Denied", "the specific type. :type type: str \"\"\" _attribute_map = {", "filter. :param principal_id: Returns role assignment of the specific principal.", "_attribute_map = { 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key':", "operations: The resource type operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map", "The role assignment type. :vartype type: str :param scope: The", "'type': 'str'}, } def __init__( self, *, value: Optional[List[\"RoleDefinition\"]] =", "{ 'type': {'key': 'type', 'type': 'str'}, 'info': {'key': 'info', 'type':", "'additional_info': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code',", "MIT License. See License.txt in the project root for license", "**kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link", "is_data_action: bool \"\"\" _attribute_map = { 'name': {'key': 'name', 'type':", "\"\"\"Provider operations metadata list. :param value: The list of providers.", "super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class ResourceType(msrest.serialization.Model):", "'type': '[ResourceType]'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__(", "'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, } def __init__( self, *,", "{'key': 'type', 'type': 'str'}, } def __init__( self, *, role_name:", "'str'}, 'scope': {'key': 'properties.scope', 'type': 'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type':", "{'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, 'can_delegate':", "of permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The URL to", "response for all Azure Resource Manager APIs to return error", "None self.role_name = role_name self.description = description self.role_type = role_type", "import HttpResponseError import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management error", "{'key': 'isDataAction', 'type': 'bool'}, } def __init__( self, *, name:", "= None, properties: Optional[Any] = None, is_data_action: Optional[bool] = None,", "name. :vartype name: str :ivar type: The role assignment type.", "definition ID. :vartype id: str :ivar name: The role definition", "error target. :vartype target: str :ivar details: The error details.", "APIs to return error details for failed operations. (This also", "The Delegation flag for the role assignment. :type can_delegate: bool", "role assignment type. :vartype type: str :param scope: The role", "def __init__( self, *, principal_id: Optional[str] = None, can_delegate: Optional[bool]", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'name': {'key': 'name', 'type': 'str'},", "request. :ivar id: The role definition ID. :vartype id: str", "= None, **kwargs ): super(ProviderOperation, self).__init__(**kwargs) self.name = name self.display_name", "'value': {'key': 'value', 'type': '[Permission]'}, 'next_link': {'key': 'nextLink', 'type': 'str'},", "Optional[str] = None, display_name: Optional[str] = None, resource_types: Optional[List[\"ResourceType\"]] =", "provider name. :type name: str :param type: The provider type.", "self.type = None self.role_name = role_name self.description = description self.role_type", "role definition ID. :vartype id: str :ivar name: The role", "definition ID used in the role assignment. :type role_definition_id: str", "'display_name': {'key': 'displayName', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'},", "def __init__( self, *, error: Optional[\"ErrorDetail\"] = None, **kwargs ):", "'type': 'ErrorDetail'}, } def __init__( self, *, error: Optional[\"ErrorDetail\"] =", "target: The error target. :vartype target: str :ivar details: The", "Optional[str] = None, type: Optional[str] = None, **kwargs ): super(RoleDefinitionFilter,", "'type': '[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, } def __init__(", "name. :type name: str :param type: The provider type. :type", "All rights reserved. # Licensed under the MIT License. See", "None, display_name: Optional[str] = None, description: Optional[str] = None, origin:", "'ErrorDetail'}, } def __init__( self, *, error: Optional[\"ErrorDetail\"] = None,", "'type': 'str'}, 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, } def __init__(", "used in the role assignment. :type role_definition_id: str :param principal_id:", "super(ProviderOperation, self).__init__(**kwargs) self.name = name self.display_name = display_name self.description =", "lost if the code is regenerated. # -------------------------------------------------------------------------- from typing", "The operation description. :type description: str :param origin: The operation", "str \"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[Permission]'},", "= None class ErrorDetail(msrest.serialization.Model): \"\"\"The error detail. Variables are only", "additional info type. :vartype type: str :ivar info: The additional", "= assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter. :param role_name: Returns", "self.assignable_scopes = assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter. :param role_name:", "None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id", "{'key': 'properties.assignableScopes', 'type': '[str]'}, } def __init__( self, *, role_name:", "'type': 'str'}, 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, } def __init__(", "operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables are only populated by", ":param next_link: The URL to use for getting the next", "a user, service principal, or security group. :type principal_id: str", "= id self.name = name self.type = type self.display_name =", "'target': {'readonly': True}, 'details': {'readonly': True}, 'additional_info': {'readonly': True}, }", "the role assignment. :type role_definition_id: str :param principal_id: Required. The", "= role_name self.description = description self.role_type = role_type self.permissions =", "Code Generator. # Changes may cause incorrect behavior and will", "'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, 'additional_info':", "None, display_name: Optional[str] = None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs", ":param role_name: The role name. :type role_name: str :param description:", ":param display_name: The provider display name. :type display_name: str :param", "role assignment. :type can_delegate: bool \"\"\" _validation = { 'role_definition_id':", "'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'display_name': {'key':", ":param value: Role definition list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link:", "for getting the next set of results. :type next_link: str", "self.message = None self.target = None self.details = None self.additional_info", "getting the next set of results. :type next_link: str \"\"\"", "'type', 'type': 'str'}, 'scope': {'key': 'properties.scope', 'type': 'str'}, 'role_definition_id': {'key':", "maps to the ID inside the Active Directory. It can", "properties: Optional[Any] = None, is_data_action: Optional[bool] = None, **kwargs ):", "Optional[bool] = None, **kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id = role_definition_id", "display_name: Optional[str] = None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ):", "Optional[List[\"ResourceType\"]] = None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ProviderOperationsMetadata,", "None, display_name: Optional[str] = None, resource_types: Optional[List[\"ResourceType\"]] = None, operations:", "= None class ErrorResponse(msrest.serialization.Model): \"\"\"Common error response for all Azure", "operations. (This also follows the OData error response format.). :param", "'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def", ":type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The URL to use for", "'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self,", "'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scope': {'key': 'properties.scope',", "= can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter. :param principal_id: Returns", "resource management error additional info. Variables are only populated by", "The additional info type. :vartype type: str :ivar info: The", "{'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'role_name':", "{'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__( self, *, name:", "= None, not_data_actions: Optional[List[str]] = None, **kwargs ): super(Permission, self).__init__(**kwargs)", "'description': {'key': 'description', 'type': 'str'}, 'origin': {'key': 'origin', 'type': 'str'},", "properties self.is_data_action = is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata. :param", "'type': '[str]'}, } def __init__( self, *, actions: Optional[List[str]] =", "operation description. :type description: str :param origin: The operation origin.", "= type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list operation result. :param", "): super(RoleAssignment, self).__init__(**kwargs) self.id = None self.name = None self.type", ":param can_delegate: The delegation flag used for creating a role", "} _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name':", "'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details',", "name. :type display_name: str :param operations: The resource type operations.", ":param display_name: The operation display name. :type display_name: str :param", "'value': {'key': 'value', 'type': '[RoleDefinition]'}, 'next_link': {'key': 'nextLink', 'type': 'str'},", "self.next_link = next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name: The operation", "str :param can_delegate: The delegation flag used for creating a", "role assignment. :type role_definition_id: str :param principal_id: Required. The principal", ":param name: The provider name. :type name: str :param type:", "operation display name. :type display_name: str :param description: The operation", "self).__init__(**kwargs) self.type = None self.info = None class ErrorDetail(msrest.serialization.Model): \"\"\"The", "server, and will be ignored when sending a request. :ivar", ":type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The URL to use for", "class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param value: An array of permissions.", "str :param display_name: The provider display name. :type display_name: str", "} def __init__( self, *, actions: Optional[List[str]] = None, not_actions:", "bool \"\"\" _validation = { 'role_definition_id': {'required': True}, 'principal_id': {'required':", "None, type: Optional[str] = None, **kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name", "error response format.). :param error: The error object. :type error:", "value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The URL to use for getting", "'[str]'}, } def __init__( self, *, role_name: Optional[str] = None,", "scope: The role assignment scope. :type scope: str :param role_definition_id:", "\"\"\"The resource management error additional info. Variables are only populated", "any :param is_data_action: The dataAction flag to specify the operation", "str :ivar type: The role definition type. :vartype type: str", "= operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata list. :param value:", "can_delegate: The Delegation flag for the role assignment. :type can_delegate:", "\"\"\" _validation = { 'code': {'readonly': True}, 'message': {'readonly': True},", "type display name. :type display_name: str :param operations: The resource", "provider display name. :type display_name: str :param resource_types: The provider", "role_type self.permissions = permissions self.assignable_scopes = assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role", "security group. :type principal_id: str :param can_delegate: The delegation flag", "The role definition description. :type description: str :param role_type: The", "role_name: Optional[str] = None, type: Optional[str] = None, **kwargs ):", "= None, description: Optional[str] = None, role_type: Optional[str] = None,", "class ErrorResponse(msrest.serialization.Model): \"\"\"Common error response for all Azure Resource Manager", "__init__( self, *, role_definition_id: str, principal_id: str, can_delegate: Optional[bool] =", "self.origin = origin self.properties = properties self.is_data_action = is_data_action class", "next_link: Optional[str] = None, **kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value =", "**kwargs ): super(ResourceType, self).__init__(**kwargs) self.name = name self.display_name = display_name", "'displayName', 'type': 'str'}, 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, 'operations': {'key':", "Any, List, Optional from azure.core.exceptions import HttpResponseError import msrest.serialization class", "the specific principal. :type principal_id: str :param can_delegate: The Delegation", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The URL to use for getting the", "__init__( self, *, value: Optional[List[\"RoleDefinition\"]] = None, next_link: Optional[str] =", "additional info. :vartype info: any \"\"\" _validation = { 'type':", "'isDataAction', 'type': 'bool'}, } def __init__( self, *, name: Optional[str]", "'type': '[RoleDefinition]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(", "self).__init__(**kwargs) self.value = value self.next_link = next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role", "'type': {'key': 'type', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'},", "name. :type role_name: str :param description: The role definition description.", "self.name = name self.display_name = display_name self.description = description self.origin", "ID. :vartype id: str :ivar name: The role assignment name.", "info: any \"\"\" _validation = { 'type': {'readonly': True}, 'info':", "origin. :type origin: str :param properties: The operation properties. :type", "self.target = None self.details = None self.additional_info = None class", "} def __init__( self, *, value: Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link:", "'type', 'type': 'str'}, } def __init__( self, *, role_name: Optional[str]", "type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list operation result. :param value:", "The error details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The error", "Optional[str] = None, **kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value = value", "Microsoft Corporation. All rights reserved. # Licensed under the MIT", "'bool'}, } def __init__( self, *, name: Optional[str] = None,", ":vartype id: str :ivar name: The role definition name. :vartype", "{ 'role_definition_id': {'required': True}, 'principal_id': {'required': True}, } _attribute_map =", "self.permissions = permissions self.assignable_scopes = assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions", "None self.message = None self.target = None self.details = None", "detail. Variables are only populated by the server, and will", "'role_type': {'key': 'properties.type', 'type': 'str'}, 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'},", "'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = {", "role assignment ID. :vartype id: str :ivar name: The role", "The principal ID. :type principal_id: str :param can_delegate: The Delegation", "definition type. :vartype type: str :param role_name: The role name.", "{'key': 'dataActions', 'type': '[str]'}, 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, }", "next_link: Optional[str] = None, **kwargs ): super(PermissionGetResult, self).__init__(**kwargs) self.value =", "self, *, value: Optional[List[\"Permission\"]] = None, next_link: Optional[str] = None,", "{'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly':", "name: str :ivar type: The role definition type. :vartype type:", "'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type':", "id: str :ivar name: The role definition name. :vartype name:", "} def __init__( self, *, value: Optional[List[\"RoleAssignment\"]] = None, next_link:", "str :param properties: The operation properties. :type properties: any :param", "The operation properties. :type properties: any :param is_data_action: The dataAction", "self.id = None self.name = None self.type = None self.role_name", "object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map = { 'error': {'key':", "assignment list operation result. :param value: Role assignment list. :type", "= None, **kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value = value self.next_link", "super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info = None class ErrorDetail(msrest.serialization.Model):", "actions: list[str] :param not_actions: Denied actions. :type not_actions: list[str] :param", "): super(Permission, self).__init__(**kwargs) self.actions = actions self.not_actions = not_actions self.data_actions", "'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List[\"RoleAssignment\"]]", "{'key': 'displayName', 'type': 'str'}, 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, 'operations':", "= { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName',", "*, role_name: Optional[str] = None, type: Optional[str] = None, **kwargs", "display_name: str :param resource_types: The provider resource types. :type resource_types:", "The provider display name. :type display_name: str :param resource_types: The", "'type': 'bool'}, } def __init__( self, *, name: Optional[str] =", "= { 'type': {'readonly': True}, 'info': {'readonly': True}, } _attribute_map", "'operations', 'type': '[ProviderOperation]'}, } def __init__( self, *, id: Optional[str]", "bool \"\"\" _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'},", "str :param description: The operation description. :type description: str :param", "self.display_name = display_name self.operations = operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments.", "self.not_data_actions = not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param value: An", "_attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'info': {'key':", "{'key': 'info', 'type': 'object'}, } def __init__( self, **kwargs ):", "'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scope': {'key':", "= can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list operation result. :param", "{'key': 'type', 'type': 'str'}, 'role_name': {'key': 'properties.roleName', 'type': 'str'}, 'description':", "str :param permissions: Role definition permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param", "See License.txt in the project root for license information. #", "= None, permissions: Optional[List[\"Permission\"]] = None, assignable_scopes: Optional[List[str]] = None,", "principal_id self.can_delegate = can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list operation", "name. :type name: str :param display_name: The resource type display", "definition. Variables are only populated by the server, and will", "'type': 'str'}, 'info': {'key': 'info', 'type': 'object'}, } def __init__(", "'type', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'resource_types': {'key':", "role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role", "name. :vartype name: str :ivar type: The role definition type.", "None, **kwargs ): super(RoleAssignment, self).__init__(**kwargs) self.id = None self.name =", "information. # Code generated by Microsoft (R) AutoRest Code Generator.", "): super(ProviderOperation, self).__init__(**kwargs) self.name = name self.display_name = display_name self.description", "principal. :type principal_id: str :param can_delegate: The Delegation flag for", "list[str] :param not_data_actions: Denied Data actions. :type not_data_actions: list[str] \"\"\"", "the next set of results. :type next_link: str \"\"\" _attribute_map", "'str'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__( self,", "): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info = None class", "Optional[bool] = None, **kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id = principal_id", "super(RoleAssignment, self).__init__(**kwargs) self.id = None self.name = None self.type =", "result. :param value: Role assignment list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param", "**kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link", "can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter. :param principal_id: Returns role", "'properties.scope', 'type': 'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key':", "self.data_actions = data_actions self.not_data_actions = not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information.", "_attribute_map = { 'value': {'key': 'value', 'type': '[Permission]'}, 'next_link': {'key':", "{'key': 'properties.scope', 'type': 'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id':", "Optional[str] = None, **kwargs ): super(PermissionGetResult, self).__init__(**kwargs) self.value = value", "used for creating a role assignment. :type can_delegate: bool \"\"\"", "display_name self.resource_types = resource_types self.operations = operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider", "# Changes may cause incorrect behavior and will be lost", "*, value: Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link: Optional[str] = None, **kwargs", "display_name: str :param operations: The resource type operations. :type operations:", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The provider operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\"", "results. :type next_link: str \"\"\" _attribute_map = { 'value': {'key':", "\"\"\"Role Assignments. Variables are only populated by the server, and", "None, assignable_scopes: Optional[List[str]] = None, **kwargs ): super(RoleDefinition, self).__init__(**kwargs) self.id", "type. :vartype type: str :param role_name: The role name. :type", "self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment", "self.type = type self.display_name = display_name self.resource_types = resource_types self.operations", "role definition type. :vartype type: str :param role_name: The role", "= principal_id self.can_delegate = can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create", "*, id: Optional[str] = None, name: Optional[str] = None, type:", "error class Permission(msrest.serialization.Model): \"\"\"Role definition permissions. :param actions: Allowed actions.", "can_delegate: bool \"\"\" _validation = { 'id': {'readonly': True}, 'name':", "ID. :type principal_id: str :param can_delegate: The Delegation flag for", "RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables are only populated by the server,", "{'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs ):", "{ 'value': {'key': 'value', 'type': '[Permission]'}, 'next_link': {'key': 'nextLink', 'type':", "'type': 'str'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__(", ":param error: The error object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map", "Type. :param name: The resource type name. :type name: str", "type. :vartype type: str :ivar info: The additional info. :vartype", "role definition ID used in the role assignment. :type role_definition_id:", "= data_actions self.not_data_actions = not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param", "'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'role_type': {'key': 'properties.type', 'type':", "self.description = description self.role_type = role_type self.permissions = permissions self.assignable_scopes", "root for license information. # Code generated by Microsoft (R)", ":type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The provider operations. :type operations:", "operation origin. :type origin: str :param properties: The operation properties.", "\"\"\"Common error response for all Azure Resource Manager APIs to", "'resourceTypes', 'type': '[ResourceType]'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def", ":type role_type: str :param permissions: Role definition permissions. :type permissions:", "id self.name = name self.type = type self.display_name = display_name", "'type': '[str]'}, 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, } def __init__(", "actions. :type actions: list[str] :param not_actions: Denied actions. :type not_actions:", "'[str]'}, } def __init__( self, *, actions: Optional[List[str]] = None,", ":type role_name: str :param type: Returns role definition with the", "Optional[str] = None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ResourceType,", "self.name = None self.type = None self.scope = scope self.role_definition_id", "Optional[List[\"Permission\"]] = None, next_link: Optional[str] = None, **kwargs ): super(PermissionGetResult,", "in order to send to Azure. :param role_definition_id: Required. The", "value: Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link: Optional[str] = None, **kwargs ):", "str :param can_delegate: The Delegation flag for the role assignment.", "= None, assignable_scopes: Optional[List[str]] = None, **kwargs ): super(RoleDefinition, self).__init__(**kwargs)", "def __init__( self, *, value: Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link: Optional[str]", ":type data_actions: list[str] :param not_data_actions: Denied Data actions. :type not_data_actions:", "str :param description: The role definition description. :type description: str", "'type', 'type': 'str'}, 'info': {'key': 'info', 'type': 'object'}, } def", "RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables are only populated by the server,", "= None, display_name: Optional[str] = None, operations: Optional[List[\"ProviderOperation\"]] = None,", "Role definition permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role definition", "Permission(msrest.serialization.Model): \"\"\"Role definition permissions. :param actions: Allowed actions. :type actions:", "to the ID inside the Active Directory. It can point", "to Azure. :param role_definition_id: Required. The role definition ID used", ":ivar type: The additional info type. :vartype type: str :ivar", "'[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs ): super(ErrorDetail, self).__init__(**kwargs) self.code", "'type': '[str]'}, 'data_actions': {'key': 'dataActions', 'type': '[str]'}, 'not_data_actions': {'key': 'notDataActions',", "role_name: Optional[str] = None, description: Optional[str] = None, role_type: Optional[str]", "str :param type: Returns role definition with the specific type.", "role definition with the specific type. :type type: str \"\"\"", "only populated by the server, and will be ignored when", "next_link: str \"\"\" _attribute_map = { 'value': {'key': 'value', 'type':", "'bool'}, } def __init__( self, *, principal_id: Optional[str] = None,", "for failed operations. (This also follows the OData error response", "error additional info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation = {", "RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list operation result. :param value: Role definition", ":vartype id: str :ivar name: The role assignment name. :vartype", "role_name: Returns role definition with the specific name. :type role_name:", "{'key': 'displayName', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'origin':", "**kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate", "'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'description': {'key':", "= display_name self.description = description self.origin = origin self.properties =", "= None, **kwargs ): super(PermissionGetResult, self).__init__(**kwargs) self.value = value self.next_link", "None, resource_types: Optional[List[\"ResourceType\"]] = None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs", "order to send to Azure. :param role_definition_id: Required. The role", "list[str] \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[str]'},", "Optional[List[str]] = None, not_actions: Optional[List[str]] = None, data_actions: Optional[List[str]] =", "'type': 'str'}, } def __init__( self, *, role_name: Optional[str] =", "import Any, List, Optional from azure.core.exceptions import HttpResponseError import msrest.serialization", "list[str] :param not_actions: Denied actions. :type not_actions: list[str] :param data_actions:", "= None, **kwargs ): super(RoleAssignment, self).__init__(**kwargs) self.id = None self.name", "'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'operations': {'key':", "list operation result. :param value: Role definition list. :type value:", "self, *, role_name: Optional[str] = None, type: Optional[str] = None,", ":type description: str :param role_type: The role type. :type role_type:", "'type': '[ProviderOperation]'}, } def __init__( self, *, name: Optional[str] =", "{'key': 'value', 'type': '[RoleAssignment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, }", "*, error: Optional[\"ErrorDetail\"] = None, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.error", ":type principal_id: str :param can_delegate: The Delegation flag for the", "\"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[RoleAssignment]'}, 'next_link':", ":type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map = { 'error': {'key': 'error',", "\"\"\" _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'can_delegate':", "self, *, value: Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link: Optional[str] = None,", ":param id: The provider id. :type id: str :param name:", "'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId', 'type': 'str'},", "): super(RoleDefinition, self).__init__(**kwargs) self.id = None self.name = None self.type", "{'key': 'error', 'type': 'ErrorDetail'}, } def __init__( self, *, error:", "= None, **kwargs ): super(ResourceType, self).__init__(**kwargs) self.name = name self.display_name", "'[str]'}, 'not_actions': {'key': 'notActions', 'type': '[str]'}, 'data_actions': {'key': 'dataActions', 'type':", "'type': {'readonly': True}, 'info': {'readonly': True}, } _attribute_map = {", "Data actions. :type not_data_actions: list[str] \"\"\" _attribute_map = { 'actions':", "An array of permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The", "'str'}, 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, 'operations': {'key': 'operations', 'type':", "behavior and will be lost if the code is regenerated.", "response format.). :param error: The error object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail", "additional info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation = { 'code':", "role_definition_id: str, principal_id: str, can_delegate: Optional[bool] = None, **kwargs ):", "The role assignment scope. :type scope: str :param role_definition_id: The", ":param role_name: Returns role definition with the specific name. :type", "Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str] =", "= name self.display_name = display_name self.description = description self.origin =", "'principal_id': {'key': 'properties.principalId', 'type': 'str'}, 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'},", "= None, resource_types: Optional[List[\"ResourceType\"]] = None, operations: Optional[List[\"ProviderOperation\"]] = None,", "result. :param value: Role definition list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param", "{'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'operations':", "from typing import Any, List, Optional from azure.core.exceptions import HttpResponseError", "and will be ignored when sending a request. :ivar type:", "{'readonly': True}, 'info': {'readonly': True}, } _attribute_map = { 'type':", "= None self.name = None self.type = None self.scope =", "Optional[List[\"RoleDefinition\"]] = None, next_link: Optional[str] = None, **kwargs ): super(RoleDefinitionListResult,", "'object'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, } def __init__( self,", "self.info = None class ErrorDetail(msrest.serialization.Model): \"\"\"The error detail. Variables are", "~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDetail'},", "the server, and will be ignored when sending a request.", "{ 'actions': {'key': 'actions', 'type': '[str]'}, 'not_actions': {'key': 'notActions', 'type':", "= None, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentFilter, self).__init__(**kwargs)", ":type id: str :param name: The provider name. :type name:", "self.resource_types = resource_types self.operations = operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations", "): super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate class", "self.can_delegate = can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list operation result.", "): super(ResourceType, self).__init__(**kwargs) self.name = name self.display_name = display_name self.operations", "{ 'value': {'key': 'value', 'type': '[RoleAssignment]'}, 'next_link': {'key': 'nextLink', 'type':", "The provider resource types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The", "Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect", "= None, not_actions: Optional[List[str]] = None, data_actions: Optional[List[str]] = None,", "data_actions: list[str] :param not_data_actions: Denied Data actions. :type not_data_actions: list[str]", "Role definition list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The URL", "can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create parameters. All required parameters", "self, *, role_name: Optional[str] = None, description: Optional[str] = None,", "'type': 'str'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties',", "str \"\"\" _attribute_map = { 'role_name': {'key': 'roleName', 'type': 'str'},", "self.value = value self.next_link = next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param", "{'key': 'canDelegate', 'type': 'bool'}, } def __init__( self, *, principal_id:", "{'key': 'properties.description', 'type': 'str'}, 'role_type': {'key': 'properties.type', 'type': 'str'}, 'permissions':", "display_name: The operation display name. :type display_name: str :param description:", "ignored when sending a request. :ivar id: The role assignment", "The role definition type. :vartype type: str :param role_name: The", "type: str :param scope: The role assignment scope. :type scope:", "str :param role_type: The role type. :type role_type: str :param", "type. :vartype type: str :param scope: The role assignment scope.", "of results. :type next_link: str \"\"\" _attribute_map = { 'value':", "next_link: The URL to use for getting the next set", "details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The error additional info.", "{'key': 'properties.canDelegate', 'type': 'bool'}, } def __init__( self, *, role_definition_id:", "error response for all Azure Resource Manager APIs to return", "} def __init__( self, *, role_name: Optional[str] = None, description:", "'data_actions': {'key': 'dataActions', 'type': '[str]'}, 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'},", "= value self.next_link = next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name:", "= display_name self.resource_types = resource_types self.operations = operations class ProviderOperationsMetadataListResult(msrest.serialization.Model):", "{ 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink', 'type':", "self).__init__(**kwargs) self.name = name self.display_name = display_name self.operations = operations", "= operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables are only populated", "name: str :param type: The provider type. :type type: str", "*, role_name: Optional[str] = None, description: Optional[str] = None, role_type:", "can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list operation result. :param value:", "} _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'info':", ":ivar details: The error details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info:", ":type display_name: str :param description: The operation description. :type description:", ":type description: str :param origin: The operation origin. :type origin:", "from azure.core.exceptions import HttpResponseError import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource", "Role definition assignable scopes. :type assignable_scopes: list[str] \"\"\" _validation =", "= permissions self.assignable_scopes = assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter.", "info. Variables are only populated by the server, and will", "'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scope': {'key': 'properties.scope', 'type':", "{'required': True}, } _attribute_map = { 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type':", "role_type: The role type. :type role_type: str :param permissions: Role", "types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The provider operations. :type", "None self.type = None self.scope = scope self.role_definition_id = role_definition_id", "The provider type. :type type: str :param display_name: The provider", "*, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs", "'not_actions': {'key': 'notActions', 'type': '[str]'}, 'data_actions': {'key': 'dataActions', 'type': '[str]'},", "{ 'value': {'key': 'value', 'type': '[RoleDefinition]'}, 'next_link': {'key': 'nextLink', 'type':", "None, permissions: Optional[List[\"Permission\"]] = None, assignable_scopes: Optional[List[str]] = None, **kwargs", "self, **kwargs ): super(ErrorDetail, self).__init__(**kwargs) self.code = None self.message =", "'value': {'key': 'value', 'type': '[RoleAssignment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'},", "message: str :ivar target: The error target. :vartype target: str", "flag for the role assignment. :type can_delegate: bool \"\"\" _attribute_map", "error: The error object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map =", "generated by Microsoft (R) AutoRest Code Generator. # Changes may", "str :ivar info: The additional info. :vartype info: any \"\"\"", ":type properties: any :param is_data_action: The dataAction flag to specify", "'type': 'str'}, 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes',", "description self.role_type = role_type self.permissions = permissions self.assignable_scopes = assignable_scopes", "actions. :type not_actions: list[str] :param data_actions: Allowed Data actions. :type", "id: The provider id. :type id: str :param name: The", "= role_name self.type = type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list", "details for failed operations. (This also follows the OData error", "ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata. :param id: The provider id. :type", ":ivar id: The role assignment ID. :vartype id: str :ivar", "details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The error additional info. :vartype additional_info:", "principal_id: str :param can_delegate: The delegation flag used for creating", "value: Role assignment list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment] :param next_link: The", "description: The operation description. :type description: str :param origin: The", "Manager APIs to return error details for failed operations. (This", "Operations metadata. :param id: The provider id. :type id: str", "self.display_name = display_name self.description = description self.origin = origin self.properties", "super(RoleAssignmentListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class RoleDefinition(msrest.serialization.Model):", "License. See License.txt in the project root for license information.", "name: Optional[str] = None, display_name: Optional[str] = None, description: Optional[str]", "'properties', 'type': 'object'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, } def", "} _attribute_map = { 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id':", "def __init__( self, **kwargs ): super(ErrorDetail, self).__init__(**kwargs) self.code = None", "_attribute_map = { 'value': {'key': 'value', 'type': '[RoleDefinition]'}, 'next_link': {'key':", "name: str :param display_name: The resource type display name. :type", "Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ResourceType, self).__init__(**kwargs) self.name = name", "to specify the operation type. :type is_data_action: bool \"\"\" _attribute_map", ":type is_data_action: bool \"\"\" _attribute_map = { 'name': {'key': 'name',", "'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'},", "= role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model):", ":type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role definition assignable scopes. :type", "class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management error additional info. Variables are", "str :param display_name: The resource type display name. :type display_name:", "self.can_delegate = can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter. :param principal_id:", "self, *, name: Optional[str] = None, display_name: Optional[str] = None,", "'type': 'str'}, } def __init__( self, *, value: Optional[List[\"RoleAssignment\"]] =", "The principal ID assigned to the role. This maps to", "self, *, value: Optional[List[\"RoleDefinition\"]] = None, next_link: Optional[str] = None,", ":vartype name: str :ivar type: The role assignment type. :vartype", "'type': 'bool'}, } def __init__( self, *, principal_id: Optional[str] =", "{'readonly': True}, 'additional_info': {'readonly': True}, } _attribute_map = { 'code':", "name: The role definition name. :vartype name: str :ivar type:", "role_name self.type = type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list operation", "\"\"\" _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDetail'}, }", "value: Optional[List[\"RoleDefinition\"]] = None, next_link: Optional[str] = None, **kwargs ):", "role_name: The role name. :type role_name: str :param description: The", "= value self.next_link = next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables", "definition name. :vartype name: str :ivar type: The role definition", "role_definition_id: The role definition ID. :type role_definition_id: str :param principal_id:", "= None self.additional_info = None class ErrorResponse(msrest.serialization.Model): \"\"\"Common error response", "'str'}, 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, 'can_delegate': {'key': 'properties.canDelegate', 'type':", "None, data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]] = None, **kwargs", "specify the operation type. :type is_data_action: bool \"\"\" _attribute_map =", "= None, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None,", ":type scope: str :param role_definition_id: The role definition ID. :type", "role_definition_id: str :param principal_id: Required. The principal ID assigned to", "None, **kwargs ): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value = value self.next_link =", "to the role. This maps to the ID inside the", "'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'},", "__init__( self, *, value: Optional[List[\"RoleAssignment\"]] = None, next_link: Optional[str] =", ":ivar info: The additional info. :vartype info: any \"\"\" _validation", "'info': {'readonly': True}, } _attribute_map = { 'type': {'key': 'type',", "Optional[List[str]] = None, **kwargs ): super(RoleDefinition, self).__init__(**kwargs) self.id = None", "**kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id = id self.name = name", "scopes. :type assignable_scopes: list[str] \"\"\" _validation = { 'id': {'readonly':", "None self.info = None class ErrorDetail(msrest.serialization.Model): \"\"\"The error detail. Variables", ":type type: str \"\"\" _attribute_map = { 'role_name': {'key': 'roleName',", "= None, display_name: Optional[str] = None, resource_types: Optional[List[\"ResourceType\"]] = None,", ":vartype target: str :ivar details: The error details. :vartype details:", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type',", "= None self.type = None self.scope = scope self.role_definition_id =", "origin: str :param properties: The operation properties. :type properties: any", "'type': {'key': 'type', 'type': 'str'}, 'info': {'key': 'info', 'type': 'object'},", "role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role", "principal ID assigned to the role. This maps to the", "self.name = None self.type = None self.role_name = role_name self.description", "in the role assignment. :type role_definition_id: str :param principal_id: Required.", "{'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'display_name':", "to return error details for failed operations. (This also follows", "__init__( self, *, error: Optional[\"ErrorDetail\"] = None, **kwargs ): super(ErrorResponse,", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The error additional info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo]", "of the specific principal. :type principal_id: str :param can_delegate: The", "Allowed actions. :type actions: list[str] :param not_actions: Denied actions. :type", "= None self.role_name = role_name self.description = description self.role_type =", "__init__( self, *, id: Optional[str] = None, name: Optional[str] =", "or security group. :type principal_id: str :param can_delegate: The delegation", "def __init__( self, *, value: Optional[List[\"Permission\"]] = None, next_link: Optional[str]", "info: The additional info. :vartype info: any \"\"\" _validation =", "self.role_name = role_name self.type = type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition", "str \"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[RoleDefinition]'},", "{ 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type':", "str :param role_name: The role name. :type role_name: str :param", "'type': {'key': 'type', 'type': 'str'}, 'role_name': {'key': 'properties.roleName', 'type': 'str'},", "_validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type':", "None class ErrorDetail(msrest.serialization.Model): \"\"\"The error detail. Variables are only populated", ":ivar additional_info: The error additional info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\"", "coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights", "'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'resource_types': {'key': 'resourceTypes',", "= None, display_name: Optional[str] = None, description: Optional[str] = None,", "} _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message':", "{'key': 'properties.principalId', 'type': 'str'}, 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, }", "'principalId', 'type': 'str'}, 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, } def", "'properties': {'key': 'properties', 'type': 'object'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'},", "= actions self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions =", "'properties.roleName', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'role_type': {'key':", "{ 'principal_id': {'key': 'principalId', 'type': 'str'}, 'can_delegate': {'key': 'canDelegate', 'type':", "Directory. It can point to a user, service principal, or", "error details for failed operations. (This also follows the OData", "under the MIT License. See License.txt in the project root", "'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs", "True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'},", "_attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key':", "None, is_data_action: Optional[bool] = None, **kwargs ): super(ProviderOperation, self).__init__(**kwargs) self.name", "class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables are only populated by the", "ID. :type role_definition_id: str :param principal_id: The principal ID. :type", "'error', 'type': 'ErrorDetail'}, } def __init__( self, *, error: Optional[\"ErrorDetail\"]", "Data actions. :type data_actions: list[str] :param not_data_actions: Denied Data actions.", "be ignored when sending a request. :ivar type: The additional", "list[str] \"\"\" _validation = { 'id': {'readonly': True}, 'name': {'readonly':", "'[Permission]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self,", "= None, **kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name = role_name self.type", "error object. :type error: ~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail \"\"\" _attribute_map = { 'error':", "= { 'type': {'key': 'type', 'type': 'str'}, 'info': {'key': 'info',", "user, service principal, or security group. :type principal_id: str :param", "str :param principal_id: Required. The principal ID assigned to the", "for the role assignment. :type can_delegate: bool \"\"\" _validation =", "{'key': 'roleName', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, }", "= { 'value': {'key': 'value', 'type': '[RoleAssignment]'}, 'next_link': {'key': 'nextLink',", ":vartype type: str :param role_name: The role name. :type role_name:", "type: Returns role definition with the specific type. :type type:", "specific type. :type type: str \"\"\" _attribute_map = { 'role_name':", "'[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, } def __init__( self,", "): super(PermissionGetResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class", "'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, 'is_data_action': {'key':", "None, origin: Optional[str] = None, properties: Optional[Any] = None, is_data_action:", ":ivar code: The error code. :vartype code: str :ivar message:", "name: str :param display_name: The operation display name. :type display_name:", "None self.scope = scope self.role_definition_id = role_definition_id self.principal_id = principal_id", "definition permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role definition assignable", "'type': '[str]'}, } def __init__( self, *, role_name: Optional[str] =", "display_name: Optional[str] = None, resource_types: Optional[List[\"ResourceType\"]] = None, operations: Optional[List[\"ProviderOperation\"]]", "None self.additional_info = None class ErrorResponse(msrest.serialization.Model): \"\"\"Common error response for", "__init__( self, *, scope: Optional[str] = None, role_definition_id: Optional[str] =", "\"\"\"Operation. :param name: The operation name. :type name: str :param", "resource type name. :type name: str :param display_name: The resource", "Optional[List[\"RoleAssignment\"]] = None, next_link: Optional[str] = None, **kwargs ): super(RoleAssignmentListResult,", "provider id. :type id: str :param name: The provider name.", "definition list operation result. :param value: Role definition list. :type", "{'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__( self, *, id:", ":param actions: Allowed actions. :type actions: list[str] :param not_actions: Denied", "not_data_actions: Optional[List[str]] = None, **kwargs ): super(Permission, self).__init__(**kwargs) self.actions =", "will be ignored when sending a request. :ivar id: The", "None, **kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id =", "additional_info: The error additional info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation", ":param operations: The resource type operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\"", "def __init__( self, *, role_definition_id: str, principal_id: str, can_delegate: Optional[bool]", "'displayName', 'type': 'str'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def", "'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key':", "description: Optional[str] = None, origin: Optional[str] = None, properties: Optional[Any]", "operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata list. :param value: The", "str :ivar details: The error details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The URL to use for getting the", "name: The operation name. :type name: str :param display_name: The", "actions. :type not_data_actions: list[str] \"\"\" _attribute_map = { 'actions': {'key':", "str :param principal_id: The principal ID. :type principal_id: str :param", "'str'}, 'properties': {'key': 'properties', 'type': 'object'}, 'is_data_action': {'key': 'isDataAction', 'type':", "assignable scopes. :type assignable_scopes: list[str] \"\"\" _validation = { 'id':", "**kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link", "not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions", "properties: any :param is_data_action: The dataAction flag to specify the", "None, **kwargs ): super(PermissionGetResult, self).__init__(**kwargs) self.value = value self.next_link =", "None, **kwargs ): super(RoleDefinition, self).__init__(**kwargs) self.id = None self.name =", "= origin self.properties = properties self.is_data_action = is_data_action class ProviderOperationsMetadata(msrest.serialization.Model):", "failed operations. (This also follows the OData error response format.).", "{'key': 'properties', 'type': 'object'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, }", "= None, role_definition_id: Optional[str] = None, principal_id: Optional[str] = None,", ":ivar target: The error target. :vartype target: str :ivar details:", "__init__( self, *, value: Optional[List[\"Permission\"]] = None, next_link: Optional[str] =", "= is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata. :param id: The", "RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list operation result. :param value: Role assignment", "None self.target = None self.details = None self.additional_info = None", "def __init__( self, *, actions: Optional[List[str]] = None, not_actions: Optional[List[str]]", "description: The role definition description. :type description: str :param role_type:", "not_actions: Denied actions. :type not_actions: list[str] :param data_actions: Allowed Data", "RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter. :param principal_id: Returns role assignment of", "self.next_link = next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param name: The", "operations metadata list. :param value: The list of providers. :type", "= None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs)", ":vartype info: any \"\"\" _validation = { 'type': {'readonly': True},", "self.type = type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role definition list operation result.", "= display_name self.operations = operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables", "= name self.display_name = display_name self.operations = operations class RoleAssignment(msrest.serialization.Model):", "principal_id: Returns role assignment of the specific principal. :type principal_id:", "name: The role assignment name. :vartype name: str :ivar type:", "self).__init__(**kwargs) self.value = value self.next_link = next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource", "'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorDetail]'}, 'additional_info': {'key':", ":type can_delegate: bool \"\"\" _validation = { 'role_definition_id': {'required': True},", "Optional[List[str]] = None, **kwargs ): super(Permission, self).__init__(**kwargs) self.actions = actions", "__init__( self, *, name: Optional[str] = None, display_name: Optional[str] =", "'str'}, 'can_delegate': {'key': 'canDelegate', 'type': 'bool'}, } def __init__( self,", "class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata list. :param value: The list", "data_actions self.not_data_actions = not_data_actions class PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param value:", "'roleName', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def", "'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List[\"ProviderOperationsMetadata\"]]", "is_data_action: Optional[bool] = None, **kwargs ): super(ProviderOperation, self).__init__(**kwargs) self.name =", "Optional[str] = None, role_type: Optional[str] = None, permissions: Optional[List[\"Permission\"]] =", "bool \"\"\" _validation = { 'id': {'readonly': True}, 'name': {'readonly':", "information. :param value: An array of permissions. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission]", "'value', 'type': '[Permission]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def", "} def __init__( self, *, scope: Optional[str] = None, role_definition_id:", "= None, data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]] = None,", ":param display_name: The resource type display name. :type display_name: str", ":param value: The list of providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param", "principal ID. :type principal_id: str :param can_delegate: The Delegation flag", "'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'},", "_attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'can_delegate': {'key':", "display name. :type display_name: str :param resource_types: The provider resource", "resource type display name. :type display_name: str :param operations: The", "PermissionGetResult(msrest.serialization.Model): \"\"\"Permissions information. :param value: An array of permissions. :type", "error details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The error additional", "'display_name': {'key': 'displayName', 'type': 'str'}, 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'},", "= None, description: Optional[str] = None, origin: Optional[str] = None,", "'type': '[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__(", "Optional[str] = None, **kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs) self.value = value", "__init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info", "None, properties: Optional[Any] = None, is_data_action: Optional[bool] = None, **kwargs", "{ 'type': {'readonly': True}, 'info': {'readonly': True}, } _attribute_map =", "role_name self.description = description self.role_type = role_type self.permissions = permissions", "(R) AutoRest Code Generator. # Changes may cause incorrect behavior", "'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(", "follows the OData error response format.). :param error: The error", "operation result. :param value: Role assignment list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleAssignment]", "azure.core.exceptions import HttpResponseError import msrest.serialization class ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management", "None, not_actions: Optional[List[str]] = None, data_actions: Optional[List[str]] = None, not_data_actions:", "'actions': {'key': 'actions', 'type': '[str]'}, 'not_actions': {'key': 'notActions', 'type': '[str]'},", ":param description: The role definition description. :type description: str :param", "str :param type: The provider type. :type type: str :param", "message: The error message. :vartype message: str :ivar target: The", "{'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, 'additional_info': {'readonly':", "\"\"\"Role definition. Variables are only populated by the server, and", "_validation = { 'type': {'readonly': True}, 'info': {'readonly': True}, }", "None self.name = None self.type = None self.role_name = role_name", "type: str :param display_name: The provider display name. :type display_name:", "resource types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The provider operations.", "None self.type = None self.role_name = role_name self.description = description", "self.error = error class Permission(msrest.serialization.Model): \"\"\"Role definition permissions. :param actions:", "list[str] :param data_actions: Allowed Data actions. :type data_actions: list[str] :param", "{'key': 'value', 'type': '[Permission]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, }", "= type self.display_name = display_name self.resource_types = resource_types self.operations =", "'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'},", ":type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The URL to use for", "-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", "self).__init__(**kwargs) self.name = name self.display_name = display_name self.description = description", "role_definition_id: str :param principal_id: The principal ID. :type principal_id: str", "None, **kwargs ): super(Permission, self).__init__(**kwargs) self.actions = actions self.not_actions =", "'str'}, 'origin': {'key': 'origin', 'type': 'str'}, 'properties': {'key': 'properties', 'type':", "self, *, value: Optional[List[\"RoleAssignment\"]] = None, next_link: Optional[str] = None,", "Denied actions. :type not_actions: list[str] :param data_actions: Allowed Data actions.", "\"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[str]'}, 'not_actions':", "definition description. :type description: str :param role_type: The role type.", "incorrect behavior and will be lost if the code is", "None, **kwargs ): super(ResourceType, self).__init__(**kwargs) self.name = name self.display_name =", "Azure. :param role_definition_id: Required. The role definition ID used in", "specific principal. :type principal_id: str :param can_delegate: The Delegation flag", "sending a request. :ivar id: The role definition ID. :vartype", "'type': 'str'}, 'resource_types': {'key': 'resourceTypes', 'type': '[ResourceType]'}, 'operations': {'key': 'operations',", "may cause incorrect behavior and will be lost if the", "{'key': 'details', 'type': '[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, }", "__init__( self, *, value: Optional[List[\"ProviderOperationsMetadata\"]] = None, next_link: Optional[str] =", "**kwargs ): super(ProviderOperation, self).__init__(**kwargs) self.name = name self.display_name = display_name", "str :param name: The provider name. :type name: str :param", "'type': '[RoleAssignment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(", "self.value = value self.next_link = next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition.", ":vartype name: str :ivar type: The role definition type. :vartype", "True}, 'details': {'readonly': True}, 'additional_info': {'readonly': True}, } _attribute_map =", "'type': {'key': 'type', 'type': 'str'}, } def __init__( self, *,", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The URL to use for getting the", "= None, **kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value = value self.next_link", ":type name: str :param display_name: The resource type display name.", "{ 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True},", "error: Optional[\"ErrorDetail\"] = None, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.error =", "\"\"\"Role definition list operation result. :param value: Role definition list.", "the project root for license information. # Code generated by", "class Permission(msrest.serialization.Model): \"\"\"Role definition permissions. :param actions: Allowed actions. :type", "self).__init__(**kwargs) self.id = id self.name = name self.type = type", "= None, role_type: Optional[str] = None, permissions: Optional[List[\"Permission\"]] = None,", "'type': 'bool'}, } def __init__( self, *, role_definition_id: str, principal_id:", "ignored when sending a request. :ivar code: The error code.", "str :ivar target: The error target. :vartype target: str :ivar", "definition with the specific type. :type type: str \"\"\" _attribute_map", "'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, }", "ErrorResponse(msrest.serialization.Model): \"\"\"Common error response for all Azure Resource Manager APIs", "the role assignment. :type can_delegate: bool \"\"\" _validation = {", "{'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id':", "the operation type. :type is_data_action: bool \"\"\" _attribute_map = {", "): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate", "**kwargs ): super(RoleAssignment, self).__init__(**kwargs) self.id = None self.name = None", "{'readonly': True}, } _attribute_map = { 'type': {'key': 'type', 'type':", "required parameters must be populated in order to send to", ":type name: str :param type: The provider type. :type type:", "'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'role_name': {'key': 'properties.roleName',", "'bool'}, } def __init__( self, *, scope: Optional[str] = None,", "assignment ID. :vartype id: str :ivar name: The role assignment", "'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'display_name': {'key': 'displayName',", ":type can_delegate: bool \"\"\" _attribute_map = { 'principal_id': {'key': 'principalId',", ":ivar type: The role assignment type. :vartype type: str :param", "Allowed Data actions. :type data_actions: list[str] :param not_data_actions: Denied Data", "{'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value:", "Optional[List[\"Permission\"]] = None, assignable_scopes: Optional[List[str]] = None, **kwargs ): super(RoleDefinition,", "\"\"\"The error detail. Variables are only populated by the server,", "flag used for creating a role assignment. :type can_delegate: bool", "id: str :param name: The provider name. :type name: str", "the role. This maps to the ID inside the Active", "**kwargs ): super(RoleDefinition, self).__init__(**kwargs) self.id = None self.name = None", ":vartype type: str :param scope: The role assignment scope. :type", "dataAction flag to specify the operation type. :type is_data_action: bool", "actions self.not_actions = not_actions self.data_actions = data_actions self.not_data_actions = not_data_actions", "to send to Azure. :param role_definition_id: Required. The role definition", "self).__init__(**kwargs) self.error = error class Permission(msrest.serialization.Model): \"\"\"Role definition permissions. :param", ":type role_name: str :param description: The role definition description. :type", "type: Optional[str] = None, display_name: Optional[str] = None, resource_types: Optional[List[\"ResourceType\"]]", "definition assignable scopes. :type assignable_scopes: list[str] \"\"\" _validation = {", "assigned to the role. This maps to the ID inside", "{'key': 'notDataActions', 'type': '[str]'}, } def __init__( self, *, actions:", "Optional[\"ErrorDetail\"] = None, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.error = error", "a request. :ivar code: The error code. :vartype code: str", "assignment. :type can_delegate: bool \"\"\" _attribute_map = { 'principal_id': {'key':", "the MIT License. See License.txt in the project root for", "role assignment of the specific principal. :type principal_id: str :param", "can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignment, self).__init__(**kwargs) self.id =", "Returns role assignment of the specific principal. :type principal_id: str", "def __init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None", "principal, or security group. :type principal_id: str :param can_delegate: The", "Optional[str] = None, display_name: Optional[str] = None, description: Optional[str] =", "display name. :type display_name: str :param description: The operation description.", "'properties.assignableScopes', 'type': '[str]'}, } def __init__( self, *, role_name: Optional[str]", "**kwargs ): super(ErrorDetail, self).__init__(**kwargs) self.code = None self.message = None", "actions: Optional[List[str]] = None, not_actions: Optional[List[str]] = None, data_actions: Optional[List[str]]", "any \"\"\" _validation = { 'type': {'readonly': True}, 'info': {'readonly':", "Assignments. Variables are only populated by the server, and will", "'operations', 'type': '[ProviderOperation]'}, } def __init__( self, *, name: Optional[str]", "The provider id. :type id: str :param name: The provider", "'properties.canDelegate', 'type': 'bool'}, } def __init__( self, *, scope: Optional[str]", ":ivar message: The error message. :vartype message: str :ivar target:", ":type display_name: str :param operations: The resource type operations. :type", "= principal_id self.can_delegate = can_delegate class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list", "display_name self.description = description self.origin = origin self.properties = properties", "self.value = value self.next_link = next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource Type.", "{'key': 'properties.canDelegate', 'type': 'bool'}, } def __init__( self, *, scope:", "is_data_action: The dataAction flag to specify the operation type. :type", "_validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target':", "'str'}, 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId', 'type':", "'str'}, 'info': {'key': 'info', 'type': 'object'}, } def __init__( self,", "def __init__( self, *, name: Optional[str] = None, display_name: Optional[str]", "'notActions', 'type': '[str]'}, 'data_actions': {'key': 'dataActions', 'type': '[str]'}, 'not_data_actions': {'key':", "The role definition name. :vartype name: str :ivar type: The", "'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id',", "{'key': 'properties.roleName', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'role_type':", "bool \"\"\" _attribute_map = { 'name': {'key': 'name', 'type': 'str'},", ":param operations: The provider operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map", "specific name. :type role_name: str :param type: Returns role definition", "when sending a request. :ivar code: The error code. :vartype", "= next_link class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name: The operation name.", "value: Role definition list. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The", "additional info. Variables are only populated by the server, and", ":type role_definition_id: str :param principal_id: The principal ID. :type principal_id:", "# Licensed under the MIT License. See License.txt in the", "= { 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId',", "description self.origin = origin self.properties = properties self.is_data_action = is_data_action", "{'key': 'displayName', 'type': 'str'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, }", "= None, **kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id = id self.name", "'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(", "self.description = description self.origin = origin self.properties = properties self.is_data_action", "properties. :type properties: any :param is_data_action: The dataAction flag to", "Optional[str] = None, resource_types: Optional[List[\"ResourceType\"]] = None, operations: Optional[List[\"ProviderOperation\"]] =", "display_name self.operations = operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables are", "It can point to a user, service principal, or security", "str \"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[RoleAssignment]'},", "= { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message',", "provider type. :type type: str :param display_name: The provider display", "'str'}, 'role_name': {'key': 'properties.roleName', 'type': 'str'}, 'description': {'key': 'properties.description', 'type':", "ErrorAdditionalInfo(msrest.serialization.Model): \"\"\"The resource management error additional info. Variables are only", "list. :param value: The list of providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata]", "def __init__( self, *, value: Optional[List[\"RoleAssignment\"]] = None, next_link: Optional[str]", ":type display_name: str :param resource_types: The provider resource types. :type", "str :ivar type: The role assignment type. :vartype type: str", "code: str :ivar message: The error message. :vartype message: str", "self).__init__(**kwargs) self.id = None self.name = None self.type = None", "Denied Data actions. :type not_data_actions: list[str] \"\"\" _attribute_map = {", "cause incorrect behavior and will be lost if the code", "(c) Microsoft Corporation. All rights reserved. # Licensed under the", "self.role_type = role_type self.permissions = permissions self.assignable_scopes = assignable_scopes class", "self.can_delegate = can_delegate class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create parameters. All", "'type': 'str'}, } def __init__( self, *, value: Optional[List[\"ProviderOperationsMetadata\"]] =", "{ 'role_name': {'key': 'roleName', 'type': 'str'}, 'type': {'key': 'type', 'type':", "'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type':", "metadata list. :param value: The list of providers. :type value:", "class ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param name: The resource type name.", "scope: Optional[str] = None, role_definition_id: Optional[str] = None, principal_id: Optional[str]", "'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorDetail]'}, 'additional_info': {'key': 'additionalInfo',", "self.operations = operations class RoleAssignment(msrest.serialization.Model): \"\"\"Role Assignments. Variables are only", ":param description: The operation description. :type description: str :param origin:", "# Code generated by Microsoft (R) AutoRest Code Generator. #", "'type': 'str'}, 'role_type': {'key': 'properties.type', 'type': 'str'}, 'permissions': {'key': 'properties.permissions',", "'type': '[str]'}, 'not_actions': {'key': 'notActions', 'type': '[str]'}, 'data_actions': {'key': 'dataActions',", "metadata. :param id: The provider id. :type id: str :param", "name. :type display_name: str :param resource_types: The provider resource types.", "'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorDetail]'},", "class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata. :param id: The provider id.", "'properties.roleDefinitionId', 'type': 'str'}, 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, 'can_delegate': {'key':", "principal_id: str :param can_delegate: The Delegation flag for the role", "management error additional info. Variables are only populated by the", "This maps to the ID inside the Active Directory. It", "'type', 'type': 'str'}, 'role_name': {'key': 'properties.roleName', 'type': 'str'}, 'description': {'key':", ":param is_data_action: The dataAction flag to specify the operation type.", "self.operations = operations class ProviderOperationsMetadataListResult(msrest.serialization.Model): \"\"\"Provider operations metadata list. :param", "next_link: Optional[str] = None, **kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value =", "{'readonly': True}, 'details': {'readonly': True}, 'additional_info': {'readonly': True}, } _attribute_map", "info. :vartype additional_info: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorAdditionalInfo] \"\"\" _validation = { 'code': {'readonly':", ":param resource_types: The provider resource types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param", "self.name = name self.type = type self.display_name = display_name self.resource_types", "'[RoleDefinition]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self,", "be ignored when sending a request. :ivar id: The role", "'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, } def", "= role_type self.permissions = permissions self.assignable_scopes = assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model):", "role definition name. :vartype name: str :ivar type: The role", "'value', 'type': '[RoleDefinition]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def", "= None, **kwargs ): super(Permission, self).__init__(**kwargs) self.actions = actions self.not_actions", "= None, origin: Optional[str] = None, properties: Optional[Any] = None,", "= { 'value': {'key': 'value', 'type': '[RoleDefinition]'}, 'next_link': {'key': 'nextLink',", "Optional[str] = None, name: Optional[str] = None, type: Optional[str] =", "self.next_link = next_link class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables are only", "True}, } _attribute_map = { 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'},", "{'key': 'actions', 'type': '[str]'}, 'not_actions': {'key': 'notActions', 'type': '[str]'}, 'data_actions':", "'properties.principalId', 'type': 'str'}, 'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, } def", ":param properties: The operation properties. :type properties: any :param is_data_action:", "self.type = None self.scope = scope self.role_definition_id = role_definition_id self.principal_id", "= scope self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate =", "the code is regenerated. # -------------------------------------------------------------------------- from typing import Any,", "permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role definition assignable scopes.", "'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink', 'type': 'str'},", "__init__( self, **kwargs ): super(ErrorDetail, self).__init__(**kwargs) self.code = None self.message", "not_actions: Optional[List[str]] = None, data_actions: Optional[List[str]] = None, not_data_actions: Optional[List[str]]", "value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.RoleDefinition] :param next_link: The URL to use for getting", "and will be ignored when sending a request. :ivar id:", ":param not_data_actions: Denied Data actions. :type not_data_actions: list[str] \"\"\" _attribute_map", "= { 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'}, 'next_link': {'key': 'nextLink',", "permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role definition assignable scopes. :type assignable_scopes:", "sending a request. :ivar code: The error code. :vartype code:", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignment,", "role_type: str :param permissions: Role definition permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission]", "class RoleAssignmentListResult(msrest.serialization.Model): \"\"\"Role assignment list operation result. :param value: Role", "'type': 'str'}, } def __init__( self, *, value: Optional[List[\"Permission\"]] =", "= None self.name = None self.type = None self.role_name =", "origin self.properties = properties self.is_data_action = is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider", "point to a user, service principal, or security group. :type", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param next_link: The URL to use for getting the", ":ivar id: The role definition ID. :vartype id: str :ivar", "super(Permission, self).__init__(**kwargs) self.actions = actions self.not_actions = not_actions self.data_actions =", "value: Optional[List[\"RoleAssignment\"]] = None, next_link: Optional[str] = None, **kwargs ):", "= { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name',", "Corporation. All rights reserved. # Licensed under the MIT License.", "'str'}, 'type': {'key': 'type', 'type': 'str'}, 'role_name': {'key': 'properties.roleName', 'type':", ":param not_actions: Denied actions. :type not_actions: list[str] :param data_actions: Allowed", "resource type operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = {", "error message. :vartype message: str :ivar target: The error target.", "**kwargs ): super(RoleDefinitionFilter, self).__init__(**kwargs) self.role_name = role_name self.type = type", "for all Azure Resource Manager APIs to return error details", "The operation display name. :type display_name: str :param description: The", "RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create parameters. All required parameters must be", "project root for license information. # Code generated by Microsoft", "group. :type principal_id: str :param can_delegate: The delegation flag used", "flag to specify the operation type. :type is_data_action: bool \"\"\"", "The role definition ID used in the role assignment. :type", "\"\"\" _validation = { 'type': {'readonly': True}, 'info': {'readonly': True},", "operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'id': {'key':", "self, *, error: Optional[\"ErrorDetail\"] = None, **kwargs ): super(ErrorResponse, self).__init__(**kwargs)", "code. :vartype code: str :ivar message: The error message. :vartype", "{'key': 'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, }", "assignment create parameters. All required parameters must be populated in", "error additional info. Variables are only populated by the server,", "'str'}, 'type': {'key': 'type', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type':", "operations: The provider operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map =", "for creating a role assignment. :type can_delegate: bool \"\"\" _validation", "= None, **kwargs ): super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id", "self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments", "str :param origin: The operation origin. :type origin: str :param", "name: The provider name. :type name: str :param type: The", "'str'}, } def __init__( self, *, value: Optional[List[\"ProviderOperationsMetadata\"]] = None,", "= None, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignment, self).__init__(**kwargs)", "'role_name': {'key': 'roleName', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'},", ":type next_link: str \"\"\" _attribute_map = { 'value': {'key': 'value',", "description: Optional[str] = None, role_type: Optional[str] = None, permissions: Optional[List[\"Permission\"]]", "str :param scope: The role assignment scope. :type scope: str", "type: str :param role_name: The role name. :type role_name: str", "'str'}, } def __init__( self, *, value: Optional[List[\"RoleAssignment\"]] = None,", "class RoleDefinition(msrest.serialization.Model): \"\"\"Role definition. Variables are only populated by the", "'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target',", "= role_definition_id self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentFilter(msrest.serialization.Model):", "sending a request. :ivar id: The role assignment ID. :vartype", "assignable_scopes class RoleDefinitionFilter(msrest.serialization.Model): \"\"\"Role Definitions filter. :param role_name: Returns role", "a request. :ivar id: The role assignment ID. :vartype id:", "The resource type operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map =", "-------------------------------------------------------------------------- from typing import Any, List, Optional from azure.core.exceptions import", "principal_id self.can_delegate = can_delegate class RoleAssignmentFilter(msrest.serialization.Model): \"\"\"Role Assignments filter. :param", "{ 'error': {'key': 'error', 'type': 'ErrorDetail'}, } def __init__( self,", "'dataActions', 'type': '[str]'}, 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, } def", "details: The error details. :vartype details: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ErrorDetail] :ivar additional_info: The", "properties: The operation properties. :type properties: any :param is_data_action: The", "= { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'can_delegate': {'key': 'canDelegate',", "display_name: str :param description: The operation description. :type description: str", "'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'operations': {'key': 'operations',", "type. :type is_data_action: bool \"\"\" _attribute_map = { 'name': {'key':", "super(ErrorResponse, self).__init__(**kwargs) self.error = error class Permission(msrest.serialization.Model): \"\"\"Role definition permissions.", "self).__init__(**kwargs) self.role_name = role_name self.type = type class RoleDefinitionListResult(msrest.serialization.Model): \"\"\"Role", "class RoleAssignmentCreateParameters(msrest.serialization.Model): \"\"\"Role assignment create parameters. All required parameters must", "resource_types: Optional[List[\"ResourceType\"]] = None, operations: Optional[List[\"ProviderOperation\"]] = None, **kwargs ):", "} def __init__( self, *, value: Optional[List[\"Permission\"]] = None, next_link:", "License.txt in the project root for license information. # Code", "class ProviderOperation(msrest.serialization.Model): \"\"\"Operation. :param name: The operation name. :type name:", "None, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignment, self).__init__(**kwargs) self.id", "'type': '[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs ): super(ErrorDetail, self).__init__(**kwargs)", "str, principal_id: str, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentCreateParameters,", "Generator. # Changes may cause incorrect behavior and will be", "type self.display_name = display_name self.resource_types = resource_types self.operations = operations", "next_link: Optional[str] = None, **kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs) self.value =", "): super(RoleAssignmentListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class", "will be lost if the code is regenerated. # --------------------------------------------------------------------------", ":param principal_id: Required. The principal ID assigned to the role.", ":ivar type: The role definition type. :vartype type: str :param", "): super(ErrorResponse, self).__init__(**kwargs) self.error = error class Permission(msrest.serialization.Model): \"\"\"Role definition", "The provider operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = {", "None, **kwargs ): super(RoleDefinitionListResult, self).__init__(**kwargs) self.value = value self.next_link =", "provider resource types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations: The provider", "'can_delegate': {'key': 'properties.canDelegate', 'type': 'bool'}, } def __init__( self, *,", "and will be lost if the code is regenerated. #", "'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'operations': {'key': 'operations', 'type':", "super(RoleAssignmentFilter, self).__init__(**kwargs) self.principal_id = principal_id self.can_delegate = can_delegate class RoleAssignmentListResult(msrest.serialization.Model):", "self.id = id self.name = name self.type = type self.display_name", "definition with the specific name. :type role_name: str :param type:", "id: Optional[str] = None, name: Optional[str] = None, type: Optional[str]", "reserved. # Licensed under the MIT License. See License.txt in", "next_link class ResourceType(msrest.serialization.Model): \"\"\"Resource Type. :param name: The resource type", "actions. :type data_actions: list[str] :param not_data_actions: Denied Data actions. :type", "are only populated by the server, and will be ignored", "{'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type':", "\"\"\"Role Assignments filter. :param principal_id: Returns role assignment of the", "'error': {'key': 'error', 'type': 'ErrorDetail'}, } def __init__( self, *,", "True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map =", "__init__( self, *, principal_id: Optional[str] = None, can_delegate: Optional[bool] =", "Resource Manager APIs to return error details for failed operations.", "\"\"\"Role assignment list operation result. :param value: Role assignment list.", "super(RoleAssignmentCreateParameters, self).__init__(**kwargs) self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate =", "display name. :type display_name: str :param operations: The resource type", "The role type. :type role_type: str :param permissions: Role definition", "None, next_link: Optional[str] = None, **kwargs ): super(ProviderOperationsMetadataListResult, self).__init__(**kwargs) self.value", "str :ivar message: The error message. :vartype message: str :ivar", "operations. :type operations: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperation] \"\"\" _attribute_map = { 'name': {'key':", "operation name. :type name: str :param display_name: The operation display", "The operation origin. :type origin: str :param properties: The operation", ":param permissions: Role definition permissions. :type permissions: list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes:", "'bool'}, } def __init__( self, *, role_definition_id: str, principal_id: str,", "self.role_name = role_name self.description = description self.role_type = role_type self.permissions", "'value', 'type': '[RoleAssignment]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def", "'type': 'bool'}, } def __init__( self, *, scope: Optional[str] =", "'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'origin': {'key': 'origin',", "super(ResourceType, self).__init__(**kwargs) self.name = name self.display_name = display_name self.operations =", "{'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'scope':", "id: str :ivar name: The role assignment name. :vartype name:", "list[~azure.mgmt.authorization.v2018_01_01_preview.models.Permission] :param assignable_scopes: Role definition assignable scopes. :type assignable_scopes: list[str]", "error detail. Variables are only populated by the server, and", ":param type: The provider type. :type type: str :param display_name:", "): super(ErrorDetail, self).__init__(**kwargs) self.code = None self.message = None self.target", "'properties.type', 'type': 'str'}, 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, 'assignable_scopes': {'key':", "be ignored when sending a request. :ivar code: The error", "name self.type = type self.display_name = display_name self.resource_types = resource_types", "self, *, principal_id: Optional[str] = None, can_delegate: Optional[bool] = None,", "ignored when sending a request. :ivar id: The role definition", "'[ResourceType]'}, 'operations': {'key': 'operations', 'type': '[ProviderOperation]'}, } def __init__( self,", "self).__init__(**kwargs) self.actions = actions self.not_actions = not_actions self.data_actions = data_actions", "and will be ignored when sending a request. :ivar code:", "self.scope = scope self.role_definition_id = role_definition_id self.principal_id = principal_id self.can_delegate", "resource_types: The provider resource types. :type resource_types: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ResourceType] :param operations:", "populated in order to send to Azure. :param role_definition_id: Required.", "} def __init__( self, *, name: Optional[str] = None, display_name:", "str :ivar name: The role assignment name. :vartype name: str", "str \"\"\" _attribute_map = { 'value': {'key': 'value', 'type': '[ProviderOperationsMetadata]'},", "Optional[str] = None, can_delegate: Optional[bool] = None, **kwargs ): super(RoleAssignmentFilter,", "Optional[List[\"ProviderOperation\"]] = None, **kwargs ): super(ProviderOperationsMetadata, self).__init__(**kwargs) self.id = id", "role type. :type role_type: str :param permissions: Role definition permissions.", "= { 'role_name': {'key': 'roleName', 'type': 'str'}, 'type': {'key': 'type',", "rights reserved. # Licensed under the MIT License. See License.txt", "type: The role definition type. :vartype type: str :param role_name:", "# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All", "self.id = None self.name = None self.type = None self.scope", "The URL to use for getting the next set of", "list of providers. :type value: list[~azure.mgmt.authorization.v2018_01_01_preview.models.ProviderOperationsMetadata] :param next_link: The URL", "= properties self.is_data_action = is_data_action class ProviderOperationsMetadata(msrest.serialization.Model): \"\"\"Provider Operations metadata.", "'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'description': {'key': 'description', 'type':", "{'key': 'type', 'type': 'str'}, 'scope': {'key': 'properties.scope', 'type': 'str'}, 'role_definition_id':", "be populated in order to send to Azure. :param role_definition_id:", ":param principal_id: Returns role assignment of the specific principal. :type", "assignable_scopes: list[str] \"\"\" _validation = { 'id': {'readonly': True}, 'name':", "'properties.description', 'type': 'str'}, 'role_type': {'key': 'properties.type', 'type': 'str'}, 'permissions': {'key':", "{'key': 'type', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'resource_types':", "can_delegate: bool \"\"\" _attribute_map = { 'principal_id': {'key': 'principalId', 'type':", "{'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target':", "__init__( self, *, role_name: Optional[str] = None, description: Optional[str] =", "The role assignment ID. :vartype id: str :ivar name: The" ]
[ "TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all()", "if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for", "render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return", "contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def aboutus_view(request): return render(request,'school/aboutus.html') def contactus_view(request):", "if accountapproval: return redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html') #for dashboard of", "return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if", "return render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid():", "#for showing signup/login button for teacher(by sumit) def teacherclick_view(request): if", "user.delete() teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id)", "invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST':", "form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date", "request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>)", "form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN", "admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status')", "adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "return render(request,'school/teacherclick.html') #for showing signup/login button for student(by sumit) def", "students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date']", "@user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date']", "and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group =", "'date':teacherdata[0].joindate, 'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request): return", "viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST)", "@user_passes_test(is_teacher) def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl)", "showing signup/login button for teacher(by sumit) def teacherclick_view(request): if request.user.is_authenticated:", "return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST)", "ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def aboutus_view(request): return render(request,'school/aboutus.html') def contactus_view(request): sub", "return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for", "for student(by sumit) def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return", "f2.save() return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all()", "form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid():", "@user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "def is_teacher(user): return user.groups.filter(name='TEACHER').exists() def is_student(user): return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request):", "def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk)", "is invalid\") return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request):", "admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm()", "form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else:", "if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form", "form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else:", "f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher')", "aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def aboutus_view(request): return render(request,'school/aboutus.html')", "mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save()", "HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for showing signup/login button for teacher(by sumit)", "sumit) def teacherclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for", "@user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "f2.user=user f2.status=True f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form is", "@user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin')", "or admin(by sumit) def is_admin(user): return user.groups.filter(name='ADMIN').exists() def is_teacher(user): return", "return HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for showing signup/login button for teacher(by", "and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def aboutus_view(request): return render(request,'school/aboutus.html') def", "studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm()", "form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and", "for teacher(by sumit) def adminclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return", "#aggregate function return dictionary so fetch data from dictionay(by sumit)", "teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date']", "form.by=request.user.first_name form.save() return redirect('teacher-dashboard') else: print('form invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST)", "return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if", "else: print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm()", "form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid()", "is_student(user): return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if is_admin(request.user): return redirect('admin-dashboard') elif", "invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin')", "studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin')", "f2.save() return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False)", "mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher)", "mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice } return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student)", "form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-student') return", "@user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice", "teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete()", "elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html')", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('teacher-dashboard')", "form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group", "print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if", "render(request,'school/student_wait_for_approval.html') #for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request):", "sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently = False) return", "for aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def aboutus_view(request): return", "render(request,'school/index.html') #for showing signup/login button for teacher(by sumit) def adminclick_view(request):", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request):", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid():", "for teacher(by sumit) def teacherclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return", "redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return", "def admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm()", "Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for checking user is", "sumit) def aboutus_view(request): return render(request,'school/aboutus.html') def contactus_view(request): sub = forms.ContactusForm()", "teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete()", "return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return", "redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return", "@user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date']", "form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False)", "def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee'))", "return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher)", "and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-student')", "redirect('teacher-dashboard') else: print('form invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER THEIR", "def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice }", "student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk):", "@login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate,", "request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for showing signup/login button for", "adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count()", "if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True", "else: print(\"form is invalid\") return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER", "sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile,", "'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict) #for", "return render(request,'school/adminclick.html') #for showing signup/login button for teacher(by sumit) def", "so fetch data from dictionay(by sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount,", "from django.contrib.auth.decorators import login_required,user_passes_test def home_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin')", "f2.status=True f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict)", "@user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin')", "render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form", "if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('admin-dashboard')", "HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST':", "redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('teacher-dashboard') else: return", "sub = forms.ContactusForm(request.POST) if sub.is_valid(): email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin')", "request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for showing signup/login button for", "return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request):", "admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "#FOR STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request):", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if", "form.save() return redirect('teacher-dashboard') else: print('form invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT", "Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm()", "# for aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def aboutus_view(request):", "render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST)", "return render(request,'school/teachersignup.html',context=mydict) #for checking user is techer , student or", "f2.user=user user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict)", "techer , student or admin(by sumit) def is_admin(user): return user.groups.filter(name='ADMIN').exists()", "pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function", "return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher)", "student(by sumit) def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html')", "return dictionary so fetch data from dictionay(by sumit) mydict={ 'teachercount':teachercount,", "user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user)", "sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request): return render(request,'school/admin_teacher.html')", "user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user)", "'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice }", "def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl)", "render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit) def", "from django.contrib.auth.models import Group from django.http import HttpResponseRedirect from django.contrib.auth.decorators", "|| '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently = False) return render(request, 'school/contactussuccess.html')", "teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk)", "#notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm() if", "= Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm()", "students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student", "Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm()", "student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user)", "redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related", "if form1.is_valid() and form2.is_valid(): print(\"form is valid\") user=form1.save() user.set_password(<PASSWORD>) user.save()", "'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def", "form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False)", "def afterlogin_view(request): if is_admin(request.user): return redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if", "mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid() and form2.is_valid():", "f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form is invalid\") return", "return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin')", "form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata)", "if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save()", "if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): print(\"form is", "return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return", "mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid() and form2.is_valid():", "@user_passes_test(is_admin) def admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm()", "user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else:", "#for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id)", "= sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER,", "signup/login button for teacher(by sumit) def teacherclick_view(request): if request.user.is_authenticated: return", "if is_admin(request.user): return redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return", "teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate", "admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True", "AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance') else: print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform})", "SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary,", "def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk)", "adminclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for showing signup/login", "from django.shortcuts import render,redirect,reverse from . import forms,models from django.db.models", "print(\"form is valid\") user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save()", "def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin')", "AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance') else: print('form", "admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl})", "f2.status=True f2.save() return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request):", "my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form is invalid\") return HttpResponseRedirect('admin-student')", "print(students) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for", "return redirect('teacher-attendance') else: print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def", "@user_passes_test(is_admin) def admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl)", "if request.method == 'POST': sub = forms.ContactusForm(request.POST) if sub.is_valid(): email", "return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if", "import login_required,user_passes_test def home_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/index.html')", "return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student)", "user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER')", "pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function return dictionary so fetch", "@user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk):", "#for showing signup/login button for teacher(by sumit) def adminclick_view(request): if", "studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee", "fetch data from dictionay(by sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount,", "def teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name", "forms,models from django.db.models import Sum from django.contrib.auth.models import Group from", "form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save()", "def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if", "redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2}", "@user_passes_test(is_admin) def admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm()", "return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for checking user is techer ,", "Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i]", "@user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin')", "pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function return dictionary", "@user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice", "approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk):", "'POST': sub = forms.ContactusForm(request.POST) if sub.is_valid(): email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name']", "return redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('teacher-dashboard') else:", "@user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date']", "django.db.models import Sum from django.contrib.auth.models import Group from django.http import", "print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit)", "dictionary so fetch data from dictionay(by sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount,", "render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related", "form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('teacher-dashboard') else: print('form invalid') return", "fail_silently = False) return render(request, 'school/contactussuccess.html') return render(request, 'school/contactus.html', {'form':sub})", "is_admin(user): return user.groups.filter(name='ADMIN').exists() def is_teacher(user): return user.groups.filter(name='TEACHER').exists() def is_student(user): return", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by", "user.delete() student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id)", "form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata)", "mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher)", "form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user)", "user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk)", "django.contrib.auth.decorators import login_required,user_passes_test def home_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return", "else: print('form invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by", "of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count()", "admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid()", "print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if", "user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user)", "redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return", "from django.db.models import Sum from django.contrib.auth.models import Group from django.http", "def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice }", "else: print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm()", "form2.is_valid(): print(\"form is valid\") user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True", "signup/login button for student(by sumit) def studentclick_view(request): if request.user.is_authenticated: return", "form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group", "return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit)", "user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if", "my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for checking user is techer", "#for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count()", "user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict)", "student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk):", "teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice } return", "@login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl):", "student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete()", "form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid() and", "return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST)", "THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={", "render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST)", "@user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit)", "def admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin')", "if form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return", "return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice", "form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-teacher') return", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-approve-student')", "dictionay(by sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'],", "print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True", "my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2}", "user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "def aboutus_view(request): return render(request,'school/aboutus.html') def contactus_view(request): sub = forms.ContactusForm() if", "f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice } return render(request,'school/student_dashboard.html',context=mydict)", "f2.user=user user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict)", "return render(request,'school/student_wait_for_approval.html') #for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "render(request,'school/teacherclick.html') #for showing signup/login button for student(by sumit) def studentclick_view(request):", "delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "function return dictionary so fetch data from dictionay(by sumit) mydict={", "f2.user=user f2.status=True f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return", "print(\"form is invalid\") return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "'notice':notice } return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm() if", "if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save()", "valid\") user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_student_group =", "redirect('admin-attendance') else: print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl):", "accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user):", "user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return", "form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid')", "forms.ContactusForm() if request.method == 'POST': sub = forms.ContactusForm(request.POST) if sub.is_valid():", "aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i", "email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message,", "teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers})", "return redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html') #for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit)", "form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False)", "user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT')", "return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST)", "STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id)", "update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student)", "form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid()", "view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request): return render(request,'school/admin_fee.html')", "@user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST':", "return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete()", "'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict) #for teacher", "return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by sumit)", "accountapproval: return redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html') #for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by", "'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return", "def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False)", "delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk)", "@user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit)", "render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request): return", "AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance') else: print('form invalid')", "f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin')", "render(request,'school/aboutus.html') def contactus_view(request): sub = forms.ContactusForm() if request.method == 'POST':", "request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save()", "user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def", "form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('teacher-dashboard') else: print('form invalid') return render(request,'school/teacher_notice.html',{'form':form})", "AttendanceModel.save() return redirect('teacher-attendance') else: print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher)", "return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST)", "@user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if", "studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form})", "home_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for showing signup/login", "def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if", "return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST':", "@user_passes_test(is_admin) def admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl)", "teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if", "render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus and", "form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): print(\"form is valid\") user=form1.save() user.set_password(<PASSWORD>)", "EMAIL_HOST_USER, ['<EMAIL>'], fail_silently = False) return render(request, 'school/contactussuccess.html') return render(request,", "my_student_group[0].user_set.add(user) else: print(\"form is invalid\") return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin')", "render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def", "render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request):", "render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm()", "user.groups.filter(name='TEACHER').exists() def is_student(user): return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if is_admin(request.user): return", "HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST':", "return user.groups.filter(name='TEACHER').exists() def is_student(user): return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if is_admin(request.user):", "if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save()", "sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return", "@login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee,", "if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('teacher-dashboard') else: print('form invalid')", "my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2}", "print('form invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit)", "LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request): teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={", "sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile,", "attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form})", "request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): print(\"form is valid\")", "sumit) def is_admin(user): return user.groups.filter(name='ADMIN').exists() def is_teacher(user): return user.groups.filter(name='TEACHER').exists() def", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-approve-teacher')", "i in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return", "@user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin')", "student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll)", "sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if", "form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save()", "return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return", "'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request):", "range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance') else:", "form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i in range(len(Attendances)): AttendanceModel=models.Attendance()", "form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid')", "and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-teacher')", "if request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group =", "Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request):", "else: print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus and contact", "'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html')", "students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save()", "def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if", "mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related", "admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True", "return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin')", "['<EMAIL>'], fail_silently = False) return render(request, 'school/contactussuccess.html') return render(request, 'school/contactus.html',", "is_admin(request.user): return redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('teacher-dashboard')", "adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin')", "admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid()", "@user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0))", "@user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk):", "render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher'))", "and form2.is_valid(): print(\"form is valid\") user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user", "invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST':", "return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for showing signup/login button for student(by", "afterlogin_view(request): if is_admin(request.user): return redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval:", "admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save()", "admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin')", "#for teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request):", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid():", "sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'],", "<filename>school/views.py from django.shortcuts import render,redirect,reverse from . import forms,models from", "accountapproval: return redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if", "render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request):", "def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students})", "user.set_password(<PASSWORD>) user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form})", "redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher)", "return render(request,'school/index.html') #for showing signup/login button for teacher(by sumit) def", "form.save() return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit)", "if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for showing signup/login button", "by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin')", "teacher(by sumit) def adminclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html')", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST)", "form1.is_valid() and form2.is_valid(): print(\"form is valid\") user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False)", "form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid() and", "render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "def student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if", "else: return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('student-dashboard')", "render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST)", "form2=forms.StudentExtraForm(request.POST,instance=student) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False)", "(by sumit) def aboutus_view(request): return render(request,'school/aboutus.html') def contactus_view(request): sub =", "return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST)", "elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html')", "and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_teacher_group", "HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for checking user is techer , student", "attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) #", "sumit) def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def", "redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return", "AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance') else: print('form", "render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST':", "user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if is_admin(request.user): return redirect('admin-dashboard') elif is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True)", "@user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False)", "by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin')", "my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request):", "form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return", "def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form", "user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return", "return redirect('teacher-dashboard') else: print('form invalid') return render(request,'school/teacher_notice.html',{'form':form}) #FOR STUDENT AFTER", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user)", "viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2}", "user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk)", "= Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for checking user", "form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT')", "from dictionay(by sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'],", "import Group from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test", "student_signup_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid()", "def admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name", "update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher)", "teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk):", "if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return", "mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): print(\"form", "@login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid():", "return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request):", "render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST':", "range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance') else:", "request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date})", "aboutus_view(request): return render(request,'school/aboutus.html') def contactus_view(request): sub = forms.ContactusForm() if request.method", "render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if", "'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn by", "@user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request):", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-view-student')", "HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST) if", "invalid\") return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True)", "related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin')", "my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for checking", "'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by", "return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html') #for dashboard", "def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "def home_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for showing", "return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete()", "render(request,'school/teachersignup.html',context=mydict) #for checking user is techer , student or admin(by", "admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2}", "notice=models.Notice.objects.all() #aggregate function return dictionary so fetch data from dictionay(by", "form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and form2.is_valid():", "render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('student-dashboard') else: return", "attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form})", "AttendanceModel.save() return redirect('admin-attendance') else: print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid')", "'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice } return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def", "HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test def home_view(request): if request.user.is_authenticated: return", "admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save()", "my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True)", "teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function return dictionary so", "@user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk):", "message = sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently =", "django.contrib.auth.models import Group from django.http import HttpResponseRedirect from django.contrib.auth.decorators import", "request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>)", "data from dictionay(by sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'],", "form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER')", "def admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm()", "} return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin')", "user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict)", "def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_notice_view(request): form=forms.NoticeForm() if request.method=='POST':", "f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice } return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request):", "Sum from django.contrib.auth.models import Group from django.http import HttpResponseRedirect from", "return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if is_admin(request.user): return redirect('admin-dashboard') elif is_teacher(request.user):", "AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance') else: print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin')", "def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin')", "request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('teacher-dashboard') else:", "admin(by sumit) def is_admin(user): return user.groups.filter(name='ADMIN').exists() def is_teacher(user): return user.groups.filter(name='TEACHER').exists()", "return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def", "form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('teacher-dashboard') else: print('form", "AFTER THEIR Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all()", "import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test def home_view(request): if request.user.is_authenticated:", "if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for showing signup/login button", "teacher(by sumit) def teacherclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html')", "AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance') else: print('form invalid') return", "if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>)", "my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "@user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False)", "render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request): return", "@user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST':", "return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST)", "user.delete() teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id)", "user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin')", "if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl", "render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if", "if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save()", "request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date})", "def is_admin(user): return user.groups.filter(name='ADMIN').exists() def is_teacher(user): return user.groups.filter(name='TEACHER').exists() def is_student(user):", "form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_teacher_group =", "= Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form is invalid\") return HttpResponseRedirect('admin-student') return", "= forms.ContactusForm() if request.method == 'POST': sub = forms.ContactusForm(request.POST) if", "= forms.ContactusForm(request.POST) if sub.is_valid(): email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message =", "django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test def home_view(request): if", "return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus", "teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user)", "studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function return", "redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html') #for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin')", "if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return", "mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for", "user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin')", "AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance') else: print('form invalid')", "delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i in range(len(Attendances)):", "invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin')", "invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss (by", "def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user)", "admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "print('form invalid') return render(request,'school/student_view_attendance_ask_date.html',{'form':form}) # for aboutus and contact ussssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss", "if sub.is_valid(): email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message'] send_mail(str(name)+'", "} return render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin')", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl):", "sub = forms.ContactusForm() if request.method == 'POST': sub = forms.ContactusForm(request.POST)", "teacher.status=True teacher.save() return redirect(reverse('admin-approve-teacher')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id)", "user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return", "form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form})", "students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all()", "if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>)", "form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin')", "render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if request.method=='POST':", "if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for showing signup/login button", "user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm() if", "} return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST':", "HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers})", "form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user", "render,redirect,reverse from . import forms,models from django.db.models import Sum from", "return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin')", "def student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True)", "def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm()", "request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return redirect('admin-dashboard') return", "teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl)", "return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save() return", "date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form invalid') return", "return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete()", "invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST':", "teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk):", "by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin')", "f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return", "render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "user.groups.filter(name='ADMIN').exists() def is_teacher(user): return user.groups.filter(name='TEACHER').exists() def is_student(user): return user.groups.filter(name='STUDENT').exists() def", "is_teacher(user): return user.groups.filter(name='TEACHER').exists() def is_student(user): return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if", "adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form is invalid\") return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict)", "def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status')", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request): return render(request,'school/admin_fee.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl):", "render(request,'school/admin_approve_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return redirect(reverse('admin-approve-student'))", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_fee_view(request,cl): feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by", "admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return", "HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for showing signup/login button for teacher(by sumit)", "@user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST)", "render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view by", "return render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "teacher_signup_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid()", "from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test def home_view(request):", "render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request):", "return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if", "return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin')", "def contactus_view(request): sub = forms.ContactusForm() if request.method == 'POST': sub", "admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary')) studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all()", "showing signup/login button for teacher(by sumit) def adminclick_view(request): if request.user.is_authenticated:", "if accountapproval: return redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True)", ", student or admin(by sumit) def is_admin(user): return user.groups.filter(name='ADMIN').exists() def", "form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by", "students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for", "redirect('teacher-attendance') else: print('form invalid') return render(request,'school/teacher_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_view_attendance_view(request,cl):", "django.shortcuts import render,redirect,reverse from . import forms,models from django.db.models import", "user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user)", "user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin') return render(request,'school/teachersignup.html',context=mydict) #for", "render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_dashboard_view(request):", "notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice } return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin')", "'fee':studentdata[0].fee, 'notice':notice } return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm()", "return render(request,'school/student_dashboard.html',context=mydict) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST)", "#fee related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_fee_view(request):", "'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit)", "sumit) mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'],", "sumit) def adminclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for", "request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date})", "return render(request,'school/aboutus.html') def contactus_view(request): sub = forms.ContactusForm() if request.method ==", "pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function return dictionary so fetch data from", "render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_attendance_view(request): return render(request,'school/teacher_attendance.html') @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def", "signup/login button for teacher(by sumit) def adminclick_view(request): if request.user.is_authenticated: return", "from . import forms,models from django.db.models import Sum from django.contrib.auth.models", "request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for showing signup/login button for", "user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group = Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('teacherlogin')", "return user.groups.filter(name='ADMIN').exists() def is_teacher(user): return user.groups.filter(name='TEACHER').exists() def is_student(user): return user.groups.filter(name='STUDENT').exists()", "button for student(by sumit) def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin')", "sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request): return render(request,'school/admin_teacher.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "showing signup/login button for student(by sumit) def studentclick_view(request): if request.user.is_authenticated:", "form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else:", "@user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid():", "import forms,models from django.db.models import Sum from django.contrib.auth.models import Group", "'+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently = False) return render(request, 'school/contactussuccess.html') return", ". import forms,models from django.db.models import Sum from django.contrib.auth.models import", "student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll, 'mobile':studentdata[0].mobile, 'fee':studentdata[0].fee, 'notice':notice } return", "login_required,user_passes_test def home_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/index.html') #for", "for i in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save()", "in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance')", "teacherclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for showing signup/login", "user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def", "teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "user is techer , student or admin(by sumit) def is_admin(user):", "f2.status=True f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) else: print(\"form is invalid\")", "else: print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by", "date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return", "date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl) mylist=zip(attendancedata,studentdata) return render(request,'school/teacher_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return", "#attendance related viewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request): return render(request,'school/admin_attendance.html')", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary')) pendingteachersalary=models.TeacherExtra.objects.filter(status=False).aggregate(Sum('salary'))", "form.by=request.user.first_name form.save() return redirect('admin-dashboard') return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by", "teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save()", "request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST':", "redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers})", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "def teacherclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for showing", "student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST,instance=user) form2=forms.StudentExtraForm(request.POST,instance=student) print(form1)", "HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students})", "teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def approve_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) teacher.status=True teacher.save()", "student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request): return render(request,'school/admin_student.html')", "AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance') else: print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin')", "form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user", "= Group.objects.get_or_create(name='TEACHER') my_teacher_group[0].user_set.add(user) return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "return redirect('admin-attendance') else: print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if", "else: print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm()", "request.method == 'POST': sub = forms.ContactusForm(request.POST) if sub.is_valid(): email =", "is_teacher(request.user): accountapproval=models.TeacherExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html') elif", "return HttpResponseRedirect('admin-teacher') return render(request,'school/admin_add_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=True) return", "@user_passes_test(is_admin) def admin_view_teacher_salary_view(request): teachers=models.TeacherExtra.objects.all() return render(request,'school/admin_view_teacher_salary.html',{'teachers':teachers}) #for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by", "is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('student-dashboard') else: return render(request,'school/student_wait_for_approval.html') #for", "f2.status=True f2.save() return redirect('admin-view-teacher') return render(request,'school/admin_update_teacher.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_teacher_salary_view(request):", "student or admin(by sumit) def is_admin(user): return user.groups.filter(name='ADMIN').exists() def is_teacher(user):", "is techer , student or admin(by sumit) def is_admin(user): return", "mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST) form2=forms.TeacherExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save()", "= sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently = False)", "in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance')", "return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) form1=forms.StudentUserForm(instance=user) form2=forms.StudentExtraForm(instance=student)", "def approve_student_view(request,pk): students=models.StudentExtra.objects.get(id=pk) students.status=True students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete() return redirect('admin-view-teacher')", "def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid():", "button for teacher(by sumit) def adminclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin')", "def adminclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for showing", "request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save() user.set_password(<PASSWORD>) user.save() my_admin_group = Group.objects.get_or_create(name='ADMIN')", "sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): print(\"form is valid\") user=form1.save()", "studentfee=models.StudentExtra.objects.filter(status=True).aggregate(Sum('fee',default=0)) pendingstudentfee=models.StudentExtra.objects.filter(status=False).aggregate(Sum('fee')) notice=models.Notice.objects.all() #aggregate function return dictionary so fetch data", "if request.method=='POST': form=forms.AttendanceForm(request.POST) if form.is_valid(): Attendances=request.POST.getlist('present_status') date=form.cleaned_data['date'] for i in", "f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return", "name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message'] send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently", "redirect('admin-view-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2}", "import render,redirect,reverse from . import forms,models from django.db.models import Sum", "return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return render(request,'school/admin_view_student_fee.html',{'students':students}) #attendance", "def admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save() user.set_password(<PASSWORD>)", "user.delete() student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id)", "HttpResponseRedirect('afterlogin') return render(request,'school/teacherclick.html') #for showing signup/login button for student(by sumit)", "@login_required(login_url='studentlogin') @user_passes_test(is_student) def student_attendance_view(request): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid():", "@user_passes_test(is_admin) def admin_add_student_view(request): form1=forms.StudentUserForm() form2=forms.StudentExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST)", "#for student by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request): return", "return HttpResponseRedirect('admin-student') return render(request,'school/admin_add_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return", "Loginnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='studentlogin') @user_passes_test(is_student) def student_dashboard_view(request): studentdata=models.StudentExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'roll':studentdata[0].roll,", "admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl) studentdata=models.StudentExtra.objects.all().filter(cl=cl)", "return redirect('teacher-dashboard') else: return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval:", "delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-approve-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "= Group.objects.get_or_create(name='ADMIN') my_admin_group[0].user_set.add(user) return HttpResponseRedirect('adminlogin') return render(request,'school/adminsignup.html',{'form':form}) def student_signup_view(request): form1=forms.StudentUserForm()", "return redirect('admin-approve-teacher') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_teacher_from_school_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) user.delete() teacher.delete()", "user=models.User.objects.get(id=student.user_id) user.delete() student.delete() return redirect('admin-view-student') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_view(request,pk): student=models.StudentExtra.objects.get(id=pk)", "teacherdata=models.TeacherExtra.objects.all().filter(status=True,user_id=request.user.id) notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict)", "students.status=True students.save() return redirect(reverse('admin-approve-student')) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_view_student_fee_view(request): students=models.StudentExtra.objects.all() return", "def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'school/studentclick.html') def admin_signup_view(request):", "button for teacher(by sumit) def teacherclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin')", "render(request,'school/admin_view_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_teacher_view(request): teachers=models.TeacherExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_teacher.html',{'teachers':teachers}) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "is valid\") user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user f2.status=True f2.save() my_student_group", "render(request,'school/studentclick.html') def admin_signup_view(request): form=forms.AdminSigupForm() if request.method=='POST': form=forms.AdminSigupForm(request.POST) if form.is_valid(): user=form.save()", "render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if", "AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('admin-attendance') else: print('form invalid') return render(request,'school/admin_take_attendance.html',{'students':students,'aform':aform})", "form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid(): form=form.save(commit=False) form.by=request.user.first_name form.save() return", "AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll AttendanceModel.save() return redirect('teacher-attendance') else: print('form invalid') return", "return render(request,'school/teacher_wait_for_approval.html') elif is_student(request.user): accountapproval=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) if accountapproval: return redirect('student-dashboard') else:", "contactus_view(request): sub = forms.ContactusForm() if request.method == 'POST': sub =", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_teacher_view(request): form1=forms.TeacherUserForm() form2=forms.TeacherExtraForm() mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST)", "'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict)", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def update_teacher_view(request,pk): teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if", "Group from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test def", "teacher=models.TeacherExtra.objects.get(id=pk) user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1)", "checking user is techer , student or admin(by sumit) def", "students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) user.delete()", "redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_approve_student_view(request): students=models.StudentExtra.objects.all().filter(status=False) return render(request,'school/admin_approve_student.html',{'students':students})", "def admin_view_attendance_view(request,cl): form=forms.AskDateForm() if request.method=='POST': form=forms.AskDateForm(request.POST) if form.is_valid(): date=form.cleaned_data['date'] attendancedata=models.Attendance.objects.all().filter(date=date,cl=cl)", "date=form.cleaned_data['date'] for i in range(len(Attendances)): AttendanceModel=models.Attendance() AttendanceModel.cl=cl AttendanceModel.date=date AttendanceModel.present_status=Attendances[i] AttendanceModel.roll=students[i].roll", "mydict={ 'teachercount':teachercount, 'pendingteachercount':pendingteachercount, 'studentcount':studentcount, 'pendingstudentcount':pendingstudentcount, 'teachersalary':teachersalary['salary__sum'], 'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice", "send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, ['<EMAIL>'], fail_silently = False) return render(request,", "def is_student(user): return user.groups.filter(name='STUDENT').exists() def afterlogin_view(request): if is_admin(request.user): return redirect('admin-dashboard')", "return render(request,'school/admin_view_attendance_page.html',{'cl':cl,'mylist':mylist,'date':date}) else: print('form invalid') return render(request,'school/admin_view_attendance_ask_date.html',{'cl':cl,'form':form}) #fee related view", "form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save()", "import Sum from django.contrib.auth.models import Group from django.http import HttpResponseRedirect", "sub.is_valid(): email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message'] send_mail(str(name)+' ||", "return HttpResponseRedirect('afterlogin') return render(request,'school/adminclick.html') #for showing signup/login button for teacher(by", "dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count()", "feedetails=models.StudentExtra.objects.all().filter(cl=cl) return render(request,'school/admin_view_fee.html',{'feedetails':feedetails,'cl':cl}) #notice related viewsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def", "request.method=='POST': form1=forms.StudentUserForm(request.POST) form2=forms.StudentExtraForm(request.POST) if form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save()", "notice=models.Notice.objects.all() mydict={ 'salary':teacherdata[0].salary, 'mobile':teacherdata[0].mobile, 'date':teacherdata[0].joindate, 'notice':notice } return render(request,'school/teacher_dashboard.html',context=mydict) @login_required(login_url='teacherlogin')", "@login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) aform=forms.AttendanceForm() if request.method=='POST': form=forms.AttendanceForm(request.POST) if", "== 'POST': sub = forms.ContactusForm(request.POST) if sub.is_valid(): email = sub.cleaned_data['Email']", "print('form invalid') return render(request,'school/teacher_view_attendance_ask_date.html',{'cl':cl,'form':form}) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm() if", "and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_student_group =", "@login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def teacher_notice_view(request): form=forms.NoticeForm() if request.method=='POST': form=forms.NoticeForm(request.POST) if form.is_valid():", "#for checking user is techer , student or admin(by sumit)", "@login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_student_view(request): return render(request,'school/admin_student.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_add_student_view(request):", "if form.is_valid(): date=form.cleaned_data['date'] studentdata=models.StudentExtra.objects.all().filter(user_id=request.user.id,status=True) attendancedata=models.Attendance.objects.all().filter(date=date,cl=studentdata[0].cl,roll=studentdata[0].roll) mylist=zip(attendancedata,studentdata) return render(request,'school/student_view_attendance_page.html',{'mylist':mylist,'date':date}) else: print('form", "return render(request,'school/admin_notice.html',{'form':form}) #for TEACHER LOGIN SECTIONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN(by sumit) @login_required(login_url='teacherlogin') @user_passes_test(is_teacher) def", "my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return HttpResponseRedirect('studentlogin') return render(request,'school/studentsignup.html',context=mydict) def teacher_signup_view(request):", "admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id)", "form1.is_valid() and form2.is_valid(): user=form1.save() user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.user=user user2=f2.save() my_teacher_group", "sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_dashboard_view(request): teachercount=models.TeacherExtra.objects.all().filter(status=True).count() pendingteachercount=models.TeacherExtra.objects.all().filter(status=False).count() studentcount=models.StudentExtra.objects.all().filter(status=True).count() pendingstudentcount=models.StudentExtra.objects.all().filter(status=False).count() teachersalary=models.TeacherExtra.objects.filter(status=True).aggregate(Sum('salary'))", "user.set_password(<PASSWORD>) user.save() f2=form2.save(commit=False) f2.status=True f2.save() return redirect('admin-view-student') return render(request,'school/admin_update_student.html',context=mydict) @login_required(login_url='adminlogin')", "render(request,'school/adminclick.html') #for showing signup/login button for teacher(by sumit) def teacherclick_view(request):", "user=models.User.objects.get(id=teacher.user_id) form1=forms.TeacherUserForm(instance=user) form2=forms.TeacherExtraForm(instance=teacher) mydict={'form1':form1,'form2':form2} if request.method=='POST': form1=forms.TeacherUserForm(request.POST,instance=user) form2=forms.TeacherExtraForm(request.POST,instance=teacher) print(form1) if", "teacher sectionnnnnnnn by adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_teacher_view(request): return", "forms.ContactusForm(request.POST) if sub.is_valid(): email = sub.cleaned_data['Email'] name=sub.cleaned_data['Name'] message = sub.cleaned_data['Message']", "def admin_view_student_view(request): students=models.StudentExtra.objects.all().filter(status=True) return render(request,'school/admin_view_student.html',{'students':students}) @login_required(login_url='adminlogin') @user_passes_test(is_admin) def delete_student_from_school_view(request,pk): student=models.StudentExtra.objects.get(id=pk)", "def admin_attendance_view(request): return render(request,'school/admin_attendance.html') @login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_take_attendance_view(request,cl): students=models.StudentExtra.objects.all().filter(cl=cl) print(students)", "else: return render(request,'school/student_wait_for_approval.html') #for dashboard of adminnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn(by sumit) @login_required(login_url='adminlogin') @user_passes_test(is_admin)", "'pendingteachersalary':pendingteachersalary['salary__sum'], 'studentfee':studentfee['fee__sum'], 'pendingstudentfee':pendingstudentfee['fee__sum'], 'notice':notice } return render(request,'school/admin_dashboard.html',context=mydict) #for teacher sectionnnnnnnn", "#for showing signup/login button for student(by sumit) def studentclick_view(request): if" ]
[ "iounet_backbone_features = TensorList([ output_features[layer] for layer in self.iounet_feature_layers ]) self.iounet_backbone_features", "SiamMask_ResNet50_base from pytracking.admin.environment import env_settings from pytracking.features.featurebase import MultiFeatureBase from", "= fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor = self.net.bb_regressor self.layer_stride = {", "debug_save_name is not None: np.savez(debug_save_name, im) im = n2p(im) output_features", "estimator_backbone_features = TensorList([ output_features[layer] for layer in self.estimator_feature_layers ]) self.estimator_backbone_features", "for layer in output_features]) return output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature.", "1 / 255.], [1, -1, 1, 1]) def free_memory(self): if", "output = TensorList([ output_features[layer].numpy() for layer in self.output_layers ]) return", "input to iounet iounet_backbone_features = TensorList([ output_features[layer] for layer in", "use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu = use_gpu self.net_path =", "128, 'block2': 256, 'block3': 512, 'classification': 256, 'fc': None }", "self.std im = n2p(im) output_features = self.net.extract_features(im, self.feature_layers) # Store", "'block2': 16, 'block3': 32, 'classification': 16, 'fc': None } self.layer_dim", "for f in self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output = TensorList([ output_features[layer].numpy()", "'block3': 2048, 'classification': 256, 'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer", ") output = TensorList([ output_features[layer].numpy() for layer in self.output_layers ])", "im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name is not None:", "8, 'block2': 16, 'block3': 32, 'classification': 16, 'fc': None }", "if debug_save_name is not None: np.savez(debug_save_name, im) im = n2p(im)", "_ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self): if hasattr(self, 'net'):", "1, 1]) self.std = np.reshape([1 / 255., 1 / 255.,", "features which are input to estimator estimator_backbone_features = TensorList([ output_features[layer]", "the raw backbone features which are input to estimator output", "if hasattr(self, 'net'): del self.net def extract(self, im: np.ndarray, debug_save_name=None):", "self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet50( backbone_pretrained=False,", "output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of layers", "iounet_backbone_features.numpy() # Store the processed features from iounet, just before", "for layer in self.estimator_feature_layers ]) self.estimator_backbone_features = estimator_backbone_features.numpy( ) output", "del self.net if hasattr(self, 'iou_predictor'): del self.iou_predictor if hasattr(self, 'iounet_backbone_features'):", "the raw resnet features which are input to iounet iounet_backbone_features", "1]) self.std = np.reshape([1 / 255., 1 / 255., 1", "ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args: output_layers: List of layers to output.", "hasattr(self, 'net'): del self.net if hasattr(self, 'target_estimator'): del self.target_estimator if", "self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True)", "pytracking.libs import TensorList from pytracking.libs.paddle_utils import n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18", "* len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.iounet_feature_layers))) self.mean =", "= { 'conv0': 64, 'conv1': 64, 'block0': 64, 'block1': 128,", "self.mean im /= self.std im = n2p(im) output_features = self.net.extract_features(im,", "self.net.extract_backbone_features(im) # Store the raw backbone features which are input", "* len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.estimator_feature_layers))) self.mean =", "import os import numpy as np from paddle import fluid", "# Store the raw backbone features which are input to", "'conv0': 2, 'conv1': 2, 'block0': 4, 'block1': 8, 'block2': 16,", "are input to estimator output = TensorList([layer.numpy() for layer in", "ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args: output_layers: List of layers to output.", "or CPU. \"\"\" def __init__(self, output_layers=('conv5', ), net_path='estimator', use_gpu=True, *args,", "self.feature_layers) # Store the raw resnet features which are input", "), net_path='atom_iou', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers)", "def initialize(self): with fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full = self.net_path else:", "iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor = self.net.bb_regressor", "= np.reshape([0.229, 0.224, 0.225], [1, -1, 1, 1]) def free_memory(self):", "self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = siamfc_alexnet( backbone_pretrained=False,", "estimator output = TensorList([layer.numpy() for layer in output_features]) return output", "iounet_backbone_features) ]) output = TensorList([ output_features[layer].numpy() for layer in self.output_layers", "l in self.output_layers]) def stride(self): return TensorList([ s * self.layer_stride[l]", "backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor", "use_gpu: Use GPU or CPU. \"\"\" def __init__(self, output_layers=('block2', ),", "256} self.estimator_feature_layers = self.net.target_estimator_layer if isinstance(self.pool_stride, int) and self.pool_stride ==", "__init__(self, output_layers=('conv5', ), net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers", "raw backbone features which are input to estimator estimator_backbone_features =", "if hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features def dim(self): return TensorList([self.layer_dim[l] for", "paddle import fluid from ltr.models.bbreg.atom import atom_resnet50, atom_resnet18 from ltr.models.siamese.siam", "from ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment import env_settings", "'target_estimator'): del self.target_estimator if hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features def dim(self):", "TensorList([ output_features[layer] for layer in self.iounet_feature_layers ]) self.iounet_backbone_features = iounet_backbone_features.numpy()", "int) and self.pool_stride == 1: self.pool_stride = [1] * len(self.output_layers)", "output_features[layer].numpy() for layer in self.output_layers ]) return output class ResNet50(MultiFeatureBase):", "im) im = im / 255. # don't use im", "def stride(self): return TensorList([ s * self.layer_stride[l] for l, s", "\"\"\" def __init__(self, net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu", "iounet iounet_backbone_features = TensorList([ output_features[layer] for layer in self.iounet_feature_layers ])", "net_path='atom_iou', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers) self.use_gpu", "in output_features]) return output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers:", "\"\"\" def __init__(self, output_layers=('conv5', ), net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args,", "= os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm,", "del self.iou_predictor if hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features if hasattr(self, 'iounet_features'):", "self.net.bb_regressor_layer if isinstance(self.pool_stride, int) and self.pool_stride == 1: self.pool_stride =", "is not None: np.savez(debug_save_name, im) im = n2p(im) output_features =", "hasattr(self, 'net'): del self.net if hasattr(self, 'iou_predictor'): del self.iou_predictor if", "255., 1 / 255.], [1, -1, 1, 1]) def free_memory(self):", "self.feature_layers = sorted( list(set(self.output_layers + self.iounet_feature_layers))) self.mean = np.reshape([0.485, 0.456,", "= estimator_backbone_features.numpy( ) output = TensorList([ output_features[layer].numpy() for layer in", "l, s in zip(self.output_layers, self.pool_stride) ]) def extract(self, im: np.ndarray,", "8} self.layer_dim = {'conv5': 256} self.estimator_feature_layers = self.net.target_estimator_layer if isinstance(self.pool_stride,", "backbone features which are input to estimator estimator_backbone_features = TensorList([", "for l in self.output_layers]) def stride(self): return TensorList([ s *", "list(output_layers) self.use_gpu = use_gpu self.net_path = net_path def initialize(self): with", "output_features[layer] for layer in self.estimator_feature_layers ]) self.estimator_backbone_features = estimator_backbone_features.numpy( )", "= self.net.target_estimator self.layer_stride = {'conv5': 8} self.layer_dim = {'conv5': 256}", "class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args: output_layers: List of layers to", "import fluid from ltr.models.bbreg.atom import atom_resnet50, atom_resnet18 from ltr.models.siamese.siam import", "for layer in output_features]) return output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature.", "os.path.isabs(self.net_path): net_path_full = self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net", "= sorted( list(set(self.output_layers + self.iounet_feature_layers))) self.mean = np.reshape([0.485, 0.456, 0.406],", "if hasattr(self, 'iou_predictor'): del self.iou_predictor if hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features", "[1, -1, 1, 1]) def free_memory(self): if hasattr(self, 'net'): del", "1]) def free_memory(self): if hasattr(self, 'net'): del self.net if hasattr(self,", "class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args: output_layers: List of layers to", "else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet50( backbone_pretrained=False, backbone_is_test=True,", "'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer if isinstance(self.pool_stride, int) and", "net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu = use_gpu self.net_path", "np.reshape([0., 0., 0.], [1, -1, 1, 1]) self.std = np.reshape([1", "net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True)", "# Store the processed features from iounet, just before pooling", "we don't want to alter the input im -= self.mean", "fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator = self.net.target_estimator self.layer_stride = {'conv5': 8}", "n2p(im) output_features = self.net.extract_features(im, self.feature_layers) # Store the raw resnet", "super().__init__(*args, **kwargs) self.output_layers = list(output_layers) self.use_gpu = use_gpu self.net_path =", "def dim(self): return TensorList([self.layer_dim[l] for l in self.output_layers]) def stride(self):", "to output. net_path: Relative or absolute net path (default should", "ltr.models.bbreg.atom import atom_resnet50, atom_resnet18 from ltr.models.siamese.siam import siamfc_alexnet from ltr.models.siam.siam", "= TensorList([ output_features[layer] for layer in self.estimator_feature_layers ]) self.estimator_backbone_features =", "estimator estimator_backbone_features = TensorList([ output_features[layer] for layer in self.estimator_feature_layers ])", "= im / 255. # don't use im /= 255.", "estimator_backbone_features.numpy( ) output = TensorList([ output_features[layer].numpy() for layer in self.output_layers", "with fluid.dygraph.guard(): if debug_save_name is not None: np.savez(debug_save_name, im) im", "env_settings from pytracking.features.featurebase import MultiFeatureBase from pytracking.libs import TensorList from", "Relative or absolute net path (default should be fine). use_gpu:", "-1, 1, 1]) def free_memory(self): if hasattr(self, 'net'): del self.net", "self.pool_stride) ]) def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if", "TensorList([ output_features[layer].numpy() for layer in self.output_layers ]) return output class", "n2p(im) output_features = self.net.extract_backbone_features(im) # Store the raw backbone features", "net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _", "MultiFeatureBase from pytracking.libs import TensorList from pytracking.libs.paddle_utils import n2p class", "]) return output class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args: output_layers: List", "self.iounet_backbone_features if hasattr(self, 'iounet_features'): del self.iounet_features def dim(self): return TensorList([self.layer_dim[l]", "self.net = siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full)", "to estimator output = TensorList([layer.numpy() for layer in output_features]) return", "255., 1 / 255., 1 / 255.], [1, -1, 1,", "to alter the input im -= self.mean im /= self.std", "layer in output_features]) return output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args:", "self.net.eval() def free_memory(self): if hasattr(self, 'net'): del self.net def extract(self,", "net_path: Relative or absolute net path (default should be fine).", "= [1] * len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.estimator_feature_layers)))", "= self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False,", "import MultiFeatureBase from pytracking.libs import TensorList from pytracking.libs.paddle_utils import n2p", "_ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor = self.net.bb_regressor self.layer_stride =", "output_layers: List of layers to output. net_path: Relative or absolute", "return TensorList([ s * self.layer_stride[l] for l, s in zip(self.output_layers,", "Store the raw backbone features which are input to estimator", "os.path.join(env_settings().network_path, self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full)", "output_features[layer].numpy() for layer in self.output_layers ]) return output class SFCAlexnet(MultiFeatureBase):", "Use GPU or CPU. \"\"\" def __init__(self, output_layers=('conv5', ), net_path='estimator',", "use_gpu: Use GPU or CPU. \"\"\" def __init__(self, output_layers=('conv5', ),", "or absolute net path (default should be fine). use_gpu: Use", "for layer in self.iounet_feature_layers ]) self.iounet_backbone_features = iounet_backbone_features.numpy() # Store", "self.feature_layers = sorted( list(set(self.output_layers + self.estimator_feature_layers))) self.mean = np.reshape([0., 0.,", "are input to estimator estimator_backbone_features = TensorList([ output_features[layer] for layer", "= SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def", "before pooling self.iounet_features = TensorList([ f.numpy() for f in self.iou_predictor.get_iou_feat(", "self.net = atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full)", "/ 255., 1 / 255.], [1, -1, 1, 1]) def", "self.target_estimator = self.net.target_estimator self.layer_stride = {'conv5': 8} self.layer_dim = {'conv5':", "alter the input im -= self.mean im /= self.std im", "feature. args: output_layers: List of layers to output. net_path: Relative", "TensorList([layer.numpy() for layer in output_features]) return output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated", "in self.output_layers ]) return output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args:", "class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of layers to", "else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict,", "} self.iounet_feature_layers = self.net.bb_regressor_layer if isinstance(self.pool_stride, int) and self.pool_stride ==", "self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict)", "in self.output_layers ]) return output class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args:", "state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator = self.net.target_estimator self.layer_stride", "self.estimator_backbone_features = estimator_backbone_features.numpy( ) output = TensorList([ output_features[layer].numpy() for layer", "if os.path.isabs(self.net_path): net_path_full = self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path)", "from pytracking.admin.environment import env_settings from pytracking.features.featurebase import MultiFeatureBase from pytracking.libs", "'net'): del self.net def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard():", "del self.iounet_features def dim(self): return TensorList([self.layer_dim[l] for l in self.output_layers])", "in self.iounet_feature_layers ]) self.iounet_backbone_features = iounet_backbone_features.numpy() # Store the processed", "/ 255. # don't use im /= 255. since we", "want to alter the input im -= self.mean im /=", "self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval()", "def __init__(self, output_layers=('conv5', ), net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs)", "self.std = np.reshape([1 / 255., 1 / 255., 1 /", "estimator_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator = self.net.target_estimator", "numpy as np from paddle import fluid from ltr.models.bbreg.atom import", "from paddle import fluid from ltr.models.bbreg.atom import atom_resnet50, atom_resnet18 from", "self.std = np.reshape([0.229, 0.224, 0.225], [1, -1, 1, 1]) def", "self.iounet_features def dim(self): return TensorList([self.layer_dim[l] for l in self.output_layers]) def", "= use_gpu self.net_path = net_path def initialize(self): with fluid.dygraph.guard(): if", "from pytracking.libs.paddle_utils import n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args: output_layers:", "ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment import env_settings from", "= self.net.extract_features(im, self.feature_layers) # Store the raw backbone features which", "[1] * len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.estimator_feature_layers))) self.mean", "output_features = self.net.extract_backbone_features(im) # Store the raw backbone features which", "'estimator_backbone_features'): del self.estimator_backbone_features def dim(self): return TensorList([self.layer_dim[l] for l in", "'conv1': 2, 'block0': 4, 'block1': 8, 'block2': 16, 'block3': 32,", "TensorList from pytracking.libs.paddle_utils import n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args:", "= self.net.target_estimator_layer if isinstance(self.pool_stride, int) and self.pool_stride == 1: self.pool_stride", "self.mean = np.reshape([0., 0., 0.], [1, -1, 1, 1]) self.std", "list(set(self.output_layers + self.iounet_feature_layers))) self.mean = np.reshape([0.485, 0.456, 0.406], [1, -1,", "= self.net.extract_backbone_features(im) # Store the raw backbone features which are", "len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.estimator_feature_layers))) self.mean = np.reshape([0.,", "# don't use im /= 255. since we don't want", "_ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator = self.net.target_estimator self.layer_stride =", "self.iounet_feature_layers = self.net.bb_regressor_layer if isinstance(self.pool_stride, int) and self.pool_stride == 1:", "= os.path.join(env_settings().network_path, self.net_path) self.net = siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm,", "debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name is not None: np.savez(debug_save_name, im)", "don't want to alter the input im -= self.mean im", "256, 'block3': 512, 'classification': 256, 'fc': None } self.iounet_feature_layers =", "/= self.std im = n2p(im) output_features = self.net.extract_features(im, self.feature_layers) #", "self.iou_predictor = self.net.bb_regressor self.layer_stride = { 'conv0': 2, 'conv1': 2,", "self.estimator_feature_layers = self.net.target_estimator_layer if isinstance(self.pool_stride, int) and self.pool_stride == 1:", "self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output = TensorList([ output_features[layer].numpy() for layer in", "self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True)", "]) def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name", "self.net_path) self.net = atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ =", "= n2p(im) output_features = self.net.extract_backbone_features(im) # Store the raw backbone", "fine). use_gpu: Use GPU or CPU. \"\"\" def __init__(self, net_path='estimator',", "not None: np.savez(debug_save_name, im) im = n2p(im) output_features = self.net.extract_backbone_features(im)", "def __init__(self, output_layers=('block2', ), net_path='atom_iou', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs)", "input to estimator output = TensorList([layer.numpy() for layer in output_features])", "fluid from ltr.models.bbreg.atom import atom_resnet50, atom_resnet18 from ltr.models.siamese.siam import siamfc_alexnet", "del self.target_estimator if hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features def dim(self): return", "2, 'conv1': 2, 'block0': 4, 'block1': 8, 'block2': 16, 'block3':", "im = im / 255. # don't use im /=", "Store the raw resnet features which are input to iounet", "free_memory(self): if hasattr(self, 'net'): del self.net if hasattr(self, 'iou_predictor'): del", "s * self.layer_stride[l] for l, s in zip(self.output_layers, self.pool_stride) ])", "= fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator = self.net.target_estimator self.layer_stride = {'conv5':", "]) self.estimator_backbone_features = estimator_backbone_features.numpy( ) output = TensorList([ output_features[layer].numpy() for", "{'conv5': 8} self.layer_dim = {'conv5': 256} self.estimator_feature_layers = self.net.target_estimator_layer if", "'classification': 16, 'fc': None } self.layer_dim = { 'conv0': 64,", "= { 'conv0': 2, 'conv1': 2, 'block0': 4, 'block1': 8,", "1: self.pool_stride = [1] * len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers", "np.reshape([0.229, 0.224, 0.225], [1, -1, 1, 1]) def free_memory(self): if", "{ 'conv0': 64, 'conv1': 64, 'block0': 256, 'block1': 512, 'block2':", "from pytracking.features.featurebase import MultiFeatureBase from pytracking.libs import TensorList from pytracking.libs.paddle_utils", "= self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet50(", "sorted( list(set(self.output_layers + self.estimator_feature_layers))) self.mean = np.reshape([0., 0., 0.], [1,", "layer in self.output_layers ]) return output class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature.", "255. since we don't want to alter the input im", "in zip(self.output_layers, self.pool_stride) ]) def extract(self, im: np.ndarray, debug_save_name=None): with", "= self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False,", "__init__(self, output_layers=('block2', ), net_path='atom_iou', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers", "state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self): if hasattr(self,", "64, 'block0': 64, 'block1': 128, 'block2': 256, 'block3': 512, 'classification':", "raw backbone features which are input to estimator output =", "f in self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output = TensorList([ output_features[layer].numpy() for", "= net_path def initialize(self): with fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full =", "self.layer_stride = {'conv5': 8} self.layer_dim = {'conv5': 256} self.estimator_feature_layers =", "= list(output_layers) self.use_gpu = use_gpu self.net_path = net_path def initialize(self):", "def free_memory(self): if hasattr(self, 'net'): del self.net if hasattr(self, 'target_estimator'):", "for layer in self.output_layers ]) return output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet", "else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict,", "class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of layers to", "]) self.iounet_backbone_features = iounet_backbone_features.numpy() # Store the processed features from", "output_features[layer] for layer in self.iounet_feature_layers ]) self.iounet_backbone_features = iounet_backbone_features.numpy() #", "output = TensorList([layer.numpy() for layer in output_features]) return output class", "'conv1': 64, 'block0': 64, 'block1': 128, 'block2': 256, 'block3': 512,", "extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name is not", "use im /= 255. since we don't want to alter", "-= self.mean im /= self.std im = n2p(im) output_features =", "for layer in self.output_layers ]) return output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet", "2, 'block0': 4, 'block1': 8, 'block2': 16, 'block3': 32, 'classification':", "net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True)", "layer in self.output_layers ]) return output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature.", "self.net.load_dict(state_dict) self.net.eval() def free_memory(self): if hasattr(self, 'net'): del self.net def", "16, 'block3': 32, 'classification': 16, 'fc': None } self.layer_dim =", "= np.reshape([1 / 255., 1 / 255., 1 / 255.],", "iounet, just before pooling self.iounet_features = TensorList([ f.numpy() for f", "self.layer_dim = { 'conv0': 64, 'conv1': 64, 'block0': 256, 'block1':", "]) return output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List", "if debug_save_name is not None: np.savez(debug_save_name, im) im = im", "= n2p(im) output_features = self.net.extract_features(im, self.feature_layers) # Store the raw", "self.net.target_estimator self.layer_stride = {'conv5': 8} self.layer_dim = {'conv5': 256} self.estimator_feature_layers", "im / 255. # don't use im /= 255. since", "1, 1]) self.std = np.reshape([0.229, 0.224, 0.225], [1, -1, 1,", "output_layers=('block2', ), net_path='atom_iou', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers =", "free_memory(self): if hasattr(self, 'net'): del self.net def extract(self, im: np.ndarray,", "initialize(self): with fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full = self.net_path else: net_path_full", "layers to output. net_path: Relative or absolute net path (default", "= {'conv5': 8} self.layer_dim = {'conv5': 256} self.estimator_feature_layers = self.net.target_estimator_layer", "siamfc_alexnet from ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment import", "output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of layers", "super().__init__(*args, **kwargs) self.use_gpu = use_gpu self.net_path = net_path def initialize(self):", "'block0': 64, 'block1': 128, 'block2': 256, 'block3': 512, 'classification': 256,", "output_layers=('conv5', ), net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers =", "'block0': 4, 'block1': 8, 'block2': 16, 'block3': 32, 'classification': 16,", "64, 'block0': 256, 'block1': 512, 'block2': 1024, 'block3': 2048, 'classification':", "del self.estimator_backbone_features def dim(self): return TensorList([self.layer_dim[l] for l in self.output_layers])", "np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name is not None: np.savez(debug_save_name,", "SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of layers to output.", "pytracking.libs.paddle_utils import n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args: output_layers: List", "backbone_is_test=True, estimator_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator =", "), net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers)", "/= 255. since we don't want to alter the input", "del self.net if hasattr(self, 'target_estimator'): del self.target_estimator if hasattr(self, 'estimator_backbone_features'):", "hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features def dim(self): return TensorList([self.layer_dim[l] for l", "{ 'conv0': 2, 'conv1': 2, 'block0': 4, 'block1': 8, 'block2':", "return output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of", "= os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _ =", "free_memory(self): if hasattr(self, 'net'): del self.net if hasattr(self, 'target_estimator'): del", "hasattr(self, 'target_estimator'): del self.target_estimator if hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features def", "SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of layers to output.", "= self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = siamfc_alexnet(", "n2p(im) output_features = self.net.extract_features(im, self.feature_layers) # Store the raw backbone", "if isinstance(self.pool_stride, int) and self.pool_stride == 1: self.pool_stride = [1]", "TensorList([ s * self.layer_stride[l] for l, s in zip(self.output_layers, self.pool_stride)", "pytracking.features.featurebase import MultiFeatureBase from pytracking.libs import TensorList from pytracking.libs.paddle_utils import", "Store the processed features from iounet, just before pooling self.iounet_features", "= siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm)", "= TensorList([ output_features[layer] for layer in self.iounet_feature_layers ]) self.iounet_backbone_features =", "fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor = self.net.bb_regressor self.layer_stride = { 'conv0':", "import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment import env_settings from pytracking.features.featurebase", "del self.iounet_backbone_features if hasattr(self, 'iounet_features'): del self.iounet_features def dim(self): return", "np.reshape([1 / 255., 1 / 255., 1 / 255.], [1,", "backbone features which are input to estimator output = TensorList([layer.numpy()", "else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict,", "self.iounet_feature_layers ]) self.iounet_backbone_features = iounet_backbone_features.numpy() # Store the processed features", "} self.layer_dim = { 'conv0': 64, 'conv1': 64, 'block0': 256,", "**kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers) self.use_gpu = use_gpu self.net_path", "backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor =", "not None: np.savez(debug_save_name, im) im = im / 255. #", "os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _", "isinstance(self.pool_stride, int) and self.pool_stride == 1: self.pool_stride = [1] *", "is not None: np.savez(debug_save_name, im) im = im / 255.", "class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of layers to", "{'conv5': 256} self.estimator_feature_layers = self.net.target_estimator_layer if isinstance(self.pool_stride, int) and self.pool_stride", "self.net if hasattr(self, 'iou_predictor'): del self.iou_predictor if hasattr(self, 'iounet_backbone_features'): del", "self.iou_predictor if hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features if hasattr(self, 'iounet_features'): del", "np.reshape([0.485, 0.456, 0.406], [1, -1, 1, 1]) self.std = np.reshape([0.229,", "of layers to output. net_path: Relative or absolute net path", "self.net.load_dict(state_dictsm) self.net.train() self.target_estimator = self.net.target_estimator self.layer_stride = {'conv5': 8} self.layer_dim", "self.estimator_feature_layers ]) self.estimator_backbone_features = estimator_backbone_features.numpy( ) output = TensorList([ output_features[layer].numpy()", "the processed features from iounet, just before pooling self.iounet_features =", "= atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm)", "self.net.train() self.target_estimator = self.net.target_estimator self.layer_stride = {'conv5': 8} self.layer_dim =", "hasattr(self, 'iou_predictor'): del self.iou_predictor if hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features if", "= TensorList([layer.numpy() for layer in output_features]) return output class SMaskResNet50_base(MultiFeatureBase):", "in self.estimator_feature_layers ]) self.estimator_backbone_features = estimator_backbone_features.numpy( ) output = TensorList([", "should be fine). use_gpu: Use GPU or CPU. \"\"\" def", "* self.layer_stride[l] for l, s in zip(self.output_layers, self.pool_stride) ]) def", "self.net.extract_features(im, self.feature_layers) # Store the raw resnet features which are", "'net'): del self.net if hasattr(self, 'iou_predictor'): del self.iou_predictor if hasattr(self,", "= os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm,", "} self.layer_dim = { 'conv0': 64, 'conv1': 64, 'block0': 64,", "and self.pool_stride == 1: self.pool_stride = [1] * len(self.output_layers) self.feature_layers", "import siamfc_alexnet from ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment", "siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train()", "self.net_path) self.net = siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm, _ =", "'block3': 512, 'classification': 256, 'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer", "in self.output_layers]) def stride(self): return TensorList([ s * self.layer_stride[l] for", "for l, s in zip(self.output_layers, self.pool_stride) ]) def extract(self, im:", "CPU. \"\"\" def __init__(self, net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs)", "use_gpu self.net_path = net_path def initialize(self): with fluid.dygraph.guard(): if os.path.isabs(self.net_path):", "the input im -= self.mean im /= self.std im =", "0., 0.], [1, -1, 1, 1]) self.std = np.reshape([1 /", "'block1': 8, 'block2': 16, 'block3': 32, 'classification': 16, 'fc': None", "self.iounet_feature_layers))) self.mean = np.reshape([0.485, 0.456, 0.406], [1, -1, 1, 1])", "be fine). use_gpu: Use GPU or CPU. \"\"\" def __init__(self,", "net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers) self.use_gpu", "features which are input to iounet iounet_backbone_features = TensorList([ output_features[layer]", "0.225], [1, -1, 1, 1]) def free_memory(self): if hasattr(self, 'net'):", "the raw backbone features which are input to estimator estimator_backbone_features", "None } self.layer_dim = { 'conv0': 64, 'conv1': 64, 'block0':", "return TensorList([self.layer_dim[l] for l in self.output_layers]) def stride(self): return TensorList([", "self.layer_dim = { 'conv0': 64, 'conv1': 64, 'block0': 64, 'block1':", "net_path def initialize(self): with fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full = self.net_path", "else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet18( backbone_pretrained=False, backbone_is_test=True,", "'iounet_backbone_features'): del self.iounet_backbone_features if hasattr(self, 'iounet_features'): del self.iounet_features def dim(self):", "(default should be fine). use_gpu: Use GPU or CPU. \"\"\"", "atom_resnet50, atom_resnet18 from ltr.models.siamese.siam import siamfc_alexnet from ltr.models.siam.siam import SiamRPN_AlexNet,", "self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict)", "just before pooling self.iounet_features = TensorList([ f.numpy() for f in", "0.456, 0.406], [1, -1, 1, 1]) self.std = np.reshape([0.229, 0.224,", "\"\"\"ResNet18 feature. args: output_layers: List of layers to output. net_path:", "del self.net def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if", "atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train()", "os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _", "output_features[layer].numpy() for layer in self.output_layers ]) return output class SRPNAlexNet(MultiFeatureBase):", "SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment import env_settings from pytracking.features.featurebase import", "as np from paddle import fluid from ltr.models.bbreg.atom import atom_resnet50,", "are input to iounet iounet_backbone_features = TensorList([ output_features[layer] for layer", "4, 'block1': 8, 'block2': 16, 'block3': 32, 'classification': 16, 'fc':", "self.net.train() self.iou_predictor = self.net.bb_regressor self.layer_stride = { 'conv0': 2, 'conv1':", "0.], [1, -1, 1, 1]) self.std = np.reshape([1 / 255.,", "*args, **kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers) self.use_gpu = use_gpu", "= TensorList([ output_features[layer].numpy() for layer in self.output_layers ]) return output", "which are input to estimator estimator_backbone_features = TensorList([ output_features[layer] for", "net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _", "TensorList([ output_features[layer] for layer in self.estimator_feature_layers ]) self.estimator_backbone_features = estimator_backbone_features.numpy(", "None } self.iounet_feature_layers = self.net.bb_regressor_layer if isinstance(self.pool_stride, int) and self.pool_stride", "os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full)", "-1, 1, 1]) self.std = np.reshape([1 / 255., 1 /", "= SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def", "from ltr.models.bbreg.atom import atom_resnet50, atom_resnet18 from ltr.models.siamese.siam import siamfc_alexnet from", "hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features if hasattr(self, 'iounet_features'): del self.iounet_features def", "/ 255., 1 / 255., 1 / 255.], [1, -1,", "__init__(self, net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu = use_gpu", "from ltr.models.siamese.siam import siamfc_alexnet from ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base", "# Store the raw resnet features which are input to", "== 1: self.pool_stride = [1] * len(self.output_layers) self.feature_layers = sorted(", "SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of layers to output.", "512, 'block2': 1024, 'block3': 2048, 'classification': 256, 'fc': None }", "= self.net.bb_regressor self.layer_stride = { 'conv0': 2, 'conv1': 2, 'block0':", "atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train()", "self.output_layers = list(output_layers) self.use_gpu = use_gpu self.net_path = net_path def", "= iounet_backbone_features.numpy() # Store the processed features from iounet, just", "self.layer_stride[l] for l, s in zip(self.output_layers, self.pool_stride) ]) def extract(self,", "layer in self.output_layers ]) return output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature.", "self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict)", "input im -= self.mean im /= self.std im = n2p(im)", "self.iounet_backbone_features = iounet_backbone_features.numpy() # Store the processed features from iounet,", "im -= self.mean im /= self.std im = n2p(im) output_features", "since we don't want to alter the input im -=", "= self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False,", "/ 255.], [1, -1, 1, 1]) def free_memory(self): if hasattr(self,", "self.iounet_features = TensorList([ f.numpy() for f in self.iou_predictor.get_iou_feat( iounet_backbone_features) ])", "= np.reshape([0., 0., 0.], [1, -1, 1, 1]) self.std =", "return output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of", "features from iounet, just before pooling self.iounet_features = TensorList([ f.numpy()", "self.layer_stride = { 'conv0': 2, 'conv1': 2, 'block0': 4, 'block1':", "layer in self.iounet_feature_layers ]) self.iounet_backbone_features = iounet_backbone_features.numpy() # Store the", "self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval()", "fine). use_gpu: Use GPU or CPU. \"\"\" def __init__(self, output_layers=('conv5',", "= self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet18(", "output_features]) return output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List", "path (default should be fine). use_gpu: Use GPU or CPU.", "None: np.savez(debug_save_name, im) im = im / 255. # don't", "**kwargs) self.use_gpu = use_gpu self.net_path = net_path def initialize(self): with", "self.pool_stride == 1: self.pool_stride = [1] * len(self.output_layers) self.feature_layers =", "'fc': None } self.layer_dim = { 'conv0': 64, 'conv1': 64,", "which are input to estimator output = TensorList([layer.numpy() for layer", "state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor = self.net.bb_regressor self.layer_stride", "1, 1]) def free_memory(self): if hasattr(self, 'net'): del self.net if", "'block0': 256, 'block1': 512, 'block2': 1024, 'block3': 2048, 'classification': 256,", "self.use_gpu = use_gpu self.net_path = net_path def initialize(self): with fluid.dygraph.guard():", "'conv0': 64, 'conv1': 64, 'block0': 64, 'block1': 128, 'block2': 256,", "0.224, 0.225], [1, -1, 1, 1]) def free_memory(self): if hasattr(self,", "'block3': 32, 'classification': 16, 'fc': None } self.layer_dim = {", "self.target_estimator if hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features def dim(self): return TensorList([self.layer_dim[l]", "hasattr(self, 'iounet_features'): del self.iounet_features def dim(self): return TensorList([self.layer_dim[l] for l", "def free_memory(self): if hasattr(self, 'net'): del self.net def extract(self, im:", "os import numpy as np from paddle import fluid from", "1]) self.std = np.reshape([0.229, 0.224, 0.225], [1, -1, 1, 1])", "output_features = self.net.extract_features(im, self.feature_layers) # Store the raw resnet features", "SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self):", "{ 'conv0': 64, 'conv1': 64, 'block0': 64, 'block1': 128, 'block2':", "in self.output_layers ]) return output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args:", "output class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args: output_layers: List of layers", "raw resnet features which are input to iounet iounet_backbone_features =", "**kwargs): super().__init__(*args, **kwargs) self.use_gpu = use_gpu self.net_path = net_path def", "256, 'block1': 512, 'block2': 1024, 'block3': 2048, 'classification': 256, 'fc':", "self.feature_layers) # Store the raw backbone features which are input", "64, 'conv1': 64, 'block0': 256, 'block1': 512, 'block2': 1024, 'block3':", "= atom_resnet50( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm)", "return output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of", "output_features]) return output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List", "return output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of", "with fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full = self.net_path else: net_path_full =", "= [1] * len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.iounet_feature_layers)))", "= os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _ =", "64, 'conv1': 64, 'block0': 64, 'block1': 128, 'block2': 256, 'block3':", "ltr.models.siamese.siam import siamfc_alexnet from ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from", "self.estimator_feature_layers))) self.mean = np.reshape([0., 0., 0.], [1, -1, 1, 1])", "'classification': 256, 'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer if isinstance(self.pool_stride,", "Use GPU or CPU. \"\"\" def __init__(self, net_path='estimator', use_gpu=True, *args,", "64, 'block1': 128, 'block2': 256, 'block3': 512, 'classification': 256, 'fc':", "output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of layers", "np.savez(debug_save_name, im) im = im / 255. # don't use", "= sorted( list(set(self.output_layers + self.estimator_feature_layers))) self.mean = np.reshape([0., 0., 0.],", "self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet18( backbone_pretrained=False,", "input to estimator estimator_backbone_features = TensorList([ output_features[layer] for layer in", "self.mean = np.reshape([0.485, 0.456, 0.406], [1, -1, 1, 1]) self.std", "<reponame>weiwei1115/models import os import numpy as np from paddle import", "don't use im /= 255. since we don't want to", "2048, 'classification': 256, 'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer if", "debug_save_name is not None: np.savez(debug_save_name, im) im = im /", "def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name is", "for layer in self.output_layers ]) return output class ResNet50(MultiFeatureBase): \"\"\"ResNet50", "SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self):", "256, 'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer if isinstance(self.pool_stride, int)", "or CPU. \"\"\" def __init__(self, net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args,", "CPU. \"\"\" def __init__(self, output_layers=('conv5', ), net_path='estimator', use_gpu=True, *args, **kwargs):", "which are input to iounet iounet_backbone_features = TensorList([ output_features[layer] for", "]) return output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List", "layer in output_features]) return output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args:", "absolute net path (default should be fine). use_gpu: Use GPU", "\"\"\"ResNet50 feature. args: output_layers: List of layers to output. net_path:", "im /= 255. since we don't want to alter the", "self.output_layers]) def stride(self): return TensorList([ s * self.layer_stride[l] for l,", "list(set(self.output_layers + self.estimator_feature_layers))) self.mean = np.reshape([0., 0., 0.], [1, -1,", "if hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features if hasattr(self, 'iounet_features'): del self.iounet_features", "SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers: List of layers to output.", "self.net_path) self.net = atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ =", "np from paddle import fluid from ltr.models.bbreg.atom import atom_resnet50, atom_resnet18", "GPU or CPU. \"\"\" def __init__(self, output_layers=('block2', ), net_path='atom_iou', use_gpu=True,", "'block1': 512, 'block2': 1024, 'block3': 2048, 'classification': 256, 'fc': None", "0.406], [1, -1, 1, 1]) self.std = np.reshape([0.229, 0.224, 0.225],", "[1] * len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.iounet_feature_layers))) self.mean", "self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True)", "**kwargs) self.output_layers = list(output_layers) self.use_gpu = use_gpu self.net_path = net_path", "if hasattr(self, 'net'): del self.net if hasattr(self, 'target_estimator'): del self.target_estimator", "net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True)", "stride(self): return TensorList([ s * self.layer_stride[l] for l, s in", "atom_resnet18 from ltr.models.siamese.siam import siamfc_alexnet from ltr.models.siam.siam import SiamRPN_AlexNet, SiamMask_ResNet50_sharp,", "self.net def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard(): if debug_save_name", "'block2': 1024, 'block3': 2048, 'classification': 256, 'fc': None } self.iounet_feature_layers", "1 / 255., 1 / 255.], [1, -1, 1, 1])", "len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers + self.iounet_feature_layers))) self.mean = np.reshape([0.485,", "else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True,", "= {'conv5': 256} self.estimator_feature_layers = self.net.target_estimator_layer if isinstance(self.pool_stride, int) and", "255.], [1, -1, 1, 1]) def free_memory(self): if hasattr(self, 'net'):", "SiamMask_ResNet50_sharp, SiamMask_ResNet50_base from pytracking.admin.environment import env_settings from pytracking.features.featurebase import MultiFeatureBase", "512, 'classification': 256, 'fc': None } self.iounet_feature_layers = self.net.bb_regressor_layer if", "-1, 1, 1]) self.std = np.reshape([0.229, 0.224, 0.225], [1, -1,", "'net'): del self.net if hasattr(self, 'target_estimator'): del self.target_estimator if hasattr(self,", "sorted( list(set(self.output_layers + self.iounet_feature_layers))) self.mean = np.reshape([0.485, 0.456, 0.406], [1,", "255. # don't use im /= 255. since we don't", "in self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output = TensorList([ output_features[layer].numpy() for layer", "to estimator estimator_backbone_features = TensorList([ output_features[layer] for layer in self.estimator_feature_layers", "= np.reshape([0.485, 0.456, 0.406], [1, -1, 1, 1]) self.std =", "self.net = atom_resnet18( backbone_pretrained=False, backbone_is_test=True, iounet_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full)", "use_gpu: Use GPU or CPU. \"\"\" def __init__(self, net_path='estimator', use_gpu=True,", "output. net_path: Relative or absolute net path (default should be", "GPU or CPU. \"\"\" def __init__(self, output_layers=('conv5', ), net_path='estimator', use_gpu=True,", "self.output_layers ]) return output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers:", "\"\"\"Resnet50-dilated feature. args: output_layers: List of layers to output. net_path:", "args: output_layers: List of layers to output. net_path: Relative or", "= self.net.bb_regressor_layer if isinstance(self.pool_stride, int) and self.pool_stride == 1: self.pool_stride", "from iounet, just before pooling self.iounet_features = TensorList([ f.numpy() for", "output class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of layers", "zip(self.output_layers, self.pool_stride) ]) def extract(self, im: np.ndarray, debug_save_name=None): with fluid.dygraph.guard():", "self.net.extract_features(im, self.feature_layers) # Store the raw backbone features which are", "*args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu = use_gpu self.net_path = net_path", "Use GPU or CPU. \"\"\" def __init__(self, output_layers=('block2', ), net_path='atom_iou',", "self.output_layers ]) return output class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args: output_layers:", "GPU or CPU. \"\"\" def __init__(self, net_path='estimator', use_gpu=True, *args, **kwargs):", "self.net_path = net_path def initialize(self): with fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full", "'iou_predictor'): del self.iou_predictor if hasattr(self, 'iounet_backbone_features'): del self.iounet_backbone_features if hasattr(self,", "import TensorList from pytracking.libs.paddle_utils import n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature.", "'conv1': 64, 'block0': 256, 'block1': 512, 'block2': 1024, 'block3': 2048,", "16, 'fc': None } self.layer_dim = { 'conv0': 64, 'conv1':", "None: np.savez(debug_save_name, im) im = n2p(im) output_features = self.net.extract_backbone_features(im) #", "fluid.dygraph.guard(): if debug_save_name is not None: np.savez(debug_save_name, im) im =", "]) output = TensorList([ output_features[layer].numpy() for layer in self.output_layers ])", "1024, 'block3': 2048, 'classification': 256, 'fc': None } self.iounet_feature_layers =", "use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.output_layers = list(output_layers) self.use_gpu =", "im /= self.std im = n2p(im) output_features = self.net.extract_features(im, self.feature_layers)", "in output_features]) return output class SMaskResNet50_sharp(MultiFeatureBase): \"\"\"Resnet50-dilated feature. args: output_layers:", "'iounet_features'): del self.iounet_features def dim(self): return TensorList([self.layer_dim[l] for l in", "if hasattr(self, 'iounet_features'): del self.iounet_features def dim(self): return TensorList([self.layer_dim[l] for", "'conv0': 64, 'conv1': 64, 'block0': 256, 'block1': 512, 'block2': 1024,", "backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dictsm) self.net.train() self.target_estimator", "to iounet iounet_backbone_features = TensorList([ output_features[layer] for layer in self.iounet_feature_layers", "dim(self): return TensorList([self.layer_dim[l] for l in self.output_layers]) def stride(self): return", "layer in self.estimator_feature_layers ]) self.estimator_backbone_features = estimator_backbone_features.numpy( ) output =", "= { 'conv0': 64, 'conv1': 64, 'block0': 256, 'block1': 512,", "import env_settings from pytracking.features.featurebase import MultiFeatureBase from pytracking.libs import TensorList", "TensorList([ f.numpy() for f in self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output =", "f.numpy() for f in self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output = TensorList([", "\"\"\"Alexnet feature. args: output_layers: List of layers to output. net_path:", "self.layer_dim = {'conv5': 256} self.estimator_feature_layers = self.net.target_estimator_layer if isinstance(self.pool_stride, int)", "os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_sharp(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full)", "n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args: output_layers: List of layers", "return output class ResNet50(MultiFeatureBase): \"\"\"ResNet50 feature. args: output_layers: List of", "import n2p class ResNet18(MultiFeatureBase): \"\"\"ResNet18 feature. args: output_layers: List of", "or CPU. \"\"\" def __init__(self, output_layers=('block2', ), net_path='atom_iou', use_gpu=True, *args,", "'block2': 256, 'block3': 512, 'classification': 256, 'fc': None } self.iounet_feature_layers", "32, 'classification': 16, 'fc': None } self.layer_dim = { 'conv0':", "output_features = self.net.extract_features(im, self.feature_layers) # Store the raw backbone features", "np.savez(debug_save_name, im) im = n2p(im) output_features = self.net.extract_backbone_features(im) # Store", "self.output_layers ]) return output class SFCAlexnet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers:", "[1, -1, 1, 1]) self.std = np.reshape([0.229, 0.224, 0.225], [1,", "class SRPNAlexNet(MultiFeatureBase): \"\"\"Alexnet feature. args: output_layers: List of layers to", "self.net.load_dict(state_dictsm) self.net.train() self.iou_predictor = self.net.bb_regressor self.layer_stride = { 'conv0': 2,", "self.pool_stride = [1] * len(self.output_layers) self.feature_layers = sorted( list(set(self.output_layers +", "im = n2p(im) output_features = self.net.extract_features(im, self.feature_layers) # Store the", "= TensorList([ f.numpy() for f in self.iou_predictor.get_iou_feat( iounet_backbone_features) ]) output", "pytracking.admin.environment import env_settings from pytracking.features.featurebase import MultiFeatureBase from pytracking.libs import", "= self.net.extract_features(im, self.feature_layers) # Store the raw resnet features which", "SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self):", "'block1': 128, 'block2': 256, 'block3': 512, 'classification': 256, 'fc': None", "fluid.dygraph.guard(): if os.path.isabs(self.net_path): net_path_full = self.net_path else: net_path_full = os.path.join(env_settings().network_path,", "\"\"\" def __init__(self, output_layers=('block2', ), net_path='atom_iou', use_gpu=True, *args, **kwargs): super().__init__(*args,", "fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self): if hasattr(self, 'net'): del self.net", "net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net = SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _", "if hasattr(self, 'net'): del self.net if hasattr(self, 'iou_predictor'): del self.iou_predictor", "= fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self): if hasattr(self, 'net'): del", "features which are input to estimator output = TensorList([layer.numpy() for", "os.path.join(env_settings().network_path, self.net_path) self.net = siamfc_alexnet( backbone_pretrained=False, backbone_is_test=True, estimator_is_test=True) state_dictsm, _", "List of layers to output. net_path: Relative or absolute net", "= os.path.join(env_settings().network_path, self.net_path) self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _ =", "self.net = SiamRPN_AlexNet(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval()", "import atom_resnet50, atom_resnet18 from ltr.models.siamese.siam import siamfc_alexnet from ltr.models.siam.siam import", "= SiamMask_ResNet50_base(backbone_pretrained=False, is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def", "TensorList([self.layer_dim[l] for l in self.output_layers]) def stride(self): return TensorList([ s", "is_test=True) state_dict, _ = fluid.load_dygraph(net_path_full) self.net.load_dict(state_dict) self.net.eval() def free_memory(self): if", "resnet features which are input to iounet iounet_backbone_features = TensorList([", "self.estimator_backbone_features def dim(self): return TensorList([self.layer_dim[l] for l in self.output_layers]) def", "fine). use_gpu: Use GPU or CPU. \"\"\" def __init__(self, output_layers=('block2',", "self.net.target_estimator_layer if isinstance(self.pool_stride, int) and self.pool_stride == 1: self.pool_stride =", "[1, -1, 1, 1]) self.std = np.reshape([1 / 255., 1", "pooling self.iounet_features = TensorList([ f.numpy() for f in self.iou_predictor.get_iou_feat( iounet_backbone_features)", "TensorList([layer.numpy() for layer in output_features]) return output class SMaskResNet50_base(MultiFeatureBase): \"\"\"Resnet50-dilated", "net path (default should be fine). use_gpu: Use GPU or", "im = n2p(im) output_features = self.net.extract_backbone_features(im) # Store the raw", "import numpy as np from paddle import fluid from ltr.models.bbreg.atom", "def __init__(self, net_path='estimator', use_gpu=True, *args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu =", "im) im = n2p(im) output_features = self.net.extract_backbone_features(im) # Store the", "from pytracking.libs import TensorList from pytracking.libs.paddle_utils import n2p class ResNet18(MultiFeatureBase):", "hasattr(self, 'net'): del self.net def extract(self, im: np.ndarray, debug_save_name=None): with", "s in zip(self.output_layers, self.pool_stride) ]) def extract(self, im: np.ndarray, debug_save_name=None):", "self.net if hasattr(self, 'target_estimator'): del self.target_estimator if hasattr(self, 'estimator_backbone_features'): del", "net_path_full = self.net_path else: net_path_full = os.path.join(env_settings().network_path, self.net_path) self.net =", "def free_memory(self): if hasattr(self, 'net'): del self.net if hasattr(self, 'iou_predictor'):", "+ self.iounet_feature_layers))) self.mean = np.reshape([0.485, 0.456, 0.406], [1, -1, 1,", "if hasattr(self, 'target_estimator'): del self.target_estimator if hasattr(self, 'estimator_backbone_features'): del self.estimator_backbone_features", "processed features from iounet, just before pooling self.iounet_features = TensorList([", "self.net.bb_regressor self.layer_stride = { 'conv0': 2, 'conv1': 2, 'block0': 4,", "+ self.estimator_feature_layers))) self.mean = np.reshape([0., 0., 0.], [1, -1, 1,", "= TensorList([layer.numpy() for layer in output_features]) return output class SMaskResNet50_sharp(MultiFeatureBase):", "CPU. \"\"\" def __init__(self, output_layers=('block2', ), net_path='atom_iou', use_gpu=True, *args, **kwargs):" ]
[ "0.0,' add } def\\n' if axis == 2: print >>self.fout,", "in titleLines: if len(t) > 0: print >>self.flog, ' '+t", "'endFunction\\n' print >>self.fout, '18 { 0.72 0.52 0.5 setrgbcolor }", "self.fout.write(' ]') if ztitle != '': print >>self.fout, '('+ztitle+') vaxis2'", "' -g1200x1100 ' cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE", "= math.modf(v0Log) if math.fabs(ff[0]) < math.fabs(v0Log)/1000 and t < 0:", "') self.fout.write(' ]') if ztitle != '': print >>self.fout, '('+ztitle+')", "1 while w/f >= 100: f *= 10 # w", "indx += 1 p.SetPlot(tMin, tMax, 0, 0, 2, 0, 'Time',", "'/dev/null' #logFile = 'plot.log' #--- class PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage)", "'+str(color[1])+' '+str(color[2])+ \\ ' setrgbcolor } ' return rv #---", "tMax = int(sys.argv[2]) fname = sys.argv[3] elif len(sys.argv) != 1:", "1: logOffset += 1 t += 1 v0 = math.pow(10,math.floor(v0Log)+1)", "== 0: v0,v1,vi = self.GetInc(vBeg,vEnd) else: v0 = vBeg v1", "if (v0 >= 0) and (v0 % m) != 0:", "#--- SeriesNames(names) # def SeriesNames(self, names): indx = len(names) -", "'/showpage {\\n 40 742 moveto' print >>self.fout, '/Helvetica findfont 12", "= math.log10(v0) t = math.ceil(v0Log) ff = math.modf(v0Log) if math.fabs(ff[0])", "(',vEnd,')' print >>self.flog, 'vList: ', vList print >>self.flog, 'logFlag: ',", "6.5 #inches self.seriesTitle = ' ' self.x0 = 0 self.xInc", "+ 'G' elif v >= 1000000 and inc > 1:", "+ ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res +self.fname+' -c quit' #", "'showpage\\n} bind def' print >>self.fout, 'doGraph' #--- End() # def", "SeriesNames(names) # def SeriesNames(self, names): indx = len(names) - 1", "print >>self.fout, '40 726 moveto\\n (',self.pageSubHeader,') show' print >>self.fout, 'showpage\\n}", "outputPS(string) # def outputPS(self, s): print >>self.fout, s #--- SeriesNames(names)", "#--- SetColor(color) # def SetColor(self, color): rv = ' {", "= int(s) r = str(s) + 'K' elif v >=", "'('+self.seriesTitle+')' while indx >= 0: if names[indx] != None: print", "print >>self.fout, 'endFunction\\n' print >>self.fout, '18 { 0.72 0.52 0.5", "return #--- SetPlotBgLevel(level) # def SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel ',", "= '{ '+str(v0-vi)+' sub '+str(vi)+' div }' logFlag = 0", "'+str(v0-vi)+' sub '+str(vi)+' div }' logFlag = 0 else: if", "'Off': v = -1 elif value == 'On': v =", "+= 1 v = v0 + n*vi fix = '{", "'logFlag: ', logFlag, ' fix: ', fix return v0,v1,vi,vList,fix,logFlag #---", "def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc = yi self.y1Count =", "SetColorIndx(indx, r, g, b) # def SetColorIndx(self, indx, r, g,", "= v0 while v <= v1: vList.append(self.ValueConvert(v,0)) v *= 10", "else: vInc = m else: vInc = m # if", "+ ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' print >>flog,", "'('+ztitle+') vaxis2' if logFlag == 1: print >>self.fout, self.yfix2 print", "len(xList)-1: continue if len(yList) <= indx: continue y = yList[indx]", "self.pageSubHeader != '': print >>self.fout, '40 726 moveto\\n (',self.pageSubHeader,') show'", "== 'K': zss = zs[:-1] factor = 1000 elif zs[-1:]", "/ 550) res = ' -r%dx%d ' % (xres, yres)", "inputLine.replace(' ','') inputLine = inputLine.replace(\"'\", '') i1 = inputLine.find('(') i2", "1 w = v1 - v0 if w <= 10:", "#--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag)", "sys.stdout) state += 1 image = p.GetImage(sys.stdout) print 'Image file:", "def SetColorIndx(self, indx, r, g, b): self.colors[indx][0] = r self.colors[indx][1]", "= plotsPerPage self.yfix1 = '' self.yfix2 = '' self.xGrid =", "'Image file: ', image p.End() if __name__ == \"__main__\": main()", "setrgbcolor } plotSymbolsC\\n' return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) #", "% 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout, x", "2, 0, 'Time', 'Socket/State', 'Chavey\\'s Plot') state = 0 while", ">>self.fout, x, 0.0 if (indx != 0) and (indx %", "setrgbcolor } ' return rv #--- SetColorIndx(indx, r, g, b)", "0: v1 = v0 + 1 w = 1 while", "z = zList[indx] else: z = '' indx += 1", "True: g_indx = self.xDict[x] print >>self.fout, g_indx, y, z else:", "math.pow(10,logInc) if d == 0: d = 10.0 else: d", "vList = vBeg vList.append(' ') self.xUniform = True v0 =", "= open(logFile, 'a') # self.flog = open('./psPlot.out', 'a') if plotsPerPage", "else: self.y2LogScale = v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title):", "(0,0.8,0) self.colorBlue = (0,0,0.8) self.colorAqua = (0,0.5,0.5) self.colorWhite = (1,1,1)", "0) and (v0 % m) != 0: v0 = int(v0", "1 w = 1 while w/f >= 100: f *=", ">>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout, x print >>self.fout, endFun, type, '\\n'", "while indx >= 0: if names[indx] != None: print >>self.fout,", "vBeg v1 = vEnd logFlag = 1 v0Log = math.log10(v0)", ">>self.fout, '/doGraph { graph4v } def' print >>self.fout, '/nextGraph {", "self.x0 = x0 self.xInc = xi self.xCount = len(xList) self.xList", "ys[:-1] factor = 1000000 else: yss = ys y =", "if self.foutPath == '/': self.foutPath = '' self.foutName = os.path.basename(fname)", "yList, zList, id, type) # def PlotData(self, axis, xList, yList,", "self.flog print >>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout) if self.plotsPerPage == 1:", "= (0,0.5,0.5) self.colorWhite = (1,1,1) self.ColorBlack = (0,0,0) self.xSize =", "!= '': print >>self.fout, '40 726 moveto\\n (',self.pageSubHeader,') show' print", "r = str(int(v*100)/100.0) return r #--- GetAxis(vBeg, vEnd, vInc, logFlag)", "v0 > 1: logOffset -= (math.log10(v0) - 1) # substract", "0 and t >= tMin and t <= tMax: fromStateList.append(s1)", "== 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout, x print >>self.fout,", "# def outputPS(self, s): print >>self.fout, s #--- SeriesNames(names) #", "xList, yList, zList, id, type) # def PlotData(self, axis, xList,", "python2 import sys import random import os.path import shutil import", "' '+t print >>self.fout, '('+t+')\\n' print >>self.fout, 'Mtitles\\n' # print", "= sys.argv[3] elif len(sys.argv) != 1: print 'USAGE: psPlot.py [tMin", "and inc > 1: s = int(v/(1000/d))/d if s*d ==", "= zs[:-1] factor = 1000 elif zs[-1:] == 'M': zss", "SetYSize(ysize) def SetYSize(self, ysize): self.ySize = ysize return #--- SetPlotBgLevel(level)", "and indx == len(xList)-1: continue if len(yList) <= indx: continue", ">>self.fout, '/Helvetica findfont 12 scalefont setfont' if self.pageHeader != '':", ">>self.fout, self.xGrid, self.yGrid, ' grid\\n' print >>self.fout, '/ymtitle ypos ylen", "{ '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ ' setrgbcolor } ' return", "1800 self.ySize = 900 shutil.copy('plot-header.ps', self.fname) self.fout = open(self.fname, 'a')", "= self.xDict[x] print >>self.fout, g_indx, y, z else: print >>self.fout,", "= len(names) - 1 if indx == 0: return print", "s2 = stateList[int(inputList[1])] t = int(inputList[2]) if indx != 0", "{ 0.72 0.52 0.5 setrgbcolor } plotSymbolsC\\n' return rv #---", "plotsPerPage == 3: print >>self.fout, '/doGraph { graph3v } def'", "= ' -g1200x550 ' size = ' -g%dx%d ' %", "None: print >>self.fout, '('+names[indx]+') ' print >>self.fout, self.SetColor(self.colors[indx % self.colorsN])", "return #--- GetImage() # def GetImage(self): flog = self.flog print", "t2List.append(time2List[indx]) sList.append(0.10 + s*0.20) indx += 1 p.PlotData(1,t1List, t2List, sList,", "= 10.0 if d == 1 and float(v)/inc > 1.0:", "'': print >>self.fout, '(',self.pageHeader,') show' if self.pageSubHeader != '': print", "vInc if vBeg > 0 and (logFlag==1 or (logFlag==0 and", "len(yList) self.yfix1 = '/yfix '+fix+' def\\n /yinc yinc1 def' print", "p = PsPlot('./p', 'Header', 'SubHeader', 1) fromStateList = [] toStateList", "1 def\\n' else: print >>self.fout, '/plotNumPercentDir 0 def\\n' return #---", "and (vEnd/vBeg > 100))): v0 = vBeg v1 = vEnd", "self.y1LogScale = 0 self.y2Inc = 0 self.y2Count = 0 self.y2LogScale", "', tMin, tMax, 'fname: ', fname p = PsPlot('./p', 'Header',", "= os.path.basename(fname) self.fname = fname+'.ps' self.pageHeader = pageHeader self.pageSubHeader =", "100000 stateList = [0,1,2,2,3,3,3,3,4] fname = 'sched.txt' if len(sys.argv) ==", "= 1 v0Log = math.log10(v0) t = math.ceil(v0Log) ff =", "while vMax <= 1 and vMax > 0: ff *=", "= pageSubHeader self.plotsPerPage = plotsPerPage self.yfix1 = '' self.yfix2 =", "xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi", "k*y k += 1 print >>self.fout, 'endFunction\\n' print >>self.fout, '19", "= m/2 else: vInc = m else: vInc = m", "v = v0 vList = [] n = 0 while", "-sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' print >>flog, 'cmdStr: ',", "v1 = math.pow(10,math.ceil(math.log10(v1))) vi = 1 vList = [] v", "1) # substract 1 from above inside parent? fix =", "logOffset += 1 t += 1 v0 = math.pow(10,math.floor(v0Log)+1) v1", "else: zss = zs y = float(zss)*factor/10.0 k = 2", "if w == 0: v1 = v0 + 1 w", "1 t += 1 v0 = math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1)))", "zss = zs y = float(zss)*factor/10.0 k = 2 while", "print >>self.fout, self.xCount, k*y k += 1 print >>self.fout, 'endFunction\\n'", "yList[indx] if isinstance(zList,list): if len(zList) <= indx: continue z =", "', self.xList, ' xList: ', xList, \\ ' yList: ',", "= [] t2List = [] sList = [] indx =", "0: v1 = int(v1 / m) * m + m", "'('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid, self.yGrid, ' grid\\n' print >>self.fout, '/ymtitle", "v0 if w <= 5*m: vInc = m/2 else: vInc", "factor = 1000000 else: yss = ys y = float(yss)*factor/10.0", "self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi self.y2Count = len(zList) print >>self.fout, '/Flag2Yaxes", "ys[:-1] factor = 1000 elif ys[-1:] == 'M': yss =", "return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def SetXLen(self, xlen): self.xLen = xlen", "fix = '{ dup 0 eq { } { log", "b): self.colors[indx][0] = r self.colors[indx][1] = g self.colors[indx][2] = b", "div }' logFlag = 0 else: if vInc == 0:", "else: d = 10.0 if d == 1 and float(v)/inc", "print 'USAGE: psPlot.py [tMin tMax] [fname]' sys.exit(1) print 'tMin,tMax: ',", "self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0 self.xInc = xi self.xCount = len(xList)", "n*vi fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div }' print", "SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value): if value == 'Off': v =", "Main # def main(): tMin = 0 tMax = 100000", "-g%dx%d ' % (self.xSize, self.ySize) xres = int(100 * self.xSize", "self.foutPath == '/': self.foutPath = '' self.foutName = os.path.basename(fname) self.fname", "tMin and t <= tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime", "'endFunctionW\\n' else: endFun = 'endFunction\\n' indx = 0 for x", "1 v1 = len(vList) vi = 1 fix = '{", "or (logFlag==0 and (vEnd/vBeg > 100))): v0 = vBeg v1", "len(sys.argv) != 1: print 'USAGE: psPlot.py [tMin tMax] [fname]' sys.exit(1)", "'doGraph' #--- End() # def End(self): print >>self.fout, '\\nshowpage\\nend' self.fout.close()", "elif w <= 20: vInc = 2 else: m =", "-dNOPAUSE -r100x100 '+self.fname+' -c quit' print >>flog, 'cmdStr: ', cmdStr", "add def\\n' # Multiple lines in title are separated by", "'/doGraph { graph4v } def' print >>self.fout, '/nextGraph { nextGraph4v", "shutil import commands import types import math #gsPath = '/usr/local/bin/gs'", "self.xUniform = False self.xLen = 6.5 #inches self.seriesTitle = '", "(x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0 self.xInc = xi self.xCount", "return #--- SetXSize(xsize) def SetXSize(self, xsize): self.xSize = xsize return", "indx == len(xList)-1: continue indx += 1 print >>self.fout, x,", "inc > 1: s = int(v/(1000000/d))/d if s*d == int(s)*d:", "logFlag == 1: print >>self.fout, 'beginFunction\\n' for ys in yList:", "findfont 12 scalefont setfont' if self.pageHeader != '': print >>self.fout,", "in yList: self.fout.write('('+str(y)+') ') print >>self.fout, ' ]' print >>self.fout,", "self.colors[indx % self.colorsN] rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+", "True: print >>self.fout, g_indx, y, z else: print >>self.fout, x,", "(0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ] self.colorsN = 11 self.colorRed = (0.8,0,0)", "y = float(yss)*factor/10.0 k = 2 while k < 10:", "= int(sys.argv[2]) fname = sys.argv[3] elif len(sys.argv) != 1: print", "= int(v1/f) if (vMin % f) != 0 and vMax", "for s in toStateList: if s == state: t1List.append(time1List[indx]) t2List.append(time2List[indx])", "1: s = int(v*d)/d if s*d == int(s)*d: s =", "indx -= 1 print >>self.fout, 'fdescriptionsC' #--- PlotVBars(xList, type) #", "#--- GetAxis(vBeg, vEnd, vInc, logFlag) # def GetAxis(self, vBeg, vEnd,", "= 0 while t < 1: logOffset += 1 t", "10.0 else: d = 10.0 if d == 1 and", "(vEnd/vBeg > 100))): v0 = vBeg v1 = vEnd logFlag", "if vBeg > 0 and (logFlag==1 or (logFlag==0 and (vEnd/vBeg", "fname, pageHeader, pageSubHeader, plotsPerPage): self.foutPath = os.path.dirname(fname)+'/' if self.foutPath ==", "inc > 1: s = int(v/(1000000000/d))/d if s*d == int(s)*d:", "xi self.xCount = len(xList) self.xList = xList self.xDict = {}", "'a') if plotsPerPage == 4: print >>self.fout, '/doGraph { graph4v", "= 'sched.txt' if len(sys.argv) == 2: fname = sys.argv[1] elif", "[] time2List = [] indx = 0 oldTime = 0", ">>self.fout, '/showpage {\\n 40 742 moveto' print >>self.fout, '/Helvetica findfont", "self.foutPath = '' self.foutName = os.path.basename(fname) self.fname = fname+'.ps' self.pageHeader", "10.0 if d == 1 and float(v)/inc > 1.0: d", "int(s)*d: s = int(s) r = str(s) + 'K' elif", "self.pageHeader != '': print >>self.fout, '(',self.pageHeader,') show' if self.pageSubHeader !=", "vInc *= (f*ff) return v0, v1, vInc #--- ValueConvert(v) #", "'(',self.pageHeader,') show' if self.pageSubHeader != '': print >>self.fout, '40 726", "t1List = [] t2List = [] sList = [] indx", ">>self.fout, '/yfix { 0 add } def\\n' print >>self.fout, 'beginFunction\\n'", "= [0,1,2,2,3,3,3,3,4] fname = 'sched.txt' if len(sys.argv) == 2: fname", "'[ ' for x in xList: self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[", "while k < 10: print >>self.fout, 0, k*y k +=", "if isinstance(zList,list): endFun = 'endFunctionW\\n' else: endFun = 'endFunction\\n' indx", "v *= 10 if v0 > 1: logOffset -= (math.log10(v0)", "self.y2Count = 0 self.y2LogScale = 0 self.xOffset = 0 self.colors", "self.xInc = xi self.xCount = len(xList) self.xList = xList self.xDict", "print >>self.fout, '19 { 0 0 0 setrgbcolor } plotSymbolsC\\n'", "tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) elif len(sys.argv) == 4:", "GetAxis(vBeg, vEnd, vInc, logFlag) # def GetAxis(self, vBeg, vEnd, vInc,", "logFlag, ' fix: ', fix return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def", "20: vInc = 2 else: m = 10 while w/m", "and vMax == v1: v1 += 1 w = v1", "d == 1 and float(v)/inc > 1.0: d = 10.0", "print >>self.fout, 'showpage\\n} bind def' print >>self.fout, 'doGraph' #--- End()", "ylen add 10 add def\\n' # Multiple lines in title", "yres) cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res", "' return rv #--- SetColorIndx(indx, r, g, b) # def", "= [] toStateList = [] time1List = [] time2List =", "v0 while v <= v1: vList.append(self.ValueConvert(v,0)) v *= 10 if", "m = 10 while w/m > 100: m *= 10", "' yList: ', yList print >>self.fout, '%\\n% Plot '+id+'\\n%\\n' print", "logFlag = 0 else: if vInc == 0: v0,v1,vi =", "print >>self.fout, ' ]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid,", "1: print >>self.fout, self.yfix1 # else: # print >>self.fout, '/yfix", ">>self.fout, '/doGraph { graph1v } def' print >>self.fout, '/nextGraph {", "def\\n/yinc yinc2 def' print >>self.fout, 'axpos axlen add aypos aylen'", "[fname]' sys.exit(1) print 'tMin,tMax: ', tMin, tMax, 'fname: ', fname", "def' self.yfix2 = '/yfix '+fix+' def\\n/yinc yinc2 def' print >>self.fout,", "rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi self.y2Count", "ztitle != '': print >>self.fout, '('+ztitle+') vaxis2' if logFlag ==", "int(v*d)/d if s*d == int(s)*d: s = int(s) r =", "'axpos axlen add aypos aylen' self.fout.write('[ ') for z in", "(v0 % vInc) != 0: v0 = int(v0/vInc)*vInc v0 +=", "vInc, logFlag): fix = '{ 0 add }' if isinstance(vBeg,list):", "= 10.0 else: d = 10.0 if d == 1", "PlotData(axis, xList, yList, zList, id, type) # def PlotData(self, axis,", "while k < 10: print >>self.fout, self.xCount, k*y k +=", "2 while k < 10: print >>self.fout, 0, k*y k", "f) != 0 and vMax == v1: v1 += 1", "state = 0 while state <= 4: t1List = []", "'K': yss = ys[:-1] factor = 1000 elif ys[-1:] ==", "v >= 1000000 and inc > 1: s = int(v/(1000000/d))/d", "self.flog = open('./psPlot.out', 'a') if plotsPerPage == 4: print >>self.fout,", "'+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ ' setrgbcolor } ' return rv", "os.path import shutil import commands import types import math #gsPath", "type, '\\n' return #--- PlotData(axis, xList, yList, zList, id, type)", "1 v = v0 + n*vi fix = '{ '+str(v0-vi)+'", ">>self.fout, self.yfix2 elif axis == 1: print >>self.fout, self.yfix1 #", "if value == 'Vertical': print >>self.fout, '/plotNumPercentDir 1 def\\n' else:", "plotWbarsC', sys.stdout) state += 1 image = p.GetImage(sys.stdout) print 'Image", "'/plotNumPercentDir 0 def\\n' return #--- SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value): if", "= 10.0 if v >= 1000000000 and inc > 1:", "1000 and inc > 1: s = int(v/(1000/d))/d if s*d", "= zList[indx] else: z = '' indx += 1 if", "print >>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')' print >>self.flog, 'vList: ',", "r = str(s) + 'G' elif v >= 1000000 and", "vBeg > 0 and (logFlag==1 or (logFlag==0 and (vEnd/vBeg >", "1 print >>self.fout, x, 0.0 if (indx != 0) and", "inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])] s2 = stateList[int(inputList[1])]", "= inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])] s2 = stateList[int(inputList[1])] t =", "logFlag == 1: print >>self.fout, self.yfix2 print >>self.fout, 'beginFunction\\n' for", "= 1 self.xUniform = False self.xLen = 6.5 #inches self.seriesTitle", "<= 1 and vMax > 0: ff *= 0.10 vMin", "t += 1 logOffset = 0 while t < 1:", ">>self.fout, '\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin, vMax) def GetInc(self,vMin, vMax): ff", "= xsize return #--- SetYSize(ysize) def SetYSize(self, ysize): self.ySize =", "vBeg vList.append(' ') self.xUniform = True v0 = 1 v1", "# def PlotData(self, axis, xList, yList, zList, id, type): flog", "cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res +self.fname+'", "t indx += 1 p.SetPlot(tMin, tMax, 0, 0, 2, 0,", "self.xGrid, self.yGrid, ' grid\\n' print >>self.fout, '/ymtitle ypos ylen add", "print >>self.fout, '18 { 0.72 0.52 0.5 setrgbcolor } plotSymbolsC\\n'", "= 2 else: m = 10 while w/m > 100:", "zs[:-1] factor = 1000 elif zs[-1:] == 'M': zss =", "tMax = int(sys.argv[2]) elif len(sys.argv) == 4: tMin = int(sys.argv[1])", "= int(v1/vInc)*vInc + vInc if (v0 % vInc) != 0:", "== 4: tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) fname =", "1 and vMax > 0: ff *= 0.10 vMin *=", "z in zList: self.fout.write('('+str(z)+') ') self.fout.write(' ]') if ztitle !=", "import types import math #gsPath = '/usr/local/bin/gs' gsPath = 'gs'", ">>self.flog, ' '+t print >>self.fout, '('+t+')\\n' print >>self.fout, 'Mtitles\\n' #", "1: logOffset -= (math.log10(v0) - 1) # substract 1 from", "* m + m w = v1 - v0 if", "+= 1 logOffset = 0 while t < 1: logOffset", "v, inc): if inc > 0: logInc = int(math.log10(v/inc)) d", "w = int(w/f) v0 = int(v0/f) v1 = int(v1/f) if", "vInc) != 0: v0 = int(v0/vInc)*vInc v0 += vInc v0", "import commands import types import math #gsPath = '/usr/local/bin/gs' gsPath", "= commands.getoutput(cmdStr) print >>flog, 'output from gs command: ', output", "'USAGE: psPlot.py [tMin tMax] [fname]' sys.exit(1) print 'tMin,tMax: ', tMin,", "12 scalefont setfont' if self.pageHeader != '': print >>self.fout, '(',self.pageHeader,')", "= self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi self.y2Count = len(zList) print >>self.fout,", "p.GetImage(sys.stdout) print 'Image file: ', image p.End() if __name__ ==", "vInc = 1 elif w <= 20: vInc = 2", "k < 10: print >>self.fout, 0, k*y k += 1", "continue y = yList[indx] if isinstance(zList,list): if len(zList) <= indx:", "and (indx % 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' if", "else: r = str(int(v*100)/100.0) return r #--- GetAxis(vBeg, vEnd, vInc,", "% (xres, yres) cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE", "'/plotBgLevel ', level, 'def\\n' return #--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if", "x in xList: self.xDict[x] = k k=k+1 print >>self.fout, '/xfix", "add } ifelse }' else: logFlag = 0 v =", "GetColorIndx(indx) # def GetColorIndx(self, indx): color = self.colors[indx % self.colorsN]", "while state <= 4: t1List = [] t2List = []", "'/xAxisLen %.2f def' % self.xLen print >>self.fout, 'doGraph' return #---", "indx = len(names) - 1 if indx == 0: return", "-r100x100 '+self.fname+' -c quit' else: size = ' -g1200x1100 '", "def GetColorIndx(self, indx): color = self.colors[indx % self.colorsN] rv =", "t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 + s*0.20) indx += 1 p.PlotData(1,t1List, t2List,", "print >>flog, 'graph xList: ', self.xList, ' xList: ', xList,", "1 w = v1 - v0 if w == 0:", "v0 += vInc v0 *= (f*ff) v1 *= (f*ff) vInc", "== 1: print >>self.fout, self.yfix1 # else: # print >>self.fout,", "self.foutPath = os.path.dirname(fname)+'/' if self.foutPath == '/': self.foutPath = ''", "self.colorsN = 11 self.colorRed = (0.8,0,0) self.colorGreen = (0,0.8,0) self.colorBlue", "inputList = inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])] s2 = stateList[int(inputList[1])] t", "else: # print >>self.fout, '/yfix { 0 add } def\\n'", "#--- End() # def End(self): print >>self.fout, '\\nshowpage\\nend' self.fout.close() #---", "= self.colors[indx % self.colorsN] rv = ' { '+str(color[0])+' '+str(color[1])+'", "#--- Main # def main(): tMin = 0 tMax =", "3: tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) elif len(sys.argv) ==", "< 10: print >>self.fout, self.xCount, k*y k += 1 print", "SetPlotPercentDir(self,value): if value == 'Vertical': print >>self.fout, '/plotNumPercentDir 1 def\\n'", "v >= 1: s = int(v*d)/d if s*d == int(s)*d:", "gsPath = 'gs' logFile = '/dev/null' #logFile = 'plot.log' #---", "SetXLen(self, xlen): self.xLen = xlen print >>self.fout, '/xAxisLen %.2f def'", "= math.pow(10,logInc) if d == 0: d = 10.0 else:", "- 1) # substract 1 from above inside parent? fix", "0) and (indx % 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n'", "2: print >>self.fout, self.yfix2 elif axis == 1: print >>self.fout,", "def\\n' # Multiple lines in title are separated by '|'", "self.yfix2 = '/yfix '+fix+' def\\n/yinc yinc2 def' print >>self.fout, 'axpos", "v0 + n*vi fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div", "toStateList = [] time1List = [] time2List = [] indx", "'/doGraph { graph3v } def' print >>self.fout, '/nextGraph { nextGraph3v", "fname+'.ps' self.pageHeader = pageHeader self.pageSubHeader = pageSubHeader self.plotsPerPage = plotsPerPage", "'('+t+')\\n' print >>self.fout, 'Mtitles\\n' # print >>self.fout, '('+title+')\\nMtitles\\n' if logFlag", "print >>self.fout, self.yfix2 print >>self.fout, 'beginFunction\\n' for zs in zList:", "self.fname = fname+'.ps' self.pageHeader = pageHeader self.pageSubHeader = pageSubHeader self.plotsPerPage", "{ log '+str(logOffset)+' add } ifelse }' else: logFlag =", "!= 0 and vMax == v1: v1 += 1 w", "<= 4: t1List = [] t2List = [] sList =", "= 'endFunctionW\\n' else: endFun = 'endFunction\\n' indx = 0 for", "100: m *= 10 if (v0 >= 0) and (v0", "self.xList = [] self.xDict = {} self.y1Inc = 0 self.y1Count", "(xres, yres) cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+", "self.plotsPerPage == 1: # size = ' -g1200x550 ' size", "open('./psPlot.out', 'a') if plotsPerPage == 4: print >>self.fout, '/doGraph {", "'Time', 'Socket/State', 'Chavey\\'s Plot') state = 0 while state <=", "} def' print >>self.fout, '/nextGraph { nextGraph1v } def' print", "ys y = float(yss)*factor/10.0 k = 2 while k <", "m else: vInc = m # if (vMax/f)%vInc != 0", "if v1 % vInc != 0: v1 = int(v1/vInc)*vInc +", "self.xSize = 1800 self.ySize = 900 shutil.copy('plot-header.ps', self.fname) self.fout =", "math.fabs(ff[0]) < math.fabs(v0Log)/1000 and t < 0: t += 1", "'/doGraph { graph2v } def' print >>self.fout, '/nextGraph { nextGraph2v", "indx: continue y = yList[indx] if isinstance(zList,list): if len(zList) <=", "= xi self.xCount = len(xList) self.xList = xList self.xDict =", "} def' elif plotsPerPage == 2: print >>self.fout, '/doGraph {", "(0,0.5,0.5) self.colorWhite = (1,1,1) self.ColorBlack = (0,0,0) self.xSize = 1800", "r, g, b) # def SetColorIndx(self, indx, r, g, b):", "print >>self.fout, 'beginFunction\\n' if isinstance(zList,list): endFun = 'endFunctionW\\n' else: endFun", "int(sys.argv[2]) elif len(sys.argv) == 4: tMin = int(sys.argv[1]) tMax =", "== ' ' and indx == len(xList)-1: continue indx +=", "0, 2, 0, 'Time', 'Socket/State', 'Chavey\\'s Plot') state = 0", "if axis == 1: self.y1LogScale = v else: self.y2LogScale =", "for y in yList: self.fout.write('('+str(y)+') ') print >>self.fout, ' ]'", ">>self.fout, 'axpos axlen add aypos aylen' self.fout.write('[ ') for z", "= int(s) r = str(s) + 'M' elif v >=", "fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div }' print >>self.flog,", "' ' self.x0 = 0 self.xInc = 0 self.xCount =", "% f) != 0 and vMax == v1: v1 +=", "(0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ] self.colorsN", "1 image = p.GetImage(sys.stdout) print 'Image file: ', image p.End()", "g_indx = self.xDict[x] print >>self.fout, g_indx, y, z else: print", "s = int(s) r = str(s) + 'G' elif v", "continue indx += 1 print >>self.fout, x, 0.0 if (indx", "/ (1200 * self.xLen)) yres = int(110 * self.ySize /", "#--- SetXLen(xlen) def SetXLen(self, xlen): self.xLen = xlen print >>self.fout,", "'Socket/State', 'Chavey\\'s Plot') state = 0 while state <= 4:", "== 1: print >>self.fout, 'beginFunction\\n' for ys in yList: factor", "> 1: s = int(v/(1000/d))/d if s*d == int(s)*d: s", "= '' self.foutName = os.path.basename(fname) self.fname = fname+'.ps' self.pageHeader =", "'fname: ', fname p = PsPlot('./p', 'Header', 'SubHeader', 1) fromStateList", "0.5 setrgbcolor } plotSymbolsC\\n' return rv #--- SetColor(color) # def", "0: logInc = int(math.log10(v/inc)) d = math.pow(10,logInc) if d ==", "in xList: self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[ ') for y in", "aypos aylen' self.fout.write('[ ') for z in zList: self.fout.write('('+str(z)+') ')", ">>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0 self.xInc", "float(zss)*factor/10.0 k = 2 while k < 10: print >>self.fout,", "= math.pow(10,math.ceil(math.log10(v1))) vi = 1 vList = [] v =", "= 1 v1 = len(vList) vi = 1 fix =", "SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel ', level, 'def\\n' return #--- SetPlotPercentDir(value)", "= '{ '+str(v0-vi)+' sub '+str(vi)+' div }' print >>self.flog, 'v0:',v0,'", "def SetPlotPercentDir(self,value): if value == 'Vertical': print >>self.fout, '/plotNumPercentDir 1", "xList: if x == ' ' and indx == len(xList)-1:", "0 self.xList = [] self.xDict = {} self.y1Inc = 0", "show' print >>self.fout, 'showpage\\n} bind def' print >>self.fout, 'doGraph' #---", "zs[-1:] == 'M': zss = zs[:-1] factor = 1000000 else:", "0 add }' if isinstance(vBeg,list): vList = vBeg vList.append(' ')", "logOffset -= (math.log10(v0) - 1) # substract 1 from above", "'a') # self.flog = open('./psPlot.out', 'a') if plotsPerPage == 4:", "else: print >>self.fout, x, y, z if (indx != 0)", "', vList print >>self.flog, 'logFlag: ', logFlag, ' fix: ',", "self.y2LogScale = 0 self.xOffset = 0 self.colors = [ (0.7,0.7,0.7),", "inputLine.replace(\"'\", '') i1 = inputLine.find('(') i2 = inputLine.find(')') inputList =", "5*m: vInc = m/2 else: vInc = m else: vInc", "v <= v1: vList.append(self.ValueConvert(v,0)) v *= 10 if v0 >", "k = 1 for x in xList: self.xDict[x] = k", "print >>self.fout, 'beginFunction\\n' endFun = 'endFunction\\n' indx = 0 for", "v0, v1, vInc #--- ValueConvert(v) # def ValueConvert(self, v, inc):", "v0 *= (f*ff) v1 *= (f*ff) vInc *= (f*ff) return", "(f*ff) vInc *= (f*ff) return v0, v1, vInc #--- ValueConvert(v)", "[tMin tMax] [fname]' sys.exit(1) print 'tMin,tMax: ', tMin, tMax, 'fname:", "factor = 1 if zs[-1:] == 'K': zss = zs[:-1]", "= int(v0 / m) * m if (v1 % m)", "*= (f*ff) vInc *= (f*ff) return v0, v1, vInc #---", "print >>self.fout, 0, k*y k += 1 print >>self.fout, 'endFunction\\n'", "v1 += 1 w = v1 - v0 if w", "= 0 self.xOffset = 0 self.colors = [ (0.7,0.7,0.7), (0,0,0.8),", "== 'M': yss = ys[:-1] factor = 1000000 else: yss", "else: yss = ys y = float(yss)*factor/10.0 k = 2", "else: logFlag = 0 v = v0 vList = []", "* self.xSize * 6.5 / (1200 * self.xLen)) yres =", "} def\\n' print >>self.fout, 'beginFunction\\n' if isinstance(zList,list): endFun = 'endFunctionW\\n'", "f = 1 w = v1 - v0 if w", "t = int(inputList[2]) if indx != 0 and t >=", "0: v0,v1,vi = self.GetInc(vBeg,vEnd) else: v0 = vBeg v1 =", "+ n*vi fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div }'", ">>self.fout, '('+title+')\\nMtitles\\n' if logFlag == 1: print >>self.fout, 'beginFunction\\n' for", "print >>self.fout, '/xfix ', fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc,", "', self.x0 - self.xInc - self.xOffset,' sub ', self.xInc, '", "{ nextGraph2v } def' else: print >>self.fout, '/doGraph { graph1v", "= m else: vInc = m # if (vMax/f)%vInc !=", "vMax == v1: v1 += 1 w = v1 -", "ys[-1:] == 'M': yss = ys[:-1] factor = 1000000 else:", "= inputLine.replace(' ','') inputLine = inputLine.replace(\"'\", '') i1 = inputLine.find('(')", "= [] time2List = [] indx = 0 oldTime =", "# def SeriesNames(self, names): indx = len(names) - 1 if", "' cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+'", "> vEnd: break n += 1 v = v0 +", ">>self.fout, '/plotNumPercentDir 1 def\\n' else: print >>self.fout, '/plotNumPercentDir 0 def\\n'", "(0,0,0) self.xSize = 1800 self.ySize = 900 shutil.copy('plot-header.ps', self.fname) self.fout", "int(v1 / m) * m + m w = v1", ">>self.fout, '%\\n% Plot '+id+'\\n%\\n' print >>self.fout, '/xfix { ', self.x0", "in title are separated by '|' print >>self.flog, 'Main Title:", "'/ymtitle ypos ylen add 10 add def\\n' # Multiple lines", "xList: ', xList, \\ ' yList: ', yList print >>self.fout,", "print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0", "tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime = t indx +=", "w <= 10: vInc = 1 elif w <= 20:", "indx >= 0: if names[indx] != None: print >>self.fout, '('+names[indx]+')", "(1200 * self.xLen)) yres = int(110 * self.ySize / 550)", "2 else: m = 10 while w/m > 100: m", "b) # def SetColorIndx(self, indx, r, g, b): self.colors[indx][0] =", "vInc = 2 else: m = 10 while w/m >", "'Header', 'SubHeader', 1) fromStateList = [] toStateList = [] time1List", "pageHeader self.pageSubHeader = pageSubHeader self.plotsPerPage = plotsPerPage self.yfix1 = ''", "= r self.colors[indx][1] = g self.colors[indx][2] = b return rv", "int(v/(1000000000/d))/d if s*d == int(s)*d: s = int(s) r =", "fname = sys.argv[1] elif len(sys.argv) == 3: tMin = int(sys.argv[1])", "self.yfix2 elif axis == 1: print >>self.fout, self.yfix1 # else:", "and (indx % 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' print", "'+self.fname+' -c quit' print >>flog, 'cmdStr: ', cmdStr output =", "yss = ys[:-1] factor = 1000000 else: yss = ys", "print >>self.fout, '/nextGraph { nextGraph3v } def' elif plotsPerPage ==", "def\\n' return #--- SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value): if value ==", "axlen add aypos aylen' self.fout.write('[ ') for z in zList:", "> 1: logOffset -= (math.log10(v0) - 1) # substract 1", "(vMin % f) != 0 and vMax == v1: v1", "!= 0: if v1 % vInc != 0: v1 =", ">>self.fout, self.SetColor(self.colors[indx % self.colorsN]) indx -= 1 print >>self.fout, 'fdescriptionsC'", "d = math.pow(10,logInc) if d == 0: d = 10.0", "'' self.yfix2 = '' self.xGrid = 1 self.yGrid = 1", ">>self.flog, 'vList: ', vList print >>self.flog, 'logFlag: ', logFlag, '", "v1 = int(v1/vInc)*vInc + vInc if (v0 % vInc) !=", "vEnd vi = vInc if vBeg > 0 and (logFlag==1", "vList print >>self.flog, 'logFlag: ', logFlag, ' fix: ', fix", "s = int(v*d)/d if s*d == int(s)*d: s = int(s)", "1 v0Log = math.log10(v0) t = math.ceil(v0Log) ff = math.modf(v0Log)", "zs[-1:] == 'K': zss = zs[:-1] factor = 1000 elif", "v0 if w == 0: v1 = v0 + 1", "== v1: v1 += 1 w = v1 - v0", "v0 = vBeg v1 = vEnd vi = vInc if", "print >>self.fout, '('+names[indx]+') ' print >>self.fout, self.SetColor(self.colors[indx % self.colorsN]) indx", "'+str(color[2])+ \\ ' setrgbcolor } ' return rv #--- SetColorIndx(indx,", "' setrgbcolor } ' return rv #--- GetColorIndx(indx) # def", "str(s) + 'G' elif v >= 1000000 and inc >", "= 0 while True: vList.append(self.ValueConvert(v,vi)) if v > vEnd: break", "v >= 1000000000 and inc > 1: s = int(v/(1000000000/d))/d", "# print >>self.fout, '('+title+')\\nMtitles\\n' if logFlag == 1: print >>self.fout,", "w = v1 - v0 if w == 0: v1", "'beginFunction\\n' for zs in zList: factor = 1 if zs[-1:]", "#--- SetColorIndx(indx, r, g, b) # def SetColorIndx(self, indx, r,", ">>self.fout, x, y, z print >>self.fout, endFun, type, '\\n' return", "w <= 5*m: vInc = m/2 else: vInc = m", "v1: vList.append(self.ValueConvert(v,0)) v *= 10 if v0 > 1: logOffset", "while t < 1: logOffset += 1 t += 1", "SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc =", "1: print 'USAGE: psPlot.py [tMin tMax] [fname]' sys.exit(1) print 'tMin,tMax:", "-c quit' print >>flog, 'cmdStr: ', cmdStr output = commands.getoutput(cmdStr)", "def' print >>self.fout, '/nextGraph { nextGraph2v } def' else: print", "v0 = int(v0/f) v1 = int(v1/f) if (vMin % f)", "self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc = yi self.y1Count = len(yList) self.yfix1 =", "return r #--- GetAxis(vBeg, vEnd, vInc, logFlag) # def GetAxis(self,", "m if (v1 % m) != 0: v1 = int(v1", "= 1000000 else: zss = zs y = float(zss)*factor/10.0 k", "self.colorGreen = (0,0.8,0) self.colorBlue = (0,0,0.8) self.colorAqua = (0,0.5,0.5) self.colorWhite", "= int(vMin) v1 = int(vMax+0.99) f = 1 w =", "int(s) r = str(s) + 'M' elif v >= 1000", "'K': zss = zs[:-1] factor = 1000 elif zs[-1:] ==", "# def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale)", "'/xfix ', fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc", "'/doGraph { graph1v } def' print >>self.fout, '/nextGraph { nextGraph1v", "-= 1 print >>self.fout, 'fdescriptionsC' #--- PlotVBars(xList, type) # def", "self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[ ') for y in yList: self.fout.write('('+str(y)+')", "commands import types import math #gsPath = '/usr/local/bin/gs' gsPath =", "'Vertical': print >>self.fout, '/plotNumPercentDir 1 def\\n' else: print >>self.fout, '/plotNumPercentDir", "= self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi self.y2Count =", "print >>self.fout, '/doGraph { graph1v } def' print >>self.fout, '/nextGraph", "1 elif w <= 20: vInc = 2 else: m", "fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc = yi", "self.y2Count = len(zList) print >>self.fout, '/Flag2Yaxes 1 def' self.yfix2 =", "1 else: v = 0; if axis == 1: self.y1LogScale", "indx: continue z = zList[indx] else: z = '' indx", ">>self.fout, x, y, z if (indx != 0) and (indx", "tMax = 100000 stateList = [0,1,2,2,3,3,3,3,4] fname = 'sched.txt' if", "0.0 if (indx != 0) and (indx % 1000) ==", "w/f >= 100: f *= 10 # w = int(w/f)", "= False self.xLen = 6.5 #inches self.seriesTitle = ' '", "= 1000000 else: yss = ys y = float(yss)*factor/10.0 k", "print >>self.flog, 'logFlag: ', logFlag, ' fix: ', fix return", "class PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage) # class PsPlot(object): def __init__(self,", "while True: vList.append(self.ValueConvert(v,vi)) if v > vEnd: break n +=", "# def GetColorIndx(self, indx): color = self.colors[indx % self.colorsN] rv", "[] time1List = [] time2List = [] indx = 0", "def SetXSize(self, xsize): self.xSize = xsize return #--- SetYSize(ysize) def", "' ]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid, self.yGrid, '", "if len(sys.argv) == 2: fname = sys.argv[1] elif len(sys.argv) ==", "color): rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ '", "= (0,0,0) self.xSize = 1800 self.ySize = 900 shutil.copy('plot-header.ps', self.fname)", "int(v1/vInc)*vInc + vInc if (v0 % vInc) != 0: v0", "pageSubHeader, plotsPerPage): self.foutPath = os.path.dirname(fname)+'/' if self.foutPath == '/': self.foutPath", ">>self.fout, self.yfix1 print >>self.fout, 'beginFunction\\n' endFun = 'endFunction\\n' indx =", "def' print >>self.fout, 'axpos axlen add aypos aylen' self.fout.write('[ ')", "} plotSymbolsC\\n' return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) # def", "'' self.foutName = os.path.basename(fname) self.fname = fname+'.ps' self.pageHeader = pageHeader", "' self.x0 = 0 self.xInc = 0 self.xCount = 0", "int(vMin) v1 = int(vMax+0.99) f = 1 w = v1", "= int(v*d)/d if s*d == int(s)*d: s = int(s) r", "', fix return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def SetXLen(self, xlen): self.xLen", "= 0 self.y1Count = 0 self.y1LogScale = 0 self.y2Inc =", "flog = self.flog print >>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout) if self.plotsPerPage", "(indx % 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout,", "print >>self.fout, 'Mtitles\\n' # print >>self.fout, '('+title+')\\nMtitles\\n' if logFlag ==", "= xList self.xDict = {} k = 1 for x", "b return rv #--- outputPS(string) # def outputPS(self, s): print", "self.colors[indx][2] = b return rv #--- outputPS(string) # def outputPS(self,", "= self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc = yi self.y1Count = len(yList) self.yfix1", "vInc = m/2 else: vInc = m else: vInc =", "s = int(v/(1000000000/d))/d if s*d == int(s)*d: s = int(s)", "xres = int(100 * self.xSize * 6.5 / (1200 *", "0: v0 = int(v0/vInc)*vInc v0 += vInc v0 *= (f*ff)", "'endFunction\\n' indx = 0 for x in xList: if x", "1: print >>self.fout, self.yfix2 print >>self.fout, 'beginFunction\\n' for zs in", "<= indx: continue z = zList[indx] else: z = ''", "'+str(vi)+' div }' logFlag = 0 else: if vInc ==", "== int(s)*d: s = int(s) r = str(s) + 'M'", "y, z print >>self.fout, endFun, type, '\\n' return #--- GetImage()", "#--- SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value): if value == 'Off': v", "#--- PlotVBars(xList, type) # def PlotVBars(self, xList, type): flog =", "fname = 'sched.txt' if len(sys.argv) == 2: fname = sys.argv[1]", "= 0 self.colors = [ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3),", "# print >>self.fout, '/yfix { 0 add } def\\n' print", "vaxis2' if logFlag == 1: print >>self.fout, self.yfix2 print >>self.fout,", "for x in xList: if x == ' ' and", "import sys import random import os.path import shutil import commands", "print >>self.fout, 'beginFunction\\n' for ys in yList: factor = 1", "= int(v0/vInc)*vInc v0 += vInc v0 *= (f*ff) v1 *=", "'\\n' return #--- GetImage() # def GetImage(self): flog = self.flog", "import math #gsPath = '/usr/local/bin/gs' gsPath = 'gs' logFile =", "div }' print >>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')' print >>self.flog,", "quit' print >>flog, 'cmdStr: ', cmdStr output = commands.getoutput(cmdStr) print", "v1 = vEnd vi = vInc if vBeg > 0", "(v0 % m) != 0: v0 = int(v0 / m)", ">>self.fout, '('+self.seriesTitle+')' while indx >= 0: if names[indx] != None:", "tMax] [fname]' sys.exit(1) print 'tMin,tMax: ', tMin, tMax, 'fname: ',", "= '{ dup 0 eq { } { log '+str(logOffset)+'", "self.y2LogScale = v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print", "fromStateList = [] toStateList = [] time1List = [] time2List", "SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if value == 'Vertical': print >>self.fout, '/plotNumPercentDir", "int(vMax+0.99) f = 1 w = v1 - v0 if", "len(zList) <= indx: continue z = zList[indx] else: z =", "self.pageSubHeader = pageSubHeader self.plotsPerPage = plotsPerPage self.yfix1 = '' self.yfix2", "= [] self.xDict = {} self.y1Inc = 0 self.y1Count =", "SetColor(color) # def SetColor(self, color): rv = ' { '+str(color[0])+'", "moveto\\n (',self.pageSubHeader,') show' print >>self.fout, 'showpage\\n} bind def' print >>self.fout,", "= (0,0,0.8) self.colorAqua = (0,0.5,0.5) self.colorWhite = (1,1,1) self.ColorBlack =", "self.xInc - self.xOffset,' sub ', self.xInc, ' div ', 0.0,'", "self.x0 = 0 self.xInc = 0 self.xCount = 0 self.xList", "1: # size = ' -g1200x550 ' size = '", "print >>self.fout, 'doGraph' return #--- SetXSize(xsize) def SetXSize(self, xsize): self.xSize", ">>self.fout, self.yfix2 print >>self.fout, 'beginFunction\\n' for zs in zList: factor", "toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime = t indx += 1 p.SetPlot(tMin,", "if indx != 0 and t >= tMin and t", "0 self.y1LogScale = 0 self.y2Inc = 0 self.y2Count = 0", "plotsPerPage): self.foutPath = os.path.dirname(fname)+'/' if self.foutPath == '/': self.foutPath =", "*= 10 if v0 > 1: logOffset -= (math.log10(v0) -", "print >>self.fout, 'endFunction\\n' print >>self.fout, '19 { 0 0 0", "= int(v/(1000/d))/d if s*d == int(s)*d: s = int(s) r", "#--- GetColorIndx(indx) # def GetColorIndx(self, indx): color = self.colors[indx %", "= 6.5 #inches self.seriesTitle = ' ' self.x0 = 0", "ypos ylen add 10 add def\\n' # Multiple lines in", "\\ ' setrgbcolor } ' return rv #--- GetColorIndx(indx) #", "str(s) + 'M' elif v >= 1000 and inc >", "k += 1 print >>self.fout, 'endFunction\\n' print >>self.fout, '18 {", "print >>self.fout, self.yfix1 print >>self.fout, '[ ' for x in", "v = v0 while v <= v1: vList.append(self.ValueConvert(v,0)) v *=", "', xList, \\ ' yList: ', yList print >>self.fout, '%\\n%", "v0 if w <= 10: vInc = 1 elif w", "<= v1: vList.append(self.ValueConvert(v,0)) v *= 10 if v0 > 1:", "int(v0 / m) * m if (v1 % m) !=", "if value == 'Off': v = -1 elif value ==", ">>self.fout, '/nextGraph { nextGraph2v } def' else: print >>self.fout, '/doGraph", "= [] v = v0 while v <= v1: vList.append(self.ValueConvert(v,0))", "0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform == True: print >>self.fout,", "+ s*0.20) indx += 1 p.PlotData(1,t1List, t2List, sList, 'Test', '0.1", "0: return print >>self.fout, '('+self.seriesTitle+')' while indx >= 0: if", "print >>self.fout, '/ymtitle ypos ylen add 10 add def\\n' #", "self.plotsPerPage = plotsPerPage self.yfix1 = '' self.yfix2 = '' self.xGrid", "vBeg v1 = vEnd vi = vInc if vBeg >", "v1:',v1,' (',vEnd,')' print >>self.flog, 'vList: ', vList print >>self.flog, 'logFlag:", "0 self.y1Count = 0 self.y1LogScale = 0 self.y2Inc = 0", "0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state += 1 image = p.GetImage(sys.stdout)", ">= 1000000 and inc > 1: s = int(v/(1000000/d))/d if", "#--- GetInc(vMin, vMax) def GetInc(self,vMin, vMax): ff = 1.0 while", "names[indx] != None: print >>self.fout, '('+names[indx]+') ' print >>self.fout, self.SetColor(self.colors[indx", "self.xUniform == True: print >>self.fout, g_indx, y, z else: print", "w/m > 100: m *= 10 if (v0 >= 0)", "vInc == 0: v0,v1,vi = self.GetInc(vBeg,vEnd) else: v0 = vBeg", "s = int(v/(1000000/d))/d if s*d == int(s)*d: s = int(s)", "int(v/(1000000/d))/d if s*d == int(s)*d: s = int(s) r =", "vEnd, vInc, logFlag): fix = '{ 0 add }' if", "else: print >>self.fout, '/doGraph { graph1v } def' print >>self.fout,", "= str(int(v*100)/100.0) return r #--- GetAxis(vBeg, vEnd, vInc, logFlag) #", "if v >= 1000000000 and inc > 1: s =", "return #--- SetYSize(ysize) def SetYSize(self, ysize): self.ySize = ysize return", "10 v0 = int(vMin) v1 = int(vMax+0.99) f = 1", "plotsPerPage self.yfix1 = '' self.yfix2 = '' self.xGrid = 1", "xlen): self.xLen = xlen print >>self.fout, '/xAxisLen %.2f def' %", "= ys[:-1] factor = 1000000 else: yss = ys y", "self.xOffset = 0 self.colors = [ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14),", "def End(self): print >>self.fout, '\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin, vMax) def", "print 'Image file: ', image p.End() if __name__ == \"__main__\":", "v0 + 1 w = 1 while w/f >= 100:", "print >>self.fout, x, 0.0 if (indx != 0) and (indx", "indx += 1 p.PlotData(1,t1List, t2List, sList, 'Test', '0.1 in 0", "add }' if isinstance(vBeg,list): vList = vBeg vList.append(' ') self.xUniform", "indx = 0 for x in xList: if x ==", "GetImage() # def GetImage(self): flog = self.flog print >>self.fout, 'showpage\\n'", "*= 10 # w = int(w/f) v0 = int(v0/f) v1", ">>flog, 'output from gs command: ', output return self.foutPath+self.foutName+'.jpg' #---", "'M': zss = zs[:-1] factor = 1000000 else: zss =", "i1 = inputLine.find('(') i2 = inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',') s1", "' ' and indx == len(xList)-1: continue indx += 1", "'%\\n% Plot '+id+'\\n%\\n' print >>self.fout, '/xfix { ', self.x0 -", "s = int(s) r = str(s) + 'M' elif v", "0: if v1 % vInc != 0: v1 = int(v1/vInc)*vInc", ">>self.fout, 'fdescriptionsC' #--- PlotVBars(xList, type) # def PlotVBars(self, xList, type):", "'/Helvetica findfont 12 scalefont setfont' if self.pageHeader != '': print", "*= 10 vMax *= 10 v0 = int(vMin) v1 =", "+ m w = v1 - v0 if w <=", "'Chavey\\'s Plot') state = 0 while state <= 4: t1List", "0 add } def\\n' print >>self.fout, 'beginFunction\\n' if isinstance(zList,list): endFun", "+= 1 print >>self.fout, 'endFunction\\n' print >>self.fout, '19 { 0", "#--- SetYSize(ysize) def SetYSize(self, ysize): self.ySize = ysize return #---", "yList: ', yList print >>self.fout, '%\\n% Plot '+id+'\\n%\\n' print >>self.fout,", "1 and float(v)/inc > 1.0: d = 10.0 if v", "if w <= 10: vInc = 1 elif w <=", ">>self.fout, ' ]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid, self.yGrid,", "zs y = float(zss)*factor/10.0 k = 2 while k <", "1 vList = [] v = v0 while v <=", "== 0: v1 = v0 + 1 w = 1", "xsize return #--- SetYSize(ysize) def SetYSize(self, ysize): self.ySize = ysize", "', self.xInc, ' div ', 0.0,' add } def\\n' if", "if math.fabs(ff[0]) < math.fabs(v0Log)/1000 and t < 0: t +=", "v >= 1000 and inc > 1: s = int(v/(1000/d))/d", "vList.append(' ') self.xUniform = True v0 = 1 v1 =", "outputPS(self, s): print >>self.fout, s #--- SeriesNames(names) # def SeriesNames(self,", "= t indx += 1 p.SetPlot(tMin, tMax, 0, 0, 2,", ">= 0) and (v0 % m) != 0: v0 =", "elif plotsPerPage == 2: print >>self.fout, '/doGraph { graph2v }", "* 6.5 / (1200 * self.xLen)) yres = int(110 *", "== 1: print >>self.fout, self.yfix2 print >>self.fout, 'beginFunction\\n' for zs", "# def End(self): print >>self.fout, '\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin, vMax)", "== int(s)*d: s = int(s) r = str(s) + 'G'", "= int(sys.argv[1]) tMax = int(sys.argv[2]) fname = sys.argv[3] elif len(sys.argv)", "0 for s in toStateList: if s == state: t1List.append(time1List[indx])", "'M': yss = ys[:-1] factor = 1000000 else: yss =", "- v0 if w <= 5*m: vInc = m/2 else:", ">>self.fout, '/doGraph { graph2v } def' print >>self.fout, '/nextGraph {", "sub '+str(vi)+' div }' logFlag = 0 else: if vInc", "def ValueConvert(self, v, inc): if inc > 0: logInc =", "+= 1 v0 = math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1))) vi =", "vi:',vi,' v1:',v1,' (',vEnd,')' print >>self.flog, 'vList: ', vList print >>self.flog,", "def\\n' if axis == 2: print >>self.fout, self.yfix2 elif axis", "m) != 0: v0 = int(v0 / m) * m", "str(s) else: r = str(int(v*100)/100.0) return r #--- GetAxis(vBeg, vEnd,", "elif ys[-1:] == 'M': yss = ys[:-1] factor = 1000000", "v0 = vBeg v1 = vEnd logFlag = 1 v0Log", "0 while True: vList.append(self.ValueConvert(v,vi)) if v > vEnd: break n", "titleLines: if len(t) > 0: print >>self.flog, ' '+t print", "', 0.0,' add } def\\n' if axis == 2: print", "#--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv =", "quit' else: size = ' -g1200x1100 ' cmdStr = gsPath", "self.xLen)) yres = int(110 * self.ySize / 550) res =", "PlotData(self, axis, xList, yList, zList, id, type): flog = self.flog", "x in xList: if x == ' ' and indx", "0, 0, 2, 0, 'Time', 'Socket/State', 'Chavey\\'s Plot') state =", "if (v1 % m) != 0: v1 = int(v1 /", "ff = math.modf(v0Log) if math.fabs(ff[0]) < math.fabs(v0Log)/1000 and t <", "*= (f*ff) v1 *= (f*ff) vInc *= (f*ff) return v0,", "axis == 1: self.y1LogScale = v else: self.y2LogScale = v", "indx != 0 and t >= tMin and t <=", "vInc #--- ValueConvert(v) # def ValueConvert(self, v, inc): if inc", "logOffset = 0 while t < 1: logOffset += 1", "def SetColor(self, color): rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+", "= math.ceil(v0Log) ff = math.modf(v0Log) if math.fabs(ff[0]) < math.fabs(v0Log)/1000 and", ">>self.fout, '/doGraph { graph3v } def' print >>self.fout, '/nextGraph {", "0 self.y2Inc = 0 self.y2Count = 0 self.y2LogScale = 0", "if vInc == 0: v0,v1,vi = self.GetInc(vBeg,vEnd) else: v0 =", ">= 0: if names[indx] != None: print >>self.fout, '('+names[indx]+') '", "/ m) * m + m w = v1 -", "10 while w/m > 100: m *= 10 if (v0", "0 or v1 % vInc != 0: if v1 %", "def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc", "fname p = PsPlot('./p', 'Header', 'SubHeader', 1) fromStateList = []", "len(vList) vi = 1 fix = '{ '+str(v0-vi)+' sub '+str(vi)+'", "{ nextGraph3v } def' elif plotsPerPage == 2: print >>self.fout,", "r self.colors[indx][1] = g self.colors[indx][2] = b return rv #---", "'+id+'\\n%\\n' print >>self.fout, '/xfix { ', self.x0 - self.xInc -", "g self.colors[indx][2] = b return rv #--- outputPS(string) # def", "self.ySize = ysize return #--- SetPlotBgLevel(level) # def SetPlotBgLevel(self,level): print", "= True v0 = 1 v1 = len(vList) vi =", "self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi self.y2Count = len(zList)", "(logFlag==1 or (logFlag==0 and (vEnd/vBeg > 100))): v0 = vBeg", "title are separated by '|' print >>self.flog, 'Main Title: '+title", "print >>self.fout, endFun, type, '\\n' return #--- PlotData(axis, xList, yList,", "'{ '+str(v0-vi)+' sub '+str(vi)+' div }' logFlag = 0 else:", "726 moveto\\n (',self.pageSubHeader,') show' print >>self.fout, 'showpage\\n} bind def' print", "vList.append(self.ValueConvert(v,0)) v *= 10 if v0 > 1: logOffset -=", "self.y1Inc = 0 self.y1Count = 0 self.y1LogScale = 0 self.y2Inc", "= 1 w = v1 - v0 if w ==", "self.pageHeader = pageHeader self.pageSubHeader = pageSubHeader self.plotsPerPage = plotsPerPage self.yfix1", ">>self.fout, self.yfix1 # else: # print >>self.fout, '/yfix { 0", "= inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])] s2 =", "print >>self.fout, '/doGraph { graph3v } def' print >>self.fout, '/nextGraph", "d = 10.0 if v >= 1000000000 and inc >", "random import os.path import shutil import commands import types import", "'{ '+str(v0-vi)+' sub '+str(vi)+' div }' print >>self.flog, 'v0:',v0,' vi:',vi,'", "tMin, tMax, 'fname: ', fname p = PsPlot('./p', 'Header', 'SubHeader',", "+self.fname+' -c quit' # cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg", "'/yfix { 0 add } def\\n' print >>self.fout, 'beginFunction\\n' if", "fix return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def SetXLen(self, xlen): self.xLen =", "= 0 tMax = 100000 stateList = [0,1,2,2,3,3,3,3,4] fname =", ">>self.fout, '/nextGraph { nextGraph3v } def' elif plotsPerPage == 2:", "return print >>self.fout, '('+self.seriesTitle+')' while indx >= 0: if names[indx]", "xList, type): flog = self.flog print >>self.fout, self.yfix1 print >>self.fout,", "self.xSize = xsize return #--- SetYSize(ysize) def SetYSize(self, ysize): self.ySize", "sys.exit(1) print 'tMin,tMax: ', tMin, tMax, 'fname: ', fname p", "\\ ' yList: ', yList print >>self.fout, '%\\n% Plot '+id+'\\n%\\n'", "'{ 0 add }' if isinstance(vBeg,list): vList = vBeg vList.append('", "(v1 % m) != 0: v1 = int(v1 / m)", ">>self.fout, 0, k*y k += 1 print >>self.fout, 'endFunction\\n' print", "plotsPerPage) # class PsPlot(object): def __init__(self, fname, pageHeader, pageSubHeader, plotsPerPage):", "/yinc yinc1 def' print >>self.fout, self.yfix1 print >>self.fout, '[ '", "% m) != 0: v1 = int(v1 / m) *", "GetAxis(self, vBeg, vEnd, vInc, logFlag): fix = '{ 0 add", "}' logFlag = 0 else: if vInc == 0: v0,v1,vi", "vEnd logFlag = 1 v0Log = math.log10(v0) t = math.ceil(v0Log)", "z else: print >>self.fout, x, y, z if (indx !=", "[] self.xDict = {} self.y1Inc = 0 self.y1Count = 0", "*= (f*ff) return v0, v1, vInc #--- ValueConvert(v) # def", "1 if indx == 0: return print >>self.fout, '('+self.seriesTitle+')' while", "gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res +self.fname+' -c quit'", "type): flog = self.flog print >>flog, 'graph xList: ', self.xList,", "= '' indx += 1 if self.xUniform == True: g_indx", "(0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ] self.colorsN = 11 self.colorRed =", "= v0 vList = [] n = 0 while True:", "psPlot.py [tMin tMax] [fname]' sys.exit(1) print 'tMin,tMax: ', tMin, tMax,", "isinstance(vBeg,list): vList = vBeg vList.append(' ') self.xUniform = True v0", "self.yfix2 print >>self.fout, 'beginFunction\\n' for zs in zList: factor =", "int(s)*d: s = int(s) r = str(s) + 'M' elif", "print >>self.fout, '('+self.seriesTitle+')' while indx >= 0: if names[indx] !=", "= int(sys.argv[2]) elif len(sys.argv) == 4: tMin = int(sys.argv[1]) tMax", "if d == 0: d = 10.0 else: d =", "title.split('|') for t in titleLines: if len(t) > 0: print", "t += 1 v0 = math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1))) vi", "1 self.yGrid = 1 self.xUniform = False self.xLen = 6.5", "= [] sList = [] indx = 0 for s", "= g self.colors[indx][2] = b return rv #--- outputPS(string) #", "if w <= 5*m: vInc = m/2 else: vInc =", "logInc = int(math.log10(v/inc)) d = math.pow(10,logInc) if d == 0:", "fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime = t indx += 1", "yList: self.fout.write('('+str(y)+') ') print >>self.fout, ' ]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n'", "0 while t < 1: logOffset += 1 t +=", "= xlen print >>self.fout, '/xAxisLen %.2f def' % self.xLen print", "int(v0/f) v1 = int(v1/f) if (vMin % f) != 0", "]') if ztitle != '': print >>self.fout, '('+ztitle+') vaxis2' if", "') for y in yList: self.fout.write('('+str(y)+') ') print >>self.fout, '", "v0 = int(v0 / m) * m if (v1 %", "print >>self.fout, '/nextGraph { nextGraph4v } def' elif plotsPerPage ==", "in zList: self.fout.write('('+str(z)+') ') self.fout.write(' ]') if ztitle != '':", "if s == state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 + s*0.20) indx", "0, 'Time', 'Socket/State', 'Chavey\\'s Plot') state = 0 while state", "'|' print >>self.flog, 'Main Title: '+title titleLines = title.split('|') for", "= v0 + 1 w = 1 while w/f >=", "+= 1 t += 1 v0 = math.pow(10,math.floor(v0Log)+1) v1 =", "pageHeader, pageSubHeader, plotsPerPage) # class PsPlot(object): def __init__(self, fname, pageHeader,", "v0Log = math.log10(v0) t = math.ceil(v0Log) ff = math.modf(v0Log) if", "vList = [] v = v0 while v <= v1:", "self.fout.write(' ]\\n[ ') for y in yList: self.fout.write('('+str(y)+') ') print", "print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid, self.yGrid, ' grid\\n' print", ">>self.fout, 'beginFunction\\n' if isinstance(zList,list): endFun = 'endFunctionW\\n' else: endFun =", "int(sys.argv[1]) tMax = int(sys.argv[2]) fname = sys.argv[3] elif len(sys.argv) !=", "state <= 4: t1List = [] t2List = [] sList", "= str(s) + 'K' elif v >= 1: s =", "k k=k+1 print >>self.fout, '/xfix ', fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag)", "vList.append(self.ValueConvert(v,vi)) if v > vEnd: break n += 1 v", "'On': v = 1 else: v = 0; if axis", ">>self.flog, 'Main Title: '+title titleLines = title.split('|') for t in", "+= 1 print >>self.fout, 'endFunction\\n' print >>self.fout, '18 { 0.72", "rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ ' setrgbcolor", "0 0 setrgbcolor } plotSymbolsC\\n' return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, #", "above inside parent? fix = '{ dup 0 eq {", "= 0 oldTime = 0 fin = open(fname, 'r') for", "oldTime = 0 fin = open(fname, 'r') for inputLine in", "'/nextGraph { nextGraph4v } def' elif plotsPerPage == 3: print", "time2List = [] indx = 0 oldTime = 0 fin", "xList self.xDict = {} k = 1 for x in", "eq { } { log '+str(logOffset)+' add } ifelse }'", "SetXSize(self, xsize): self.xSize = xsize return #--- SetYSize(ysize) def SetYSize(self,", "y, z else: print >>self.fout, x, y, z print >>self.fout,", "vMax <= 1 and vMax > 0: ff *= 0.10", "> 0: print >>self.flog, ' '+t print >>self.fout, '('+t+')\\n' print", "' print >>self.fout, self.SetColor(self.colors[indx % self.colorsN]) indx -= 1 print", "'output from gs command: ', output return self.foutPath+self.foutName+'.jpg' #--- Main", "command: ', output return self.foutPath+self.foutName+'.jpg' #--- Main # def main():", "cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+' -c", "PlotVBars(self, xList, type): flog = self.flog print >>self.fout, self.yfix1 print", "plotSymbolsC\\n' return rv #--- SetColor(color) # def SetColor(self, color): rv", "if s*d == int(s)*d: s = int(s) r = str(s)", "v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def SetXLen(self, xlen): self.xLen = xlen print", "= int(110 * self.ySize / 550) res = ' -r%dx%d", "import shutil import commands import types import math #gsPath =", "= int(vMax+0.99) f = 1 w = v1 - v0", "'18 { 0.72 0.52 0.5 setrgbcolor } plotSymbolsC\\n' return rv", "10 add def\\n' # Multiple lines in title are separated", "0: if names[indx] != None: print >>self.fout, '('+names[indx]+') ' print", "and (v0 % m) != 0: v0 = int(v0 /", "> 0: ff *= 0.10 vMin *= 10 vMax *=", "SetXSize(xsize) def SetXSize(self, xsize): self.xSize = xsize return #--- SetYSize(ysize)", "0.10 vMin *= 10 vMax *= 10 v0 = int(vMin)", "for zs in zList: factor = 1 if zs[-1:] ==", "rv #--- GetColorIndx(indx) # def GetColorIndx(self, indx): color = self.colors[indx", "oldTime = t indx += 1 p.SetPlot(tMin, tMax, 0, 0,", "'+str(logOffset)+' add } ifelse }' else: logFlag = 0 v", "continue if len(yList) <= indx: continue y = yList[indx] if", "= 100000 stateList = [0,1,2,2,3,3,3,3,4] fname = 'sched.txt' if len(sys.argv)", "= math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1))) vi = 1 vList =", "= int(100 * self.xSize * 6.5 / (1200 * self.xLen))", "while w/f >= 100: f *= 10 # w =", "str(s) + 'K' elif v >= 1: s = int(v*d)/d", "s == state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 + s*0.20) indx +=", "w = v1 - v0 if w <= 10: vInc", "dup 0 eq { } { log '+str(logOffset)+' add }", "setrgbcolor } ' return rv #--- GetColorIndx(indx) # def GetColorIndx(self,", "and vMax > 0: ff *= 0.10 vMin *= 10", "ysize return #--- SetPlotBgLevel(level) # def SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel", "'('+names[indx]+') ' print >>self.fout, self.SetColor(self.colors[indx % self.colorsN]) indx -= 1", "def\\n' print >>self.fout, 'beginFunction\\n' if isinstance(zList,list): endFun = 'endFunctionW\\n' else:", "== True: g_indx = self.xDict[x] print >>self.fout, g_indx, y, z", "', yList print >>self.fout, '%\\n% Plot '+id+'\\n%\\n' print >>self.fout, '/xfix", "> 1: s = int(v/(1000000/d))/d if s*d == int(s)*d: s", "setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0 self.xInc = xi", "are separated by '|' print >>self.flog, 'Main Title: '+title titleLines", "- v0 if w <= 10: vInc = 1 elif", "self.fout.close() #--- GetInc(vMin, vMax) def GetInc(self,vMin, vMax): ff = 1.0", "'beginFunction\\n' if isinstance(zList,list): endFun = 'endFunctionW\\n' else: endFun = 'endFunction\\n'", "'') i1 = inputLine.find('(') i2 = inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',')", "m) * m + m w = v1 - v0", "int(v/(1000/d))/d if s*d == int(s)*d: s = int(s) r =", "ys in yList: factor = 1 if ys[-1:] == 'K':", "color = self.colors[indx % self.colorsN] rv = ' { '+str(color[0])+'", "if x == ' ' and indx == len(xList)-1: continue", "SetPlotBgLevel(level) # def SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel ', level, 'def\\n'", "(y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc = yi self.y1Count = len(yList)", "'40 726 moveto\\n (',self.pageSubHeader,') show' print >>self.fout, 'showpage\\n} bind def'", "SetXLen(xlen) def SetXLen(self, xlen): self.xLen = xlen print >>self.fout, '/xAxisLen", ">>self.fout, self.xCount, k*y k += 1 print >>self.fout, 'endFunction\\n' print", "1 p.PlotData(1,t1List, t2List, sList, 'Test', '0.1 in 0 '+p.SetColor(p.colors[state])+' plotWbarsC',", "1: s = int(v/(1000000/d))/d if s*d == int(s)*d: s =", "for x in xList: self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[ ') for", "setrgbcolor } plotSymbolsC\\n' return rv #--- SetColor(color) # def SetColor(self,", "= zs[:-1] factor = 1000000 else: zss = zs y", "def PlotData(self, axis, xList, yList, zList, id, type): flog =", "0: t += 1 logOffset = 0 while t <", "= title.split('|') for t in titleLines: if len(t) > 0:", "def GetImage(self): flog = self.flog print >>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout)", "== 2: fname = sys.argv[1] elif len(sys.argv) == 3: tMin", "g_indx, y, z else: print >>self.fout, x, y, z if", "= ' -g1200x1100 ' cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg", "= 1 self.yGrid = 1 self.xUniform = False self.xLen =", "inc > 0: logInc = int(math.log10(v/inc)) d = math.pow(10,logInc) if", "if len(t) > 0: print >>self.flog, ' '+t print >>self.fout,", "inc): if inc > 0: logInc = int(math.log10(v/inc)) d =", "inc > 1: s = int(v/(1000/d))/d if s*d == int(s)*d:", "1.0 while vMax <= 1 and vMax > 0: ff", "= 0 self.xCount = 0 self.xList = [] self.xDict =", "open(fname, 'r') for inputLine in fin: inputLine = inputLine.replace(' ','')", "graph2v } def' print >>self.fout, '/nextGraph { nextGraph2v } def'", "image = p.GetImage(sys.stdout) print 'Image file: ', image p.End() if", "(',self.pageSubHeader,') show' print >>self.fout, 'showpage\\n} bind def' print >>self.fout, 'doGraph'", "-sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' else: size = '", "s #--- SeriesNames(names) # def SeriesNames(self, names): indx = len(names)", "#!/usr/bin/env python2 import sys import random import os.path import shutil", "int(sys.argv[2]) fname = sys.argv[3] elif len(sys.argv) != 1: print 'USAGE:", "elif v >= 1000 and inc > 1: s =", "1 self.xUniform = False self.xLen = 6.5 #inches self.seriesTitle =", "if ztitle != '': print >>self.fout, '('+ztitle+') vaxis2' if logFlag", "'graph xList: ', self.xList, ' xList: ', xList, \\ '", "> 1: s = int(v/(1000000000/d))/d if s*d == int(s)*d: s", "elif len(sys.argv) != 1: print 'USAGE: psPlot.py [tMin tMax] [fname]'", "yi self.y1Count = len(yList) self.yfix1 = '/yfix '+fix+' def\\n /yinc", "SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) =", "0 tMax = 100000 stateList = [0,1,2,2,3,3,3,3,4] fname = 'sched.txt'", "= p.GetImage(sys.stdout) print 'Image file: ', image p.End() if __name__", "'fdescriptionsC' #--- PlotVBars(xList, type) # def PlotVBars(self, xList, type): flog", "0: v1 = int(v1/vInc)*vInc + vInc if (v0 % vInc)", "SetPlotYLogScale(self,axis,value): if value == 'Off': v = -1 elif value", ">= 1: s = int(v*d)/d if s*d == int(s)*d: s", "= v0 + n*vi fix = '{ '+str(v0-vi)+' sub '+str(vi)+'", "add } def\\n' if axis == 2: print >>self.fout, self.yfix2", "0 and (logFlag==1 or (logFlag==0 and (vEnd/vBeg > 100))): v0", "GetImage(self): flog = self.flog print >>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout) if", "type, '\\n' return #--- GetImage() # def GetImage(self): flog =", "zList, id, type): flog = self.flog print >>flog, 'graph xList:", "(0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ] self.colorsN = 11", "plotsPerPage == 4: print >>self.fout, '/doGraph { graph4v } def'", "= 1800 self.ySize = 900 shutil.copy('plot-header.ps', self.fname) self.fout = open(self.fname,", "', output return self.foutPath+self.foutName+'.jpg' #--- Main # def main(): tMin", "== True: print >>self.fout, g_indx, y, z else: print >>self.fout,", "= self.flog print >>flog, 'graph xList: ', self.xList, ' xList:", "'sched.txt' if len(sys.argv) == 2: fname = sys.argv[1] elif len(sys.argv)", "zss = zs[:-1] factor = 1000000 else: zss = zs", "indx): color = self.colors[indx % self.colorsN] rv = ' {", "End(self): print >>self.fout, '\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin, vMax) def GetInc(self,vMin,", "SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title)", "(0,0,0.8) self.colorAqua = (0,0.5,0.5) self.colorWhite = (1,1,1) self.ColorBlack = (0,0,0)", "math.log10(v0) t = math.ceil(v0Log) ff = math.modf(v0Log) if math.fabs(ff[0]) <", "== 0: return print >>self.fout, '('+self.seriesTitle+')' while indx >= 0:", "v1 % vInc != 0: v1 = int(v1/vInc)*vInc + vInc", "print >>self.fout, s #--- SeriesNames(names) # def SeriesNames(self, names): indx", "1 logOffset = 0 while t < 1: logOffset +=", "while w/m > 100: m *= 10 if (v0 >=", "= 0 fin = open(fname, 'r') for inputLine in fin:", "'/yfix '+fix+' def\\n/yinc yinc2 def' print >>self.fout, 'axpos axlen add", "= 1 elif w <= 20: vInc = 2 else:", "tMax, 'fname: ', fname p = PsPlot('./p', 'Header', 'SubHeader', 1)", "= ' -r%dx%d ' % (xres, yres) cmdStr = gsPath", "self.xInc, ' div ', 0.0,' add } def\\n' if axis", "r = str(s) + 'K' elif v >= 1: s", ">>self.fout, x print >>self.fout, endFun, type, '\\n' return #--- PlotData(axis,", "'+ res +self.fname+' -c quit' # cmdStr = gsPath +", "open(logFile, 'a') # self.flog = open('./psPlot.out', 'a') if plotsPerPage ==", "= [] indx = 0 oldTime = 0 fin =", "(0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0),", "moveto' print >>self.fout, '/Helvetica findfont 12 scalefont setfont' if self.pageHeader", "print >>self.fout, '/plotBgLevel ', level, 'def\\n' return #--- SetPlotPercentDir(value) def", "factor = 1000 elif ys[-1:] == 'M': yss = ys[:-1]", "scalefont setfont' if self.pageHeader != '': print >>self.fout, '(',self.pageHeader,') show'", "type) # def PlotData(self, axis, xList, yList, zList, id, type):", "'Test', '0.1 in 0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state += 1", "' setrgbcolor } ' return rv #--- SetColorIndx(indx, r, g,", "= v1 - v0 if w == 0: v1 =", "from gs command: ', output return self.foutPath+self.foutName+'.jpg' #--- Main #", "self.xLen print >>self.fout, 'doGraph' return #--- SetXSize(xsize) def SetXSize(self, xsize):", "* m if (v1 % m) != 0: v1 =", "k*y k += 1 print >>self.fout, 'endFunction\\n' print >>self.fout, '18", "'/nextGraph { nextGraph2v } def' else: print >>self.fout, '/doGraph {", "self.x0 - self.xInc - self.xOffset,' sub ', self.xInc, ' div", "xList: self.xDict[x] = k k=k+1 print >>self.fout, '/xfix ', fix,", "self.xCount = 0 self.xList = [] self.xDict = {} self.y1Inc", "grid\\n' print >>self.fout, '/ymtitle ypos ylen add 10 add def\\n'", "self.y1LogScale = v else: self.y2LogScale = v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title)", "if logFlag == 1: print >>self.fout, self.yfix2 print >>self.fout, 'beginFunction\\n'", "r = str(s) + 'M' elif v >= 1000 and", "= vBeg v1 = vEnd logFlag = 1 v0Log =", "n = 0 while True: vList.append(self.ValueConvert(v,vi)) if v > vEnd:", "PlotVBars(xList, type) # def PlotVBars(self, xList, type): flog = self.flog", "and (logFlag==1 or (logFlag==0 and (vEnd/vBeg > 100))): v0 =", ">>self.fout, '/xfix ', fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale)", "== int(s)*d: s = int(s) r = str(s) else: r", "sub ', self.xInc, ' div ', 0.0,' add } def\\n'", "(1,1,1) self.ColorBlack = (0,0,0) self.xSize = 1800 self.ySize = 900", "self.xSize * 6.5 / (1200 * self.xLen)) yres = int(110", "<= 5*m: vInc = m/2 else: vInc = m else:", "sub '+str(vi)+' div }' print >>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')'", "= 'gs' logFile = '/dev/null' #logFile = 'plot.log' #--- class", "== 0: d = 10.0 else: d = 10.0 if", "1 def' self.yfix2 = '/yfix '+fix+' def\\n/yinc yinc2 def' print", "indx == len(xList)-1: continue if len(yList) <= indx: continue y", "-c quit' else: size = ' -g1200x1100 ' cmdStr =", "main(): tMin = 0 tMax = 100000 stateList = [0,1,2,2,3,3,3,3,4]", "self.xCount, k*y k += 1 print >>self.fout, 'endFunction\\n' print >>self.fout,", "time1List = [] time2List = [] indx = 0 oldTime", "{ graph1v } def' print >>self.fout, '/nextGraph { nextGraph1v }", "elif v >= 1000000 and inc > 1: s =", "rv #--- SetColor(color) # def SetColor(self, color): rv = '", "if logFlag == 1: print >>self.fout, 'beginFunction\\n' for ys in", "# if (vMax/f)%vInc != 0 or v1 % vInc !=", "v = 1 else: v = 0; if axis ==", "self.xLen = xlen print >>self.fout, '/xAxisLen %.2f def' % self.xLen", "v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1", ">>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout) if self.plotsPerPage == 1: # size", "== 'M': zss = zs[:-1] factor = 1000000 else: zss", "') for z in zList: self.fout.write('('+str(z)+') ') self.fout.write(' ]') if", "y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv", "= sys.argv[1] elif len(sys.argv) == 3: tMin = int(sys.argv[1]) tMax", "self.y2Inc = 0 self.y2Count = 0 self.y2LogScale = 0 self.xOffset", "factor = 1 if ys[-1:] == 'K': yss = ys[:-1]", "', cmdStr output = commands.getoutput(cmdStr) print >>flog, 'output from gs", "= [ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5),", "!= 0: v0 = int(v0/vInc)*vInc v0 += vInc v0 *=", "print >>self.fout, self.xGrid, self.yGrid, ' grid\\n' print >>self.fout, '/ymtitle ypos", "(f*ff) v1 *= (f*ff) vInc *= (f*ff) return v0, v1,", "End() # def End(self): print >>self.fout, '\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin,", "print >>self.fout, '/doGraph { graph2v } def' print >>self.fout, '/nextGraph", ">>self.fout, 'doGraph' #--- End() # def End(self): print >>self.fout, '\\nshowpage\\nend'", "1 if zs[-1:] == 'K': zss = zs[:-1] factor =", "= v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout,", "- self.xOffset,' sub ', self.xInc, ' div ', 0.0,' add", "separated by '|' print >>self.flog, 'Main Title: '+title titleLines =", "self.flog = open(logFile, 'a') # self.flog = open('./psPlot.out', 'a') if", "in toStateList: if s == state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 +", "} { log '+str(logOffset)+' add } ifelse }' else: logFlag", "0 def\\n' return #--- SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value): if value", "for ys in yList: factor = 1 if ys[-1:] ==", ">>self.fout, '/nextGraph { nextGraph1v } def' print >>self.fout, '/showpage {\\n", "int(s)*d: s = int(s) r = str(s) else: r =", "self.flog print >>flog, 'graph xList: ', self.xList, ' xList: ',", "(indx % 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform", "True v0 = 1 v1 = len(vList) vi = 1", "self.colorsN]) indx -= 1 print >>self.fout, 'fdescriptionsC' #--- PlotVBars(xList, type)", "print >>self.fout, 'doGraph' #--- End() # def End(self): print >>self.fout,", "if v > vEnd: break n += 1 v =", ">>self.fout, '19 { 0 0 0 setrgbcolor } plotSymbolsC\\n' return", "vList = [] n = 0 while True: vList.append(self.ValueConvert(v,vi)) if", "== state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 + s*0.20) indx += 1", "int(v0/vInc)*vInc v0 += vInc v0 *= (f*ff) v1 *= (f*ff)", "logFlag) # def GetAxis(self, vBeg, vEnd, vInc, logFlag): fix =", "indx += 1 if self.xUniform == True: g_indx = self.xDict[x]", "stateList = [0,1,2,2,3,3,3,3,4] fname = 'sched.txt' if len(sys.argv) == 2:", "= -1 elif value == 'On': v = 1 else:", "= 1 if ys[-1:] == 'K': yss = ys[:-1] factor", "v1 = int(v1/f) if (vMin % f) != 0 and", "k=k+1 print >>self.fout, '/xfix ', fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag) =", "== 2: print >>self.fout, self.yfix2 elif axis == 1: print", "yList, zList, id, type): flog = self.flog print >>flog, 'graph", "= yi self.y1Count = len(yList) self.yfix1 = '/yfix '+fix+' def\\n", "div ', 0.0,' add } def\\n' if axis == 2:", "if (vMax/f)%vInc != 0 or v1 % vInc != 0:", "else: endFun = 'endFunction\\n' indx = 0 for x in", "v1 = vEnd logFlag = 1 v0Log = math.log10(v0) t", "self.colorAqua = (0,0.5,0.5) self.colorWhite = (1,1,1) self.ColorBlack = (0,0,0) self.xSize", ">>self.fout, '40 726 moveto\\n (',self.pageSubHeader,') show' print >>self.fout, 'showpage\\n} bind", "< 1: logOffset += 1 t += 1 v0 =", ">>self.fout, 'doGraph' return #--- SetXSize(xsize) def SetXSize(self, xsize): self.xSize =", "xList, yList, zList, id, type): flog = self.flog print >>flog,", "len(xList) self.xList = xList self.xDict = {} k = 1", "float(v)/inc > 1.0: d = 10.0 if v >= 1000000000", "or v1 % vInc != 0: if v1 % vInc", "4: tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) fname = sys.argv[3]", "indx = 0 for s in toStateList: if s ==", "parent? fix = '{ dup 0 eq { } {", "= os.path.dirname(fname)+'/' if self.foutPath == '/': self.foutPath = '' self.foutName", "vInc, logFlag) # def GetAxis(self, vBeg, vEnd, vInc, logFlag): fix", "type): flog = self.flog print >>self.fout, self.yfix1 print >>self.fout, 'beginFunction\\n'", "'{ dup 0 eq { } { log '+str(logOffset)+' add", "[] n = 0 while True: vList.append(self.ValueConvert(v,vi)) if v >", "self.yfix1 print >>self.fout, '[ ' for x in xList: self.fout.write('('+str(x)+')", "= int(v/(1000000000/d))/d if s*d == int(s)*d: s = int(s) r", "' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res +self.fname+' -c quit' # cmdStr", "-r100x100 '+self.fname+' -c quit' print >>flog, 'cmdStr: ', cmdStr output", "v = 0; if axis == 1: self.y1LogScale = v", "else: print >>self.fout, '/plotNumPercentDir 0 def\\n' return #--- SetPlotYLogScale(axis,value) #", "math.pow(10,math.ceil(math.log10(v1))) vi = 1 vList = [] v = v0", "if v0 > 1: logOffset -= (math.log10(v0) - 1) #", "fin = open(fname, 'r') for inputLine in fin: inputLine =", ">>self.fout, 'Mtitles\\n' # print >>self.fout, '('+title+')\\nMtitles\\n' if logFlag == 1:", "elif len(sys.argv) == 3: tMin = int(sys.argv[1]) tMax = int(sys.argv[2])", ">>self.fout, 'showpage\\n} bind def' print >>self.fout, 'doGraph' #--- End() #", "return rv #--- GetColorIndx(indx) # def GetColorIndx(self, indx): color =", "s*d == int(s)*d: s = int(s) r = str(s) +", "print >>self.flog, 'vList: ', vList print >>self.flog, 'logFlag: ', logFlag,", "SetYSize(self, ysize): self.ySize = ysize return #--- SetPlotBgLevel(level) # def", "self.yfix1 print >>self.fout, 'beginFunction\\n' endFun = 'endFunction\\n' indx = 0", "print >>flog, 'cmdStr: ', cmdStr output = commands.getoutput(cmdStr) print >>flog,", "t2List = [] sList = [] indx = 0 for", "= int(w/f) v0 = int(v0/f) v1 = int(v1/f) if (vMin", "# self.flog = open('./psPlot.out', 'a') if plotsPerPage == 4: print", "print >>self.fout, '(',self.pageHeader,') show' if self.pageSubHeader != '': print >>self.fout,", "x == ' ' and indx == len(xList)-1: continue if", "' -r%dx%d ' % (xres, yres) cmdStr = gsPath +", "= gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res +self.fname+' -c", "isinstance(zList,list): if len(zList) <= indx: continue z = zList[indx] else:", "'\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin, vMax) def GetInc(self,vMin, vMax): ff =", "self.fout = open(self.fname, 'a') self.flog = open(logFile, 'a') # self.flog", "if zs[-1:] == 'K': zss = zs[:-1] factor = 1000", "- self.xInc - self.xOffset,' sub ', self.xInc, ' div ',", "elif v >= 1: s = int(v*d)/d if s*d ==", "= 0 while state <= 4: t1List = [] t2List", "vMax) def GetInc(self,vMin, vMax): ff = 1.0 while vMax <=", "= 1 while w/f >= 100: f *= 10 #", "= 0 v = v0 vList = [] n =", "# xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag)", "s): print >>self.fout, s #--- SeriesNames(names) # def SeriesNames(self, names):", "= 1 else: v = 0; if axis == 1:", "+ ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' else: size", "'+title titleLines = title.split('|') for t in titleLines: if len(t)", "inputLine.find('(') i2 = inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])]", "len(zList) print >>self.fout, '/Flag2Yaxes 1 def' self.yfix2 = '/yfix '+fix+'", "= 0 else: if vInc == 0: v0,v1,vi = self.GetInc(vBeg,vEnd)", "tMin = 0 tMax = 100000 stateList = [0,1,2,2,3,3,3,3,4] fname", "= PsPlot('./p', 'Header', 'SubHeader', 1) fromStateList = [] toStateList =", "pageSubHeader, plotsPerPage) # class PsPlot(object): def __init__(self, fname, pageHeader, pageSubHeader,", "toStateList: if s == state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 + s*0.20)", "xsize): self.xSize = xsize return #--- SetYSize(ysize) def SetYSize(self, ysize):", "1 print >>self.fout, 'fdescriptionsC' #--- PlotVBars(xList, type) # def PlotVBars(self,", "plotsPerPage == 2: print >>self.fout, '/doGraph { graph2v } def'", "id, type) # def PlotData(self, axis, xList, yList, zList, id,", "int(100 * self.xSize * 6.5 / (1200 * self.xLen)) yres", "names): indx = len(names) - 1 if indx == 0:", "= int(v0/f) v1 = int(v1/f) if (vMin % f) !=", "logFile = '/dev/null' #logFile = 'plot.log' #--- class PsPlot(fname, pageHeader,", "self.xDict[x] print >>self.fout, g_indx, y, z else: print >>self.fout, x,", "(0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ] self.colorsN = 11 self.colorRed", "/ m) * m if (v1 % m) != 0:", "cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+' -c", "3: print >>self.fout, '/doGraph { graph3v } def' print >>self.fout,", "= 0 for x in xList: if x == '", "sys.argv[1] elif len(sys.argv) == 3: tMin = int(sys.argv[1]) tMax =", "PsPlot(object): def __init__(self, fname, pageHeader, pageSubHeader, plotsPerPage): self.foutPath = os.path.dirname(fname)+'/'", "= 0 self.y2Inc = 0 self.y2Count = 0 self.y2LogScale =", "1000000 else: zss = zs y = float(zss)*factor/10.0 k =", "stateList[int(inputList[0])] s2 = stateList[int(inputList[1])] t = int(inputList[2]) if indx !=", "10.0 if v >= 1000000000 and inc > 1: s", "self.yfix1 = '/yfix '+fix+' def\\n /yinc yinc1 def' print >>self.fout,", "print >>self.fout, x, y, z print >>self.fout, endFun, type, '\\n'", "m) * m if (v1 % m) != 0: v1", "m/2 else: vInc = m else: vInc = m #", "}' print >>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')' print >>self.flog, 'vList:", "= 0 self.y2Count = 0 self.y2LogScale = 0 self.xOffset =", "endFun+type+'\\nbeginFunction\\n' print >>self.fout, x print >>self.fout, endFun, type, '\\n' return", "!= '': print >>self.fout, '('+ztitle+') vaxis2' if logFlag == 1:", "[] sList = [] indx = 0 for s in", "= float(yss)*factor/10.0 k = 2 while k < 10: print", "10 if v0 > 1: logOffset -= (math.log10(v0) - 1)", "v1 % vInc != 0: if v1 % vInc !=", "self.fout.write('('+str(z)+') ') self.fout.write(' ]') if ztitle != '': print >>self.fout,", "0 self.xInc = 0 self.xCount = 0 self.xList = []", "self.xInc = 0 self.xCount = 0 self.xList = [] self.xDict", "= [] n = 0 while True: vList.append(self.ValueConvert(v,vi)) if v", "yss = ys y = float(yss)*factor/10.0 k = 2 while", "len(t) > 0: print >>self.flog, ' '+t print >>self.fout, '('+t+')\\n'", "[] t2List = [] sList = [] indx = 0", "shutil.copy('plot-header.ps', self.fname) self.fout = open(self.fname, 'a') self.flog = open(logFile, 'a')", ">>self.fout, 'beginFunction\\n' for ys in yList: factor = 1 if", "print >>self.fout, '/Helvetica findfont 12 scalefont setfont' if self.pageHeader !=", "== 1: # size = ' -g1200x550 ' size =", "'\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0 self.xInc =", "*= 0.10 vMin *= 10 vMax *= 10 v0 =", "# def SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel ', level, 'def\\n' return", "!= '': print >>self.fout, '(',self.pageHeader,') show' if self.pageSubHeader != '':", "(0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0)", "= {} k = 1 for x in xList: self.xDict[x]", "v1 *= (f*ff) vInc *= (f*ff) return v0, v1, vInc", "40 742 moveto' print >>self.fout, '/Helvetica findfont 12 scalefont setfont'", "+ 'K' elif v >= 1: s = int(v*d)/d if", "') self.xUniform = True v0 = 1 v1 = len(vList)", "{ graph4v } def' print >>self.fout, '/nextGraph { nextGraph4v }", "break n += 1 v = v0 + n*vi fix", "and t >= tMin and t <= tMax: fromStateList.append(s1) toStateList.append(s2)", "100: f *= 10 # w = int(w/f) v0 =", "-dNOPAUSE -r100x100 '+self.fname+' -c quit' else: size = ' -g1200x1100", "y, z if (indx != 0) and (indx % 1000)", "if self.pageSubHeader != '': print >>self.fout, '40 726 moveto\\n (',self.pageSubHeader,')", "z if (indx != 0) and (indx % 1000) ==", "'gs' logFile = '/dev/null' #logFile = 'plot.log' #--- class PsPlot(fname,", "= '' self.xGrid = 1 self.yGrid = 1 self.xUniform =", "print >>self.flog, 'Main Title: '+title titleLines = title.split('|') for t", "flog = self.flog print >>self.fout, self.yfix1 print >>self.fout, 'beginFunction\\n' endFun", "= 1.0 while vMax <= 1 and vMax > 0:", "in xList: if x == ' ' and indx ==", "vMin *= 10 vMax *= 10 v0 = int(vMin) v1", "> 0: logInc = int(math.log10(v/inc)) d = math.pow(10,logInc) if d", "v1 = int(vMax+0.99) f = 1 w = v1 -", "self.xCount = len(xList) self.xList = xList self.xDict = {} k", "int(s) r = str(s) + 'K' elif v >= 1:", "self.GetInc(vBeg,vEnd) else: v0 = vBeg v1 = vEnd vi =", "y, z else: print >>self.fout, x, y, z if (indx", "'beginFunction\\n' for ys in yList: factor = 1 if ys[-1:]", "self.seriesTitle = ' ' self.x0 = 0 self.xInc = 0", "= ' -g%dx%d ' % (self.xSize, self.ySize) xres = int(100", "print >>self.fout, self.yfix2 elif axis == 1: print >>self.fout, self.yfix1", ">>self.fout, g_indx, y, z else: print >>self.fout, x, y, z", "v = -1 elif value == 'On': v = 1", "== ' ' and indx == len(xList)-1: continue if len(yList)", "= '/usr/local/bin/gs' gsPath = 'gs' logFile = '/dev/null' #logFile =", "'K' elif v >= 1: s = int(v*d)/d if s*d", "def SetPlotYLogScale(self,axis,value): if value == 'Off': v = -1 elif", ">>self.fout, '/xAxisLen %.2f def' % self.xLen print >>self.fout, 'doGraph' return", "print >>self.fout, '/xAxisLen %.2f def' % self.xLen print >>self.fout, 'doGraph'", "+ vInc if (v0 % vInc) != 0: v0 =", "yList: factor = 1 if ys[-1:] == 'K': yss =", "zss = zs[:-1] factor = 1000 elif zs[-1:] == 'M':", "{ graph2v } def' print >>self.fout, '/nextGraph { nextGraph2v }", "#--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if value == 'Vertical': print >>self.fout,", "= vEnd vi = vInc if vBeg > 0 and", "nextGraph2v } def' else: print >>self.fout, '/doGraph { graph1v }", "% (self.xSize, self.ySize) xres = int(100 * self.xSize * 6.5", "') print >>self.fout, ' ]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout,", "v0 = 1 v1 = len(vList) vi = 1 fix", "= int(inputList[2]) if indx != 0 and t >= tMin", "(0.8,0.0,0.0), (0,0,0) ] self.colorsN = 11 self.colorRed = (0.8,0,0) self.colorGreen", "self.ySize = 900 shutil.copy('plot-header.ps', self.fname) self.fout = open(self.fname, 'a') self.flog", "* self.ySize / 550) res = ' -r%dx%d ' %", "= 1 if zs[-1:] == 'K': zss = zs[:-1] factor", "742 moveto' print >>self.fout, '/Helvetica findfont 12 scalefont setfont' if", "s = int(v/(1000/d))/d if s*d == int(s)*d: s = int(s)", "'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')' print >>self.flog, 'vList: ', vList print", ">>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')' print >>self.flog, 'vList: ', vList", "if ys[-1:] == 'K': yss = ys[:-1] factor = 1000", "% m) != 0: v0 = int(v0 / m) *", "for t in titleLines: if len(t) > 0: print >>self.flog,", "self.ySize / 550) res = ' -r%dx%d ' % (xres,", "{} k = 1 for x in xList: self.xDict[x] =", "print >>flog, 'output from gs command: ', output return self.foutPath+self.foutName+'.jpg'", "self.yGrid = 1 self.xUniform = False self.xLen = 6.5 #inches", "= 1000 elif ys[-1:] == 'M': yss = ys[:-1] factor", "+ 'M' elif v >= 1000 and inc > 1:", "self.colorWhite = (1,1,1) self.ColorBlack = (0,0,0) self.xSize = 1800 self.ySize", "nextGraph4v } def' elif plotsPerPage == 3: print >>self.fout, '/doGraph", "= (1,1,1) self.ColorBlack = (0,0,0) self.xSize = 1800 self.ySize =", "return self.foutPath+self.foutName+'.jpg' #--- Main # def main(): tMin = 0", "zList: self.fout.write('('+str(z)+') ') self.fout.write(' ]') if ztitle != '': print", "'/usr/local/bin/gs' gsPath = 'gs' logFile = '/dev/null' #logFile = 'plot.log'", "!= None: print >>self.fout, '('+names[indx]+') ' print >>self.fout, self.SetColor(self.colors[indx %", "size = ' -g1200x550 ' size = ' -g%dx%d '", "tMax, 0, 0, 2, 0, 'Time', 'Socket/State', 'Chavey\\'s Plot') state", "t2List, sList, 'Test', '0.1 in 0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state", "(indx != 0) and (indx % 1000) == 0: print", "open(self.fname, 'a') self.flog = open(logFile, 'a') # self.flog = open('./psPlot.out',", "' for x in xList: self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[ ')", "self.colorRed = (0.8,0,0) self.colorGreen = (0,0.8,0) self.colorBlue = (0,0,0.8) self.colorAqua", "math.modf(v0Log) if math.fabs(ff[0]) < math.fabs(v0Log)/1000 and t < 0: t", "xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title): rv = self.SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) (z0,z1,zi,zList,fix,logFlag) =", "= 10 while w/m > 100: m *= 10 if", "== '/': self.foutPath = '' self.foutName = os.path.basename(fname) self.fname =", "0: print >>self.flog, ' '+t print >>self.fout, '('+t+')\\n' print >>self.fout,", "= x0 self.xInc = xi self.xCount = len(xList) self.xList =", "'cmdStr: ', cmdStr output = commands.getoutput(cmdStr) print >>flog, 'output from", "self.y1Count = 0 self.y1LogScale = 0 self.y2Inc = 0 self.y2Count", "== 2: print >>self.fout, '/doGraph { graph2v } def' print", "- 1 if indx == 0: return print >>self.fout, '('+self.seriesTitle+')'", "{ nextGraph1v } def' print >>self.fout, '/showpage {\\n 40 742", "aylen' self.fout.write('[ ') for z in zList: self.fout.write('('+str(z)+') ') self.fout.write('", "= 0; if axis == 1: self.y1LogScale = v else:", "type) # def PlotVBars(self, xList, type): flog = self.flog print", "}' else: logFlag = 0 v = v0 vList =", "xList: self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[ ') for y in yList:", "z else: print >>self.fout, x, y, z print >>self.fout, endFun,", "0 and vMax == v1: v1 += 1 w =", "print >>self.fout, '[ ' for x in xList: self.fout.write('('+str(x)+') ')", "# size = ' -g1200x550 ' size = ' -g%dx%d", "= ysize return #--- SetPlotBgLevel(level) # def SetPlotBgLevel(self,level): print >>self.fout,", "continue z = zList[indx] else: z = '' indx +=", "if self.plotsPerPage == 1: # size = ' -g1200x550 '", "return rv #--- SetColorIndx(indx, r, g, b) # def SetColorIndx(self,", "Plot') state = 0 while state <= 4: t1List =", "= 11 self.colorRed = (0.8,0,0) self.colorGreen = (0,0.8,0) self.colorBlue =", "vMax): ff = 1.0 while vMax <= 1 and vMax", "s = int(s) r = str(s) + 'K' elif v", "'Main Title: '+title titleLines = title.split('|') for t in titleLines:", ">>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform == True: print >>self.fout, g_indx, y,", "'' self.xGrid = 1 self.yGrid = 1 self.xUniform = False", ">>self.fout, '/nextGraph { nextGraph4v } def' elif plotsPerPage == 3:", "'/yfix '+fix+' def\\n /yinc yinc1 def' print >>self.fout, self.yfix1 print", "1 from above inside parent? fix = '{ dup 0", "== int(s)*d: s = int(s) r = str(s) + 'K'", "\\ ' setrgbcolor } ' return rv #--- SetColorIndx(indx, r,", ">>flog, 'graph xList: ', self.xList, ' xList: ', xList, \\", "# class PsPlot(object): def __init__(self, fname, pageHeader, pageSubHeader, plotsPerPage): self.foutPath", "print >>self.fout, 'fdescriptionsC' #--- PlotVBars(xList, type) # def PlotVBars(self, xList,", "graph4v } def' print >>self.fout, '/nextGraph { nextGraph4v } def'", "v1, vInc #--- ValueConvert(v) # def ValueConvert(self, v, inc): if", "by '|' print >>self.flog, 'Main Title: '+title titleLines = title.split('|')", "# def ValueConvert(self, v, inc): if inc > 0: logInc", ">>self.fout, '/plotBgLevel ', level, 'def\\n' return #--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value):", "0 self.xCount = 0 self.xList = [] self.xDict = {}", ">= tMin and t <= tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t)", "value == 'Vertical': print >>self.fout, '/plotNumPercentDir 1 def\\n' else: print", "if (indx != 0) and (indx % 1000) == 0:", "y in yList: self.fout.write('('+str(y)+') ') print >>self.fout, ' ]' print", "= {} self.y1Inc = 0 self.y1Count = 0 self.y1LogScale =", "m *= 10 if (v0 >= 0) and (v0 %", "Multiple lines in title are separated by '|' print >>self.flog,", "1 if ys[-1:] == 'K': yss = ys[:-1] factor =", "self.colorsN] rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ '", "vInc = m # if (vMax/f)%vInc != 0 or v1", "return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n'", "xList: ', self.xList, ' xList: ', xList, \\ ' yList:", "') self.fout.write(' ]\\n[ ') for y in yList: self.fout.write('('+str(y)+') ')", "'Mtitles\\n' # print >>self.fout, '('+title+')\\nMtitles\\n' if logFlag == 1: print", "[] toStateList = [] time1List = [] time2List = []", "= gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit'", "print >>self.fout, '/Flag2Yaxes 1 def' self.yfix2 = '/yfix '+fix+' def\\n/yinc", "in xList: self.xDict[x] = k k=k+1 print >>self.fout, '/xfix ',", "def SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel ', level, 'def\\n' return #---", "titleLines = title.split('|') for t in titleLines: if len(t) >", "d == 0: d = 10.0 else: d = 10.0", "y = float(zss)*factor/10.0 k = 2 while k < 10:", "zList: factor = 1 if zs[-1:] == 'K': zss =", "inputLine = inputLine.replace(' ','') inputLine = inputLine.replace(\"'\", '') i1 =", "time2List.append(t) oldTime = t indx += 1 p.SetPlot(tMin, tMax, 0,", "quit' # cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100", "-sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE '+ res +self.fname+' -c quit' # cmdStr =", "0 else: if vInc == 0: v0,v1,vi = self.GetInc(vBeg,vEnd) else:", "ValueConvert(v) # def ValueConvert(self, v, inc): if inc > 0:", "w <= 20: vInc = 2 else: m = 10", ">>self.fout, '18 { 0.72 0.52 0.5 setrgbcolor } plotSymbolsC\\n' return", "', fix, ' def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc =", "g, b) # def SetColorIndx(self, indx, r, g, b): self.colors[indx][0]", "ifelse }' else: logFlag = 0 v = v0 vList", "= float(zss)*factor/10.0 k = 2 while k < 10: print", "= [] time1List = [] time2List = [] indx =", "= stateList[int(inputList[0])] s2 = stateList[int(inputList[1])] t = int(inputList[2]) if indx", "# def GetImage(self): flog = self.flog print >>self.fout, 'showpage\\n' self.fout.flush()", "#logFile = 'plot.log' #--- class PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage) #", "lines in title are separated by '|' print >>self.flog, 'Main", "w = 1 while w/f >= 100: f *= 10", "m # if (vMax/f)%vInc != 0 or v1 % vInc", "#--- class PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage) # class PsPlot(object): def", "' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ ' setrgbcolor } '", "< math.fabs(v0Log)/1000 and t < 0: t += 1 logOffset", "ys[-1:] == 'K': yss = ys[:-1] factor = 1000 elif", "[0,1,2,2,3,3,3,3,4] fname = 'sched.txt' if len(sys.argv) == 2: fname =", ">>self.fout, s #--- SeriesNames(names) # def SeriesNames(self, names): indx =", "= open(fname, 'r') for inputLine in fin: inputLine = inputLine.replace('", "elif len(sys.argv) == 4: tMin = int(sys.argv[1]) tMax = int(sys.argv[2])", "k += 1 print >>self.fout, 'endFunction\\n' print >>self.fout, '19 {", "[ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5),", "x0 self.xInc = xi self.xCount = len(xList) self.xList = xList", "logFlag = 0 v = v0 vList = [] n", "def GetInc(self,vMin, vMax): ff = 1.0 while vMax <= 1", "else: z = '' indx += 1 if self.xUniform ==", "'': print >>self.fout, '40 726 moveto\\n (',self.pageSubHeader,') show' print >>self.fout,", "0 while state <= 4: t1List = [] t2List =", "yres = int(110 * self.ySize / 550) res = '", "# def SetColorIndx(self, indx, r, g, b): self.colors[indx][0] = r", "'+str(color[2])+ \\ ' setrgbcolor } ' return rv #--- GetColorIndx(indx)", "int(v1/f) if (vMin % f) != 0 and vMax ==", "} ifelse }' else: logFlag = 0 v = v0", "self.xUniform = True v0 = 1 v1 = len(vList) vi", "math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1))) vi = 1 vList = []", "x, y, z if (indx != 0) and (indx %", "if len(zList) <= indx: continue z = zList[indx] else: z", "}' if isinstance(vBeg,list): vList = vBeg vList.append(' ') self.xUniform =", "= k k=k+1 print >>self.fout, '/xfix ', fix, ' def\\n'", ">= 1000000000 and inc > 1: s = int(v/(1000000000/d))/d if", "# def GetAxis(self, vBeg, vEnd, vInc, logFlag): fix = '{", "os.path.dirname(fname)+'/' if self.foutPath == '/': self.foutPath = '' self.foutName =", "*= 10 if (v0 >= 0) and (v0 % m)", "#--- PlotData(axis, xList, yList, zList, id, type) # def PlotData(self,", "'tMin,tMax: ', tMin, tMax, 'fname: ', fname p = PsPlot('./p',", "== 'On': v = 1 else: v = 0; if", "self.yGrid, ' grid\\n' print >>self.fout, '/ymtitle ypos ylen add 10", "vInc v0 *= (f*ff) v1 *= (f*ff) vInc *= (f*ff)", "return v0, v1, vInc #--- ValueConvert(v) # def ValueConvert(self, v,", "- v0 if w == 0: v1 = v0 +", "level, 'def\\n' return #--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if value ==", "bind def' print >>self.fout, 'doGraph' #--- End() # def End(self):", "int(s) r = str(s) else: r = str(int(v*100)/100.0) return r", "self.foutPath+self.foutName+'.jpg' #--- Main # def main(): tMin = 0 tMax", "show' if self.pageSubHeader != '': print >>self.fout, '40 726 moveto\\n", "(0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ] self.colorsN =", "#--- SetXSize(xsize) def SetXSize(self, xsize): self.xSize = xsize return #---", "int(110 * self.ySize / 550) res = ' -r%dx%d '", "# else: # print >>self.fout, '/yfix { 0 add }", "plotSymbolsC\\n' return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc,", "res = ' -r%dx%d ' % (xres, yres) cmdStr =", "print >>self.fout, endFun, type, '\\n' return #--- GetImage() # def", "1000 elif ys[-1:] == 'M': yss = ys[:-1] factor =", "s*0.20) indx += 1 p.PlotData(1,t1List, t2List, sList, 'Test', '0.1 in", "= len(xList) self.xList = xList self.xDict = {} k =", "else: size = ' -g1200x1100 ' cmdStr = gsPath +", "== len(xList)-1: continue if len(yList) <= indx: continue y =", "x print >>self.fout, endFun, type, '\\n' return #--- PlotData(axis, xList,", "!= 0) and (indx % 1000) == 0: print >>self.fout,", "vInc != 0: v1 = int(v1/vInc)*vInc + vInc if (v0", "int(w/f) v0 = int(v0/f) v1 = int(v1/f) if (vMin %", "= len(vList) vi = 1 fix = '{ '+str(v0-vi)+' sub", "self.xDict[x] = k k=k+1 print >>self.fout, '/xfix ', fix, '", "print >>self.fout, '('+t+')\\n' print >>self.fout, 'Mtitles\\n' # print >>self.fout, '('+title+')\\nMtitles\\n'", "% 1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform ==", "v0 = math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1))) vi = 1 vList", "'('+title+')\\nMtitles\\n' if logFlag == 1: print >>self.fout, 'beginFunction\\n' for ys", "y = yList[indx] if isinstance(zList,list): if len(zList) <= indx: continue", "def' print >>self.fout, '/nextGraph { nextGraph1v } def' print >>self.fout,", "def __init__(self, fname, pageHeader, pageSubHeader, plotsPerPage): self.foutPath = os.path.dirname(fname)+'/' if", "self.SetColor(self.colors[indx % self.colorsN]) indx -= 1 print >>self.fout, 'fdescriptionsC' #---", "= self.flog print >>self.fout, self.yfix1 print >>self.fout, 'beginFunction\\n' endFun =", "else: m = 10 while w/m > 100: m *=", "= int(s) r = str(s) else: r = str(int(v*100)/100.0) return", "output return self.foutPath+self.foutName+'.jpg' #--- Main # def main(): tMin =", "fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div }' logFlag =", "s1 = stateList[int(inputList[0])] s2 = stateList[int(inputList[1])] t = int(inputList[2]) if", "vBeg, vEnd, vInc, logFlag): fix = '{ 0 add }'", "def outputPS(self, s): print >>self.fout, s #--- SeriesNames(names) # def", "t <= tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime = t", "0 self.colors = [ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8),", "graph3v } def' print >>self.fout, '/nextGraph { nextGraph3v } def'", "] self.colorsN = 11 self.colorRed = (0.8,0,0) self.colorGreen = (0,0.8,0)", ">>self.fout, 'beginFunction\\n' for zs in zList: factor = 1 if", "size = ' -g1200x1100 ' cmdStr = gsPath + '", "1 print >>self.fout, 'endFunction\\n' print >>self.fout, '19 { 0 0", "= zs y = float(zss)*factor/10.0 k = 2 while k", "in zList: factor = 1 if zs[-1:] == 'K': zss", "= str(s) + 'G' elif v >= 1000000 and inc", "v0 = int(vMin) v1 = int(vMax+0.99) f = 1 w", "(logFlag==0 and (vEnd/vBeg > 100))): v0 = vBeg v1 =", "', fname p = PsPlot('./p', 'Header', 'SubHeader', 1) fromStateList =", "from above inside parent? fix = '{ dup 0 eq", "self.xList, ' xList: ', xList, \\ ' yList: ', yList", "Plot '+id+'\\n%\\n' print >>self.fout, '/xfix { ', self.x0 - self.xInc", "self.colors = [ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0),", "10: vInc = 1 elif w <= 20: vInc =", "11 self.colorRed = (0.8,0,0) self.colorGreen = (0,0.8,0) self.colorBlue = (0,0,0.8)", "(0.8,0,0), (0.42,0.55,0.14), (0.6,0.5,0.3), (0.6,0.2,0.8), (0,0.8,0), (0.4,0.3,0.5), (0.5,0.5,0.5), (0.8,0.0,0.0), (0,0,0) ]", "0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout, x print >>self.fout, endFun,", "ValueConvert(self, v, inc): if inc > 0: logInc = int(math.log10(v/inc))", "p.PlotData(1,t1List, t2List, sList, 'Test', '0.1 in 0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout)", "k = 2 while k < 10: print >>self.fout, self.xCount,", "= m # if (vMax/f)%vInc != 0 or v1 %", "v1 = int(v1 / m) * m + m w", "<= tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime = t indx", "= '' self.yfix2 = '' self.xGrid = 1 self.yGrid =", "(z0,z1,zi,zList,fix,logFlag) = self.GetAxis(zbeg,zend,zinc,self.y2LogScale) self.y2Inc = zi self.y2Count = len(zList) print", ">>self.fout, '(',self.pageHeader,') show' if self.pageSubHeader != '': print >>self.fout, '40", "(f*ff) return v0, v1, vInc #--- ValueConvert(v) # def ValueConvert(self,", "if len(yList) <= indx: continue y = yList[indx] if isinstance(zList,list):", "def' elif plotsPerPage == 3: print >>self.fout, '/doGraph { graph3v", "def main(): tMin = 0 tMax = 100000 stateList =", "1) fromStateList = [] toStateList = [] time1List = []", "print >>self.fout, self.yfix1 print >>self.fout, 'beginFunction\\n' endFun = 'endFunction\\n' indx", "self.fout.write('[ ') for z in zList: self.fout.write('('+str(z)+') ') self.fout.write(' ]')", "= (0,0.8,0) self.colorBlue = (0,0,0.8) self.colorAqua = (0,0.5,0.5) self.colorWhite =", "= 900 shutil.copy('plot-header.ps', self.fname) self.fout = open(self.fname, 'a') self.flog =", "'/': self.foutPath = '' self.foutName = os.path.basename(fname) self.fname = fname+'.ps'", "1 for x in xList: self.xDict[x] = k k=k+1 print", "'/plotNumPercentDir 1 def\\n' else: print >>self.fout, '/plotNumPercentDir 0 def\\n' return", "(0,0,0) ] self.colorsN = 11 self.colorRed = (0.8,0,0) self.colorGreen =", "1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform == True:", "'/Flag2Yaxes 1 def' self.yfix2 = '/yfix '+fix+' def\\n/yinc yinc2 def'", "2: fname = sys.argv[1] elif len(sys.argv) == 3: tMin =", "> 1.0: d = 10.0 if v >= 1000000000 and", "0.72 0.52 0.5 setrgbcolor } plotSymbolsC\\n' return rv #--- SetColor(color)", "else: v0 = vBeg v1 = vEnd vi = vInc", "0 self.y2Count = 0 self.y2LogScale = 0 self.xOffset = 0", "commands.getoutput(cmdStr) print >>flog, 'output from gs command: ', output return", "} ' return rv #--- GetColorIndx(indx) # def GetColorIndx(self, indx):", "PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage) # class PsPlot(object): def __init__(self, fname,", "v1 = v0 + 1 w = 1 while w/f", "GetColorIndx(self, indx): color = self.colors[indx % self.colorsN] rv = '", "print >>self.fout, '/plotNumPercentDir 1 def\\n' else: print >>self.fout, '/plotNumPercentDir 0", "2 while k < 10: print >>self.fout, self.xCount, k*y k", "Title: '+title titleLines = title.split('|') for t in titleLines: if", ">>self.fout, endFun, type, '\\n' return #--- GetImage() # def GetImage(self):", "= int(v1 / m) * m + m w =", "def' print >>self.fout, 'doGraph' #--- End() # def End(self): print", "(v0 >= 0) and (v0 % m) != 0: v0", "' xList: ', xList, \\ ' yList: ', yList print", "if inc > 0: logInc = int(math.log10(v/inc)) d = math.pow(10,logInc)", "if indx == 0: return print >>self.fout, '('+self.seriesTitle+')' while indx", "s = int(s) r = str(s) else: r = str(int(v*100)/100.0)", "= '/dev/null' #logFile = 'plot.log' #--- class PsPlot(fname, pageHeader, pageSubHeader,", ">= 100: f *= 10 # w = int(w/f) v0", "def' print >>self.fout, self.yfix1 print >>self.fout, '[ ' for x", "factor = 1000000 else: zss = zs y = float(zss)*factor/10.0", "0 fin = open(fname, 'r') for inputLine in fin: inputLine", "log '+str(logOffset)+' add } ifelse }' else: logFlag = 0", "inside parent? fix = '{ dup 0 eq { }", "} plotSymbolsC\\n' return rv #--- SetColor(color) # def SetColor(self, color):", "% vInc) != 0: v0 = int(v0/vInc)*vInc v0 += vInc", "6.5 / (1200 * self.xLen)) yres = int(110 * self.ySize", "nextGraph3v } def' elif plotsPerPage == 2: print >>self.fout, '/doGraph", "self.fout.write('('+str(y)+') ') print >>self.fout, ' ]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print", "+= 1 print >>self.fout, x, 0.0 if (indx != 0)", "print >>self.fout, g_indx, y, z else: print >>self.fout, x, y,", "(0.8,0,0) self.colorGreen = (0,0.8,0) self.colorBlue = (0,0,0.8) self.colorAqua = (0,0.5,0.5)", "for inputLine in fin: inputLine = inputLine.replace(' ','') inputLine =", "def SetYSize(self, ysize): self.ySize = ysize return #--- SetPlotBgLevel(level) #", "print >>self.fout, '/nextGraph { nextGraph2v } def' else: print >>self.fout,", "#--- outputPS(string) # def outputPS(self, s): print >>self.fout, s #---", "= vBeg v1 = vEnd vi = vInc if vBeg", "0; if axis == 1: self.y1LogScale = v else: self.y2LogScale", "#gsPath = '/usr/local/bin/gs' gsPath = 'gs' logFile = '/dev/null' #logFile", "if names[indx] != None: print >>self.fout, '('+names[indx]+') ' print >>self.fout,", "-= (math.log10(v0) - 1) # substract 1 from above inside", "= b return rv #--- outputPS(string) # def outputPS(self, s):", ">>self.fout, 'beginFunction\\n' endFun = 'endFunction\\n' indx = 0 for x", "yss = ys[:-1] factor = 1000 elif ys[-1:] == 'M':", "= ys y = float(yss)*factor/10.0 k = 2 while k", "+= vInc v0 *= (f*ff) v1 *= (f*ff) vInc *=", "pageSubHeader self.plotsPerPage = plotsPerPage self.yfix1 = '' self.yfix2 = ''", "self.ColorBlack = (0,0,0) self.xSize = 1800 self.ySize = 900 shutil.copy('plot-header.ps',", "= '/yfix '+fix+' def\\n /yinc yinc1 def' print >>self.fout, self.yfix1", "self.xOffset,' sub ', self.xInc, ' div ', 0.0,' add }", ">>self.fout, '/plotNumPercentDir 0 def\\n' return #--- SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value):", "int(math.log10(v/inc)) d = math.pow(10,logInc) if d == 0: d =", "'+fix+' def\\n/yinc yinc2 def' print >>self.fout, 'axpos axlen add aypos", "True: vList.append(self.ValueConvert(v,vi)) if v > vEnd: break n += 1", "r, g, b): self.colors[indx][0] = r self.colors[indx][1] = g self.colors[indx][2]", "endFun, type, '\\n' return #--- GetImage() # def GetImage(self): flog", "logFlag): fix = '{ 0 add }' if isinstance(vBeg,list): vList", "= 0 self.xList = [] self.xDict = {} self.y1Inc =", "print 'tMin,tMax: ', tMin, tMax, 'fname: ', fname p =", "'+self.fname+' -c quit' else: size = ' -g1200x1100 ' cmdStr", "axis == 2: print >>self.fout, self.yfix2 elif axis == 1:", "k < 10: print >>self.fout, self.xCount, k*y k += 1", "'/xfix { ', self.x0 - self.xInc - self.xOffset,' sub ',", "= str(s) else: r = str(int(v*100)/100.0) return r #--- GetAxis(vBeg,", "and indx == len(xList)-1: continue indx += 1 print >>self.fout,", "10 if (v0 >= 0) and (v0 % m) !=", "time1List.append(oldTime) time2List.append(t) oldTime = t indx += 1 p.SetPlot(tMin, tMax,", "tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) fname = sys.argv[3] elif", "1: s = int(v/(1000/d))/d if s*d == int(s)*d: s =", "# substract 1 from above inside parent? fix = '{", "0 0 0 setrgbcolor } plotSymbolsC\\n' return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc,", ">>self.fout, '('+ztitle+') vaxis2' if logFlag == 1: print >>self.fout, self.yfix2", "setfont' if self.pageHeader != '': print >>self.fout, '(',self.pageHeader,') show' if", "SetColorIndx(self, indx, r, g, b): self.colors[indx][0] = r self.colors[indx][1] =", "output = commands.getoutput(cmdStr) print >>flog, 'output from gs command: ',", "1 v0 = math.pow(10,math.floor(v0Log)+1) v1 = math.pow(10,math.ceil(math.log10(v1))) vi = 1", "= ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\ ' setrgbcolor }", "'+t print >>self.fout, '('+t+')\\n' print >>self.fout, 'Mtitles\\n' # print >>self.fout,", "def PlotVBars(self, xList, type): flog = self.flog print >>self.fout, self.yfix1", "state += 1 image = p.GetImage(sys.stdout) print 'Image file: ',", "len(sys.argv) == 3: tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) elif", "self.xList = xList self.xDict = {} k = 1 for", "]' print >>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid, self.yGrid, ' grid\\n'", "return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title) # def SetPlot2(self,xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, xtitle,ytitle,ztitle,title):", "% vInc != 0: v1 = int(v1/vInc)*vInc + vInc if", "'+str(v0-vi)+' sub '+str(vi)+' div }' print >>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,'", "v1 - v0 if w == 0: v1 = v0", "# cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+'", "= v1 - v0 if w <= 5*m: vInc =", "self.yfix1 = '' self.yfix2 = '' self.xGrid = 1 self.yGrid", "s in toStateList: if s == state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10", "print >>self.fout, '/yfix { 0 add } def\\n' print >>self.fout,", "print >>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform == True: print >>self.fout, g_indx,", "inputLine = inputLine.replace(\"'\", '') i1 = inputLine.find('(') i2 = inputLine.find(')')", "if (v0 % vInc) != 0: v0 = int(v0/vInc)*vInc v0", "v > vEnd: break n += 1 v = v0", "* self.xLen)) yres = int(110 * self.ySize / 550) res", "= ' ' self.x0 = 0 self.xInc = 0 self.xCount", "{ graph3v } def' print >>self.fout, '/nextGraph { nextGraph3v }", ">>self.fout, '[ ' for x in xList: self.fout.write('('+str(x)+') ') self.fout.write('", "< 10: print >>self.fout, 0, k*y k += 1 print", "else: v = 0; if axis == 1: self.y1LogScale =", "vMax *= 10 v0 = int(vMin) v1 = int(vMax+0.99) f", "{ ', self.x0 - self.xInc - self.xOffset,' sub ', self.xInc,", "and t <= tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime) time2List.append(t) oldTime =", "gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' else:", "' and indx == len(xList)-1: continue if len(yList) <= indx:", "xList, \\ ' yList: ', yList print >>self.fout, '%\\n% Plot", "-g1200x1100 ' cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100", "} def' elif plotsPerPage == 3: print >>self.fout, '/doGraph {", "cmdStr output = commands.getoutput(cmdStr) print >>flog, 'output from gs command:", ">>self.fout, self.yfix1 print >>self.fout, '[ ' for x in xList:", "print >>self.fout, '/showpage {\\n 40 742 moveto' print >>self.fout, '/Helvetica", "self.y1LogScale) self.y1Inc = yi self.y1Count = len(yList) self.yfix1 = '/yfix", "print >>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout, x print >>self.fout, endFun, type,", "zList, id, type) # def PlotData(self, axis, xList, yList, zList,", "' -g1200x550 ' size = ' -g%dx%d ' % (self.xSize,", "vi = 1 vList = [] v = v0 while", "[] indx = 0 for s in toStateList: if s", "GetInc(self,vMin, vMax): ff = 1.0 while vMax <= 1 and", "if self.xUniform == True: g_indx = self.xDict[x] print >>self.fout, g_indx,", "= vEnd logFlag = 1 v0Log = math.log10(v0) t =", "vInc != 0: if v1 % vInc != 0: v1", "axis, xList, yList, zList, id, type): flog = self.flog print", "return rv #--- SetColor(color) # def SetColor(self, color): rv =", "print >>self.fout, self.yfix1 # else: # print >>self.fout, '/yfix {", "100))): v0 = vBeg v1 = vEnd logFlag = 1", "= zi self.y2Count = len(zList) print >>self.fout, '/Flag2Yaxes 1 def'", "def' print >>self.fout, '/nextGraph { nextGraph3v } def' elif plotsPerPage", "' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' else: size =", "x in xList: self.fout.write('('+str(x)+') ') self.fout.write(' ]\\n[ ') for y", "for z in zList: self.fout.write('('+str(z)+') ') self.fout.write(' ]') if ztitle", "if self.xUniform == True: print >>self.fout, g_indx, y, z else:", "logFlag = 1 v0Log = math.log10(v0) t = math.ceil(v0Log) ff", "flog = self.flog print >>flog, 'graph xList: ', self.xList, '", "'' indx += 1 if self.xUniform == True: g_indx =", "if self.pageHeader != '': print >>self.fout, '(',self.pageHeader,') show' if self.pageSubHeader", "= 1 for x in xList: self.xDict[x] = k k=k+1", "print >>self.fout, '('+ztitle+') vaxis2' if logFlag == 1: print >>self.fout,", "= stateList[int(inputList[1])] t = int(inputList[2]) if indx != 0 and", "= vBeg vList.append(' ') self.xUniform = True v0 = 1", "v1 - v0 if w <= 10: vInc = 1", "if isinstance(zList,list): if len(zList) <= indx: continue z = zList[indx]", "class PsPlot(object): def __init__(self, fname, pageHeader, pageSubHeader, plotsPerPage): self.foutPath =", "x, 0.0 if (indx != 0) and (indx % 1000)", "[] v = v0 while v <= v1: vList.append(self.ValueConvert(v,0)) v", "math #gsPath = '/usr/local/bin/gs' gsPath = 'gs' logFile = '/dev/null'", "= 0 self.xInc = 0 self.xCount = 0 self.xList =", "'+str(vi)+' div }' print >>self.flog, 'v0:',v0,' vi:',vi,' v1:',v1,' (',vEnd,')' print", "self.colors[indx][1] = g self.colors[indx][2] = b return rv #--- outputPS(string)", "stateList[int(inputList[1])] t = int(inputList[2]) if indx != 0 and t", "(vMax/f)%vInc != 0 or v1 % vInc != 0: if", "self.colors[indx][0] = r self.colors[indx][1] = g self.colors[indx][2] = b return", "vInc = m else: vInc = m # if (vMax/f)%vInc", "'r') for inputLine in fin: inputLine = inputLine.replace(' ','') inputLine", "indx = 0 oldTime = 0 fin = open(fname, 'r')", "import random import os.path import shutil import commands import types", "1: s = int(v/(1000000000/d))/d if s*d == int(s)*d: s =", "#--- SetPlotBgLevel(level) # def SetPlotBgLevel(self,level): print >>self.fout, '/plotBgLevel ', level,", "t < 0: t += 1 logOffset = 0 while", "<= indx: continue y = yList[indx] if isinstance(zList,list): if len(zList)", "]\\n[ ') for y in yList: self.fout.write('('+str(y)+') ') print >>self.fout,", "!= 0 and t >= tMin and t <= tMax:", "p.SetPlot(tMin, tMax, 0, 0, 2, 0, 'Time', 'Socket/State', 'Chavey\\'s Plot')", "+ 1 w = 1 while w/f >= 100: f", "'': print >>self.fout, '('+ztitle+') vaxis2' if logFlag == 1: print", "1000000 and inc > 1: s = int(v/(1000000/d))/d if s*d", "(math.log10(v0) - 1) # substract 1 from above inside parent?", "-c quit' # cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE", "!= 0: v1 = int(v1 / m) * m +", "add } def\\n' print >>self.fout, 'beginFunction\\n' if isinstance(zList,list): endFun =", "' fix: ', fix return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def SetXLen(self,", "1 if self.xUniform == True: g_indx = self.xDict[x] print >>self.fout,", "== 1 and float(v)/inc > 1.0: d = 10.0 if", "indx += 1 print >>self.fout, x, 0.0 if (indx !=", "'G' elif v >= 1000000 and inc > 1: s", "d = 10.0 else: d = 10.0 if d ==", "elif axis == 1: print >>self.fout, self.yfix1 # else: #", "0 oldTime = 0 fin = open(fname, 'r') for inputLine", "k = 2 while k < 10: print >>self.fout, 0,", "= int(sys.argv[1]) tMax = int(sys.argv[2]) elif len(sys.argv) == 4: tMin", "return #--- SetPlotYLogScale(axis,value) # def SetPlotYLogScale(self,axis,value): if value == 'Off':", "False self.xLen = 6.5 #inches self.seriesTitle = ' ' self.x0", "-g1200x550 ' size = ' -g%dx%d ' % (self.xSize, self.ySize)", "gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' print", "self.yfix2 = '' self.xGrid = 1 self.yGrid = 1 self.xUniform", "v1 - v0 if w <= 5*m: vInc = m/2", "print >>self.fout, x print >>self.fout, endFun, type, '\\n' return #---", "-1 elif value == 'On': v = 1 else: v", "if (vMin % f) != 0 and vMax == v1:", "} def' print >>self.fout, '/showpage {\\n 40 742 moveto' print", "and inc > 1: s = int(v/(1000000000/d))/d if s*d ==", "r #--- GetAxis(vBeg, vEnd, vInc, logFlag) # def GetAxis(self, vBeg,", "{ } { log '+str(logOffset)+' add } ifelse }' else:", "> 100: m *= 10 if (v0 >= 0) and", "0 self.y2LogScale = 0 self.xOffset = 0 self.colors = [", "4: t1List = [] t2List = [] sList = []", "add aypos aylen' self.fout.write('[ ') for z in zList: self.fout.write('('+str(z)+')", "= 2 while k < 10: print >>self.fout, self.xCount, k*y", "0 setrgbcolor } plotSymbolsC\\n' return y1 #--- SetPlot2(xbeg,xend,xinc,ybeg,yend,yinc,zbeg,zend,zinc, # xtitle,ytitle,ztitle,title)", "v0 vList = [] n = 0 while True: vList.append(self.ValueConvert(v,vi))", "return #--- PlotData(axis, xList, yList, zList, id, type) # def", "(self.xSize, self.ySize) xres = int(100 * self.xSize * 6.5 /", "= inputLine.find('(') i2 = inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',') s1 =", "endFun = 'endFunction\\n' indx = 0 for x in xList:", "pageHeader, pageSubHeader, plotsPerPage): self.foutPath = os.path.dirname(fname)+'/' if self.foutPath == '/':", "= pageHeader self.pageSubHeader = pageSubHeader self.plotsPerPage = plotsPerPage self.yfix1 =", "len(sys.argv) == 2: fname = sys.argv[1] elif len(sys.argv) == 3:", "os.path.basename(fname) self.fname = fname+'.ps' self.pageHeader = pageHeader self.pageSubHeader = pageSubHeader", "else: vInc = m # if (vMax/f)%vInc != 0 or", "= self.flog print >>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout) if self.plotsPerPage ==", "substract 1 from above inside parent? fix = '{ dup", "zs in zList: factor = 1 if zs[-1:] == 'K':", "x, y, z print >>self.fout, endFun, type, '\\n' return #---", "*= 10 v0 = int(vMin) v1 = int(vMax+0.99) f =", "in 0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state += 1 image =", "rv #--- SetColorIndx(indx, r, g, b) # def SetColorIndx(self, indx,", "sys import random import os.path import shutil import commands import", "-r%dx%d ' % (xres, yres) cmdStr = gsPath + '", "print >>self.fout, '/xfix { ', self.x0 - self.xInc - self.xOffset,'", "len(yList) <= indx: continue y = yList[indx] if isinstance(zList,list): if", "' % (xres, yres) cmdStr = gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg", "550) res = ' -r%dx%d ' % (xres, yres) cmdStr", ">>flog, 'cmdStr: ', cmdStr output = commands.getoutput(cmdStr) print >>flog, 'output", "= v else: self.y2LogScale = v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) #", "= self.GetAxis(xbeg,xend,xinc,0) self.x0 = x0 self.xInc = xi self.xCount =", "print >>self.fout, '\\nshowpage\\nend' self.fout.close() #--- GetInc(vMin, vMax) def GetInc(self,vMin, vMax):", "print >>self.fout, '/nextGraph { nextGraph1v } def' print >>self.fout, '/showpage", "self.colorBlue = (0,0,0.8) self.colorAqua = (0,0.5,0.5) self.colorWhite = (1,1,1) self.ColorBlack", "' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'%d.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit' print >>flog, 'cmdStr:", "< 0: t += 1 logOffset = 0 while t", "'doGraph' return #--- SetXSize(xsize) def SetXSize(self, xsize): self.xSize = xsize", "'\\n' return #--- PlotData(axis, xList, yList, zList, id, type) #", "len(sys.argv) == 4: tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) fname", "= len(zList) print >>self.fout, '/Flag2Yaxes 1 def' self.yfix2 = '/yfix", "= yList[indx] if isinstance(zList,list): if len(zList) <= indx: continue z", "g, b): self.colors[indx][0] = r self.colors[indx][1] = g self.colors[indx][2] =", "{\\n 40 742 moveto' print >>self.fout, '/Helvetica findfont 12 scalefont", "def' print >>self.fout, '/nextGraph { nextGraph4v } def' elif plotsPerPage", "w = v1 - v0 if w <= 5*m: vInc", "SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0 =", "+= 1 p.PlotData(1,t1List, t2List, sList, 'Test', '0.1 in 0 '+p.SetColor(p.colors[state])+'", "xlen print >>self.fout, '/xAxisLen %.2f def' % self.xLen print >>self.fout,", "yList print >>self.fout, '%\\n% Plot '+id+'\\n%\\n' print >>self.fout, '/xfix {", "i2 = inputLine.find(')') inputList = inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])] s2", "'a') self.flog = open(logFile, 'a') # self.flog = open('./psPlot.out', 'a')", "if d == 1 and float(v)/inc > 1.0: d =", "= '/yfix '+fix+' def\\n/yinc yinc2 def' print >>self.fout, 'axpos axlen", "= self.GetInc(vBeg,vEnd) else: v0 = vBeg v1 = vEnd vi", "sList = [] indx = 0 for s in toStateList:", "= (0.8,0,0) self.colorGreen = (0,0.8,0) self.colorBlue = (0,0,0.8) self.colorAqua =", "10: print >>self.fout, 0, k*y k += 1 print >>self.fout,", "' ' and indx == len(xList)-1: continue if len(yList) <=", "__init__(self, fname, pageHeader, pageSubHeader, plotsPerPage): self.foutPath = os.path.dirname(fname)+'/' if self.foutPath", "d = 10.0 if d == 1 and float(v)/inc >", "== 3: print >>self.fout, '/doGraph { graph3v } def' print", "endFun+type+'\\nbeginFunction\\n' if self.xUniform == True: print >>self.fout, g_indx, y, z", "rv #--- outputPS(string) # def outputPS(self, s): print >>self.fout, s", "vInc if (v0 % vInc) != 0: v0 = int(v0/vInc)*vInc", "indx == 0: return print >>self.fout, '('+self.seriesTitle+')' while indx >=", "endFun = 'endFunctionW\\n' else: endFun = 'endFunction\\n' indx = 0", "10 vMax *= 10 v0 = int(vMin) v1 = int(vMax+0.99)", "print >>self.flog, ' '+t print >>self.fout, '('+t+')\\n' print >>self.fout, 'Mtitles\\n'", "def' % self.xLen print >>self.fout, 'doGraph' return #--- SetXSize(xsize) def", "' % (self.xSize, self.ySize) xres = int(100 * self.xSize *", "t in titleLines: if len(t) > 0: print >>self.flog, '", ">>self.fout, endFun, type, '\\n' return #--- PlotData(axis, xList, yList, zList,", "vi = 1 fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div", "!= 1: print 'USAGE: psPlot.py [tMin tMax] [fname]' sys.exit(1) print", "0: ff *= 0.10 vMin *= 10 vMax *= 10", "# def SetColor(self, color): rv = ' { '+str(color[0])+' '+str(color[1])+'", "t < 1: logOffset += 1 t += 1 v0", "self.xDict = {} self.y1Inc = 0 self.y1Count = 0 self.y1LogScale", "self.foutName = os.path.basename(fname) self.fname = fname+'.ps' self.pageHeader = pageHeader self.pageSubHeader", "# def SetPlotYLogScale(self,axis,value): if value == 'Off': v = -1", "self.y1Count = len(yList) self.yfix1 = '/yfix '+fix+' def\\n /yinc yinc1", "= 1000 elif zs[-1:] == 'M': zss = zs[:-1] factor", "self.y1Inc = yi self.y1Count = len(yList) self.yfix1 = '/yfix '+fix+'", "v = v0 + n*vi fix = '{ '+str(v0-vi)+' sub", "ff = 1.0 while vMax <= 1 and vMax >", "res +self.fname+' -c quit' # cmdStr = gsPath + '", "int(inputList[2]) if indx != 0 and t >= tMin and", "print >>self.fout, '/doGraph { graph4v } def' print >>self.fout, '/nextGraph", "value == 'On': v = 1 else: v = 0;", "!= 0: v1 = int(v1/vInc)*vInc + vInc if (v0 %", "zi self.y2Count = len(zList) print >>self.fout, '/Flag2Yaxes 1 def' self.yfix2", "{ 0 add } def\\n' print >>self.fout, 'beginFunction\\n' if isinstance(zList,list):", "self.ySize) xres = int(100 * self.xSize * 6.5 / (1200", "v0,v1,vi = self.GetInc(vBeg,vEnd) else: v0 = vBeg v1 = vEnd", "' div ', 0.0,' add } def\\n' if axis ==", "axis == 1: print >>self.fout, self.yfix1 # else: # print", "!= 0 or v1 % vInc != 0: if v1", "{ nextGraph4v } def' elif plotsPerPage == 3: print >>self.fout,", "[] indx = 0 oldTime = 0 fin = open(fname,", ">>self.flog, 'logFlag: ', logFlag, ' fix: ', fix return v0,v1,vi,vList,fix,logFlag", "len(names) - 1 if indx == 0: return print >>self.fout,", ">>self.fout, 'endFunction\\n' print >>self.fout, '19 { 0 0 0 setrgbcolor", "vEnd: break n += 1 v = v0 + n*vi", "= str(s) + 'M' elif v >= 1000 and inc", "!= 0: v0 = int(v0 / m) * m if", "'beginFunction\\n' endFun = 'endFunction\\n' indx = 0 for x in", "def SeriesNames(self, names): indx = len(names) - 1 if indx", "} def' print >>self.fout, '/nextGraph { nextGraph3v } def' elif", "def GetAxis(self, vBeg, vEnd, vInc, logFlag): fix = '{ 0", "r = str(s) else: r = str(int(v*100)/100.0) return r #---", "1000 elif zs[-1:] == 'M': zss = zs[:-1] factor =", "+= 1 image = p.GetImage(sys.stdout) print 'Image file: ', image", "1 fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div }' logFlag", "elif value == 'On': v = 1 else: v =", "== 1: self.y1LogScale = v else: self.y2LogScale = v return", "def SetXLen(self, xlen): self.xLen = xlen print >>self.fout, '/xAxisLen %.2f", "{ 0 0 0 setrgbcolor } plotSymbolsC\\n' return y1 #---", "elif plotsPerPage == 3: print >>self.fout, '/doGraph { graph3v }", "self.yfix1 # else: # print >>self.fout, '/yfix { 0 add", "+= 1 if self.xUniform == True: g_indx = self.xDict[x] print", "print >>self.fout, 'beginFunction\\n' for zs in zList: factor = 1", "self.xDict = {} k = 1 for x in xList:", "'/nextGraph { nextGraph3v } def' elif plotsPerPage == 2: print", "0 eq { } { log '+str(logOffset)+' add } ifelse", "for x in xList: self.xDict[x] = k k=k+1 print >>self.fout,", "'+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state += 1 image = p.GetImage(sys.stdout) print", "1 print >>self.fout, 'endFunction\\n' print >>self.fout, '18 { 0.72 0.52", "1 p.SetPlot(tMin, tMax, 0, 0, 2, 0, 'Time', 'Socket/State', 'Chavey\\'s", "0 v = v0 vList = [] n = 0", "print >>self.fout, self.SetColor(self.colors[indx % self.colorsN]) indx -= 1 print >>self.fout,", "' def\\n' (y0,y1,yi,yList,fix,logFlag) = self.GetAxis(ybeg,yend,yinc, self.y1LogScale) self.y1Inc = yi self.y1Count", "zs[:-1] factor = 1000000 else: zss = zs y =", "= int(s) r = str(s) + 'G' elif v >=", "'M' elif v >= 1000 and inc > 1: s", "'showpage\\n' self.fout.flush() os.fsync(self.fout) if self.plotsPerPage == 1: # size =", "} def' else: print >>self.fout, '/doGraph { graph1v } def'", "value == 'Off': v = -1 elif value == 'On':", "= vInc if vBeg > 0 and (logFlag==1 or (logFlag==0", "in fin: inputLine = inputLine.replace(' ','') inputLine = inputLine.replace(\"'\", '')", "0.52 0.5 setrgbcolor } plotSymbolsC\\n' return rv #--- SetColor(color) #", "'def\\n' return #--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if value == 'Vertical':", "t >= tMin and t <= tMax: fromStateList.append(s1) toStateList.append(s2) time1List.append(oldTime)", "def' else: print >>self.fout, '/doGraph { graph1v } def' print", "inputLine in fin: inputLine = inputLine.replace(' ','') inputLine = inputLine.replace(\"'\",", "' size = ' -g%dx%d ' % (self.xSize, self.ySize) xres", "= 1 fix = '{ '+str(v0-vi)+' sub '+str(vi)+' div }'", "return rv #--- outputPS(string) # def outputPS(self, s): print >>self.fout,", "zList[indx] else: z = '' indx += 1 if self.xUniform", "= v1 - v0 if w <= 10: vInc =", "', logFlag, ' fix: ', fix return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen)", ">>self.fout, '('+names[indx]+') ' print >>self.fout, self.SetColor(self.colors[indx % self.colorsN]) indx -=", "t = math.ceil(v0Log) ff = math.modf(v0Log) if math.fabs(ff[0]) < math.fabs(v0Log)/1000", "gs command: ', output return self.foutPath+self.foutName+'.jpg' #--- Main # def", "z print >>self.fout, endFun, type, '\\n' return #--- GetImage() #", "% self.xLen print >>self.fout, 'doGraph' return #--- SetXSize(xsize) def SetXSize(self,", "v1: v1 += 1 w = v1 - v0 if", "%.2f def' % self.xLen print >>self.fout, 'doGraph' return #--- SetXSize(xsize)", "= open('./psPlot.out', 'a') if plotsPerPage == 4: print >>self.fout, '/doGraph", ">= 1000 and inc > 1: s = int(v/(1000/d))/d if", "len(xList)-1: continue indx += 1 print >>self.fout, x, 0.0 if", "and float(v)/inc > 1.0: d = 10.0 if v >=", "> 100))): v0 = vBeg v1 = vEnd logFlag =", "else: if vInc == 0: v0,v1,vi = self.GetInc(vBeg,vEnd) else: v0", "' return rv #--- GetColorIndx(indx) # def GetColorIndx(self, indx): color", "= 0 self.y1LogScale = 0 self.y2Inc = 0 self.y2Count =", "os.fsync(self.fout) if self.plotsPerPage == 1: # size = ' -g1200x550", "m) != 0: v1 = int(v1 / m) * m", "print >>self.fout, '('+title+')\\nMtitles\\n' if logFlag == 1: print >>self.fout, 'beginFunction\\n'", "= open(self.fname, 'a') self.flog = open(logFile, 'a') # self.flog =", "add 10 add def\\n' # Multiple lines in title are", "sys.argv[3] elif len(sys.argv) != 1: print 'USAGE: psPlot.py [tMin tMax]", ">>self.fout, '/Flag2Yaxes 1 def' self.yfix2 = '/yfix '+fix+' def\\n/yinc yinc2", "# def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0)", "= int(math.log10(v/inc)) d = math.pow(10,logInc) if d == 0: d", "== 'Off': v = -1 elif value == 'On': v", "= 0 for s in toStateList: if s == state:", "#inches self.seriesTitle = ' ' self.x0 = 0 self.xInc =", "size = ' -g%dx%d ' % (self.xSize, self.ySize) xres =", "# def PlotVBars(self, xList, type): flog = self.flog print >>self.fout,", "GetInc(vMin, vMax) def GetInc(self,vMin, vMax): ff = 1.0 while vMax", "n += 1 v = v0 + n*vi fix =", "= 'plot.log' #--- class PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage) # class", "== 3: tMin = int(sys.argv[1]) tMax = int(sys.argv[2]) elif len(sys.argv)", "} def' print >>self.fout, '/nextGraph { nextGraph4v } def' elif", "isinstance(zList,list): endFun = 'endFunctionW\\n' else: endFun = 'endFunction\\n' indx =", "self.xUniform == True: g_indx = self.xDict[x] print >>self.fout, g_indx, y,", "factor = 1000 elif zs[-1:] == 'M': zss = zs[:-1]", "SetColor(self, color): rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\", "m + m w = v1 - v0 if w", "1000000 else: yss = ys y = float(yss)*factor/10.0 k =", "print >>self.fout, '/plotNumPercentDir 0 def\\n' return #--- SetPlotYLogScale(axis,value) # def", "inputLine[i1+1:i2-1].split(',') s1 = stateList[int(inputList[0])] s2 = stateList[int(inputList[1])] t = int(inputList[2])", "fix: ', fix return v0,v1,vi,vList,fix,logFlag #--- SetXLen(xlen) def SetXLen(self, xlen):", "def SetPlot(self,xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title): print >>self.fout, '\\n\\nnextGraph\\n1 setlinewidth\\n' (x0,x1,xi,xList,fix,logFlag) = self.GetAxis(xbeg,xend,xinc,0) self.x0", "0 self.xOffset = 0 self.colors = [ (0.7,0.7,0.7), (0,0,0.8), (0.8,0,0),", "= len(yList) self.yfix1 = '/yfix '+fix+' def\\n /yinc yinc1 def'", "def\\n' else: print >>self.fout, '/plotNumPercentDir 0 def\\n' return #--- SetPlotYLogScale(axis,value)", "' grid\\n' print >>self.fout, '/ymtitle ypos ylen add 10 add", "z = '' indx += 1 if self.xUniform == True:", "math.fabs(v0Log)/1000 and t < 0: t += 1 logOffset =", "} ' return rv #--- SetColorIndx(indx, r, g, b) #", "== len(xList)-1: continue indx += 1 print >>self.fout, x, 0.0", "== 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' if self.xUniform == True: print", "self.flog print >>self.fout, self.yfix1 print >>self.fout, 'beginFunction\\n' endFun = 'endFunction\\n'", "== 'Vertical': print >>self.fout, '/plotNumPercentDir 1 def\\n' else: print >>self.fout,", "print >>self.fout, x, y, z if (indx != 0) and", "def\\n /yinc yinc1 def' print >>self.fout, self.yfix1 print >>self.fout, '[", "fname = sys.argv[3] elif len(sys.argv) != 1: print 'USAGE: psPlot.py", "w == 0: v1 = v0 + 1 w =", "v0 = int(v0/vInc)*vInc v0 += vInc v0 *= (f*ff) v1", "900 shutil.copy('plot-header.ps', self.fname) self.fout = open(self.fname, 'a') self.flog = open(logFile,", "int(sys.argv[1]) tMax = int(sys.argv[2]) elif len(sys.argv) == 4: tMin =", "'0.1 in 0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state += 1 image", "<= 10: vInc = 1 elif w <= 20: vInc", "= inputLine.replace(\"'\", '') i1 = inputLine.find('(') i2 = inputLine.find(')') inputList", "graph1v } def' print >>self.fout, '/nextGraph { nextGraph1v } def'", "+= 1 w = v1 - v0 if w <=", "'19 { 0 0 0 setrgbcolor } plotSymbolsC\\n' return y1", "2: print >>self.fout, '/doGraph { graph2v } def' print >>self.fout,", "10 # w = int(w/f) v0 = int(v0/f) v1 =", "self.xGrid = 1 self.yGrid = 1 self.xUniform = False self.xLen", "' and indx == len(xList)-1: continue indx += 1 print", ">>self.fout, '/xfix { ', self.x0 - self.xInc - self.xOffset,' sub", "+= 1 p.SetPlot(tMin, tMax, 0, 0, 2, 0, 'Time', 'Socket/State',", "elif zs[-1:] == 'M': zss = zs[:-1] factor = 1000000", "str(int(v*100)/100.0) return r #--- GetAxis(vBeg, vEnd, vInc, logFlag) # def", "0, k*y k += 1 print >>self.fout, 'endFunction\\n' print >>self.fout,", "% self.colorsN] rv = ' { '+str(color[0])+' '+str(color[1])+' '+str(color[2])+ \\", "ff *= 0.10 vMin *= 10 vMax *= 10 v0", "== 'K': yss = ys[:-1] factor = 1000 elif ys[-1:]", "v1 = len(vList) vi = 1 fix = '{ '+str(v0-vi)+'", "vi = vInc if vBeg > 0 and (logFlag==1 or", "#--- GetImage() # def GetImage(self): flog = self.flog print >>self.fout,", ">>self.fout, '/ymtitle ypos ylen add 10 add def\\n' # Multiple", "yinc1 def' print >>self.fout, self.yfix1 print >>self.fout, '[ ' for", "PsPlot('./p', 'Header', 'SubHeader', 1) fromStateList = [] toStateList = []", "1000000000 and inc > 1: s = int(v/(1000000000/d))/d if s*d", "v else: self.y2LogScale = v return #--- SetPlot(xbeg,xend,xinc,ybeg,yend,yinc,xtitle,ytitle,title) # def", "= gsPath + ' -sDEVICE=jpeg'+size+'-sOutputFile='+self.foutPath+self.foutName+'.jpg -dNOPAUSE -r100x100 '+self.fname+' -c quit'", "state: t1List.append(time1List[indx]) t2List.append(time2List[indx]) sList.append(0.10 + s*0.20) indx += 1 p.PlotData(1,t1List,", "indx, r, g, b): self.colors[indx][0] = r self.colors[indx][1] = g", "'plot.log' #--- class PsPlot(fname, pageHeader, pageSubHeader, plotsPerPage) # class PsPlot(object):", "' -g%dx%d ' % (self.xSize, self.ySize) xres = int(100 *", "nextGraph1v } def' print >>self.fout, '/showpage {\\n 40 742 moveto'", "} def' print >>self.fout, '/nextGraph { nextGraph2v } def' else:", "'+fix+' def\\n /yinc yinc1 def' print >>self.fout, self.yfix1 print >>self.fout,", ">>self.fout, 'endFunction\\n' print >>self.fout, '18 { 0.72 0.52 0.5 setrgbcolor", "1: self.y1LogScale = v else: self.y2LogScale = v return #---", "== 4: print >>self.fout, '/doGraph { graph4v } def' print", "','') inputLine = inputLine.replace(\"'\", '') i1 = inputLine.find('(') i2 =", "<= 20: vInc = 2 else: m = 10 while", "x == ' ' and indx == len(xList)-1: continue indx", "10: print >>self.fout, self.xCount, k*y k += 1 print >>self.fout,", ">>self.fout, '('+t+')\\n' print >>self.fout, 'Mtitles\\n' # print >>self.fout, '('+title+')\\nMtitles\\n' if", "f *= 10 # w = int(w/f) v0 = int(v0/f)", "', level, 'def\\n' return #--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if value", "id, type): flog = self.flog print >>flog, 'graph xList: ',", "# Multiple lines in title are separated by '|' print", "fin: inputLine = inputLine.replace(' ','') inputLine = inputLine.replace(\"'\", '') i1", "self.fname) self.fout = open(self.fname, 'a') self.flog = open(logFile, 'a') #", "> 0 and (logFlag==1 or (logFlag==0 and (vEnd/vBeg > 100))):", "{} self.y1Inc = 0 self.y1Count = 0 self.y1LogScale = 0", "else: print >>self.fout, x, y, z print >>self.fout, endFun, type,", "% vInc != 0: if v1 % vInc != 0:", "-dNOPAUSE '+ res +self.fname+' -c quit' # cmdStr = gsPath", "self.xLen = 6.5 #inches self.seriesTitle = ' ' self.x0 =", "vMax > 0: ff *= 0.10 vMin *= 10 vMax", "= ys[:-1] factor = 1000 elif ys[-1:] == 'M': yss", "if plotsPerPage == 4: print >>self.fout, '/doGraph { graph4v }", "0: d = 10.0 else: d = 10.0 if d", "and t < 0: t += 1 logOffset = 0", "'endFunction\\n' print >>self.fout, '19 { 0 0 0 setrgbcolor }", "= int(v/(1000000/d))/d if s*d == int(s)*d: s = int(s) r", "if isinstance(vBeg,list): vList = vBeg vList.append(' ') self.xUniform = True", "yinc2 def' print >>self.fout, 'axpos axlen add aypos aylen' self.fout.write('[", "0 for x in xList: if x == ' '", "sList, 'Test', '0.1 in 0 '+p.SetColor(p.colors[state])+' plotWbarsC', sys.stdout) state +=", "print >>self.fout, '%\\n% Plot '+id+'\\n%\\n' print >>self.fout, '/xfix { ',", "int(s)*d: s = int(s) r = str(s) + 'G' elif", "m w = v1 - v0 if w <= 5*m:", "import os.path import shutil import commands import types import math", "math.ceil(v0Log) ff = math.modf(v0Log) if math.fabs(ff[0]) < math.fabs(v0Log)/1000 and t", "1.0: d = 10.0 if v >= 1000000000 and inc", "float(yss)*factor/10.0 k = 2 while k < 10: print >>self.fout,", "SeriesNames(self, names): indx = len(names) - 1 if indx ==", "1: print >>self.fout, 'beginFunction\\n' for ys in yList: factor =", "vEnd, vInc, logFlag) # def GetAxis(self, vBeg, vEnd, vInc, logFlag):", "types import math #gsPath = '/usr/local/bin/gs' gsPath = 'gs' logFile", "print >>self.fout, 'axpos axlen add aypos aylen' self.fout.write('[ ') for", "= 'endFunction\\n' indx = 0 for x in xList: if", "sList.append(0.10 + s*0.20) indx += 1 p.PlotData(1,t1List, t2List, sList, 'Test',", "% self.colorsN]) indx -= 1 print >>self.fout, 'fdescriptionsC' #--- PlotVBars(xList,", "def' elif plotsPerPage == 2: print >>self.fout, '/doGraph { graph2v", "= [] indx = 0 for s in toStateList: if", "'vList: ', vList print >>self.flog, 'logFlag: ', logFlag, ' fix:", "'SubHeader', 1) fromStateList = [] toStateList = [] time1List =", "return #--- SetPlotPercentDir(value) def SetPlotPercentDir(self,value): if value == 'Vertical': print", "#--- ValueConvert(v) # def ValueConvert(self, v, inc): if inc >", "self.y2Inc = zi self.y2Count = len(zList) print >>self.fout, '/Flag2Yaxes 1", "s*d == int(s)*d: s = int(s) r = str(s) else:", "def' print >>self.fout, '/showpage {\\n 40 742 moveto' print >>self.fout,", "1000) == 0: print >>self.fout, endFun+type+'\\nbeginFunction\\n' print >>self.fout, x print", "= 2 while k < 10: print >>self.fout, 0, k*y", "} def\\n' if axis == 2: print >>self.fout, self.yfix2 elif", "0: v0 = int(v0 / m) * m if (v1", "g_indx, y, z else: print >>self.fout, x, y, z print", "self.fout.flush() os.fsync(self.fout) if self.plotsPerPage == 1: # size = '", "4: print >>self.fout, '/doGraph { graph4v } def' print >>self.fout,", "= 0 self.y2LogScale = 0 self.xOffset = 0 self.colors =", "int(s) r = str(s) + 'G' elif v >= 1000000", ">>self.fout, '('+xtitle+')\\n('+ytitle+')\\naxes\\n' print >>self.fout, self.xGrid, self.yGrid, ' grid\\n' print >>self.fout,", "'/nextGraph { nextGraph1v } def' print >>self.fout, '/showpage {\\n 40", "in yList: factor = 1 if ys[-1:] == 'K': yss", "and inc > 1: s = int(v/(1000000/d))/d if s*d ==", "# w = int(w/f) v0 = int(v0/f) v1 = int(v1/f)", "= '{ 0 add }' if isinstance(vBeg,list): vList = vBeg", "fix = '{ 0 add }' if isinstance(vBeg,list): vList =", "# def main(): tMin = 0 tMax = 100000 stateList", "if axis == 2: print >>self.fout, self.yfix2 elif axis ==", "ysize): self.ySize = ysize return #--- SetPlotBgLevel(level) # def SetPlotBgLevel(self,level):", "= fname+'.ps' self.pageHeader = pageHeader self.pageSubHeader = pageSubHeader self.plotsPerPage =", "while v <= v1: vList.append(self.ValueConvert(v,0)) v *= 10 if v0", "= 1 vList = [] v = v0 while v", "print >>self.fout, 'showpage\\n' self.fout.flush() os.fsync(self.fout) if self.plotsPerPage == 1: #", "endFun, type, '\\n' return #--- PlotData(axis, xList, yList, zList, id," ]
[ "dependencies = [ ('exercises', '0002_auto_20161128_1718'), ] operations = [ migrations.RenameModel(", "from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):", "= [ ('exercises', '0002_auto_20161128_1718'), ] operations = [ migrations.RenameModel( old_name='Exercises',", "on 2016-11-28 06:53 from __future__ import unicode_literals from django.db import", "[ ('exercises', '0002_auto_20161128_1718'), ] operations = [ migrations.RenameModel( old_name='Exercises', new_name='Exercise',", "-*- coding: utf-8 -*- # Generated by Django 1.10.3 on", "Django 1.10.3 on 2016-11-28 06:53 from __future__ import unicode_literals from", "2016-11-28 06:53 from __future__ import unicode_literals from django.db import migrations", "coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-28", "utf-8 -*- # Generated by Django 1.10.3 on 2016-11-28 06:53", "# -*- coding: utf-8 -*- # Generated by Django 1.10.3", "<filename>physio2go/exercises/migrations/0003_auto_20161128_1753.py # -*- coding: utf-8 -*- # Generated by Django", "unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('exercises',", "by Django 1.10.3 on 2016-11-28 06:53 from __future__ import unicode_literals", "1.10.3 on 2016-11-28 06:53 from __future__ import unicode_literals from django.db", "'0002_auto_20161128_1718'), ] operations = [ migrations.RenameModel( old_name='Exercises', new_name='Exercise', ), ]", "('exercises', '0002_auto_20161128_1718'), ] operations = [ migrations.RenameModel( old_name='Exercises', new_name='Exercise', ),", "Generated by Django 1.10.3 on 2016-11-28 06:53 from __future__ import", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('exercises', '0002_auto_20161128_1718'),", "import migrations class Migration(migrations.Migration): dependencies = [ ('exercises', '0002_auto_20161128_1718'), ]", "import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies =", "__future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies", "class Migration(migrations.Migration): dependencies = [ ('exercises', '0002_auto_20161128_1718'), ] operations =", "# Generated by Django 1.10.3 on 2016-11-28 06:53 from __future__", "migrations class Migration(migrations.Migration): dependencies = [ ('exercises', '0002_auto_20161128_1718'), ] operations", "-*- # Generated by Django 1.10.3 on 2016-11-28 06:53 from", "Migration(migrations.Migration): dependencies = [ ('exercises', '0002_auto_20161128_1718'), ] operations = [", "06:53 from __future__ import unicode_literals from django.db import migrations class" ]
[ "Copyright 2021 Northern.tech AS # # Licensed under the Apache", "version_string_line = open(VERSIONFILE, \"rt\").read() VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match", "re.M) if match: version_string = match.group(1) else: raise RuntimeError(\"Unable to", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]}, package_dir={\"\":", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Northern.tech AS # # Licensed under the Apache License, Version", "2.0 (the \"License\"); # you may not use this file", "file except in compliance with the License. # You may", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language :: Python :: 3\", \"License ::", "% (VERSIONFILE,)) with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description =", "distributed under the License is distributed on an \"AS IS\"", "to find version string in %s.\" % (VERSIONFILE,)) with open(\"README.md\",", "= \"src/mender/_version.py\" version_string_line = open(VERSIONFILE, \"rt\").read() VSRE = r\"^__version__ =", "%s.\" % (VERSIONFILE,)) with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description", "version string in %s.\" % (VERSIONFILE,)) with open(\"README.md\", \"r\", encoding=\"utf-8\")", "re.search(VSRE, version_string_line, re.M) if match: version_string = match.group(1) else: raise", "], keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\":", "\"rt\").read() VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE, version_string_line,", "the specific language governing permissions and # limitations under the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "implementation of the Mender client interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", ":: 3\", \"License :: OSI Approved :: Apache Software License\",", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "setuptools import re VERSIONFILE = \"src/mender/_version.py\" version_string_line = open(VERSIONFILE, \"rt\").read()", "the License. import setuptools import re VERSIONFILE = \"src/mender/_version.py\" version_string_line", "description=\"A Python implementation of the Mender client interface\", long_description=long_description, long_description_content_type=\"text/markdown\",", "long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language :: Python :: 3\", \"License", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "Software License\", \"Operating System :: OS Independent\", ], keywords=[\"mender\", \"OTA\",", "keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]},", "writing, software # distributed under the License is distributed on", "name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python implementation of", "in writing, software # distributed under the License is distributed", "OSI Approved :: Apache Software License\", \"Operating System :: OS", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "language governing permissions and # limitations under the License. import", ":: OS Independent\", ], keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\",", "author_email=\"<EMAIL>\", description=\"A Python implementation of the Mender client interface\", long_description=long_description,", "of the Mender client interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming", "\"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]}, package_dir={\"\": \"src\"},", "# limitations under the License. import setuptools import re VERSIONFILE", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "governing permissions and # limitations under the License. import setuptools", "the Mender client interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language", "long_description = fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\",", "CONDITIONS OF ANY KIND, either express or implied. # See", "= match.group(1) else: raise RuntimeError(\"Unable to find version string in", "permissions and # limitations under the License. import setuptools import", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"src/mender/_version.py\" version_string_line = open(VERSIONFILE, \"rt\").read() VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "fh: long_description = fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\",", "version_string = match.group(1) else: raise RuntimeError(\"Unable to find version string", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python implementation of the Mender client interface\",", "\"License :: OSI Approved :: Apache Software License\", \"Operating System", "OS Independent\", ], keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\",", ":: Python :: 3\", \"License :: OSI Approved :: Apache", "under the License is distributed on an \"AS IS\" BASIS,", "License. import setuptools import re VERSIONFILE = \"src/mender/_version.py\" version_string_line =", ":: OSI Approved :: Apache Software License\", \"Operating System ::", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "3\", \"License :: OSI Approved :: Apache Software License\", \"Operating", "AS # # Licensed under the Apache License, Version 2.0", "\"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string,", "= r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE, version_string_line, re.M) if", "with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup(", "Mender client interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language ::", "limitations under the License. import setuptools import re VERSIONFILE =", "\"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]}, package_dir={\"\": \"src\"}, python_requires=\">=3.6\", zip_safe=False, include_package_data=True,", "# Copyright 2021 Northern.tech AS # # Licensed under the", "encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache", "the License for the specific language governing permissions and #", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "(VERSIONFILE,)) with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read()", "# you may not use this file except in compliance", "open(\"README.md\", \"r\", encoding=\"utf-8\") as fh: long_description = fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\",", "client interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language :: Python", "either express or implied. # See the License for the", "long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language :: Python :: 3\",", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "VERSIONFILE = \"src/mender/_version.py\" version_string_line = open(VERSIONFILE, \"rt\").read() VSRE = r\"^__version__", "under the License. import setuptools import re VERSIONFILE = \"src/mender/_version.py\"", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE, version_string_line, re.M) if match:", "2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python implementation of the Mender client", "\"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]}, package_dir={\"\": \"src\"}, python_requires=\">=3.6\", zip_safe=False, include_package_data=True, )", "software # distributed under the License is distributed on an", "string in %s.\" % (VERSIONFILE,)) with open(\"README.md\", \"r\", encoding=\"utf-8\") as", "install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]}, package_dir={\"\": \"src\"}, python_requires=\">=3.6\", zip_safe=False,", "# # Unless required by applicable law or agreed to", "match.group(1) else: raise RuntimeError(\"Unable to find version string in %s.\"", "import re VERSIONFILE = \"src/mender/_version.py\" version_string_line = open(VERSIONFILE, \"rt\").read() VSRE", "fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python", "= ['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE, version_string_line, re.M) if match: version_string", "Independent\", ], keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"],", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI", "System :: OS Independent\", ], keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\",", "Version 2.0 (the \"License\"); # you may not use this", "packages=setuptools.find_packages(where=\"src\"), install_requires=[\"cryptography\", \"requests\", \"msgpack\", \"websockets\"], entry_points={\"console_scripts\": [\"mender-python-client=mender.mender:main\"]}, package_dir={\"\": \"src\"}, python_requires=\">=3.6\",", "law or agreed to in writing, software # distributed under", "['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE, version_string_line, re.M) if match: version_string =", "else: raise RuntimeError(\"Unable to find version string in %s.\" %", "\"Operating System :: OS Independent\", ], keywords=[\"mender\", \"OTA\", \"updater\"], packages=setuptools.find_packages(where=\"src\"),", "find version string in %s.\" % (VERSIONFILE,)) with open(\"README.md\", \"r\",", "version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python implementation of the", ":: Apache Software License\", \"Operating System :: OS Independent\", ],", "= open(VERSIONFILE, \"rt\").read() VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match =", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "= re.search(VSRE, version_string_line, re.M) if match: version_string = match.group(1) else:", "\"License\"); # you may not use this file except in", "Approved :: Apache Software License\", \"Operating System :: OS Independent\",", "Apache Software License\", \"Operating System :: OS Independent\", ], keywords=[\"mender\",", "VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE, version_string_line, re.M)", "License\", \"Operating System :: OS Independent\", ], keywords=[\"mender\", \"OTA\", \"updater\"],", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python implementation", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "RuntimeError(\"Unable to find version string in %s.\" % (VERSIONFILE,)) with", "match = re.search(VSRE, version_string_line, re.M) if match: version_string = match.group(1)", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "match: version_string = match.group(1) else: raise RuntimeError(\"Unable to find version", "interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\", classifiers=[ \"Programming Language :: Python ::", "open(VERSIONFILE, \"rt\").read() VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\" match = re.search(VSRE,", "Python :: 3\", \"License :: OSI Approved :: Apache Software", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "and # limitations under the License. import setuptools import re", "\"Programming Language :: Python :: 3\", \"License :: OSI Approved", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "import setuptools import re VERSIONFILE = \"src/mender/_version.py\" version_string_line = open(VERSIONFILE,", "in %s.\" % (VERSIONFILE,)) with open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:", "Python implementation of the Mender client interface\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/mendersoftware/mender-python-client\",", "Language :: Python :: 3\", \"License :: OSI Approved ::", "version_string_line, re.M) if match: version_string = match.group(1) else: raise RuntimeError(\"Unable", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "as fh: long_description = fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\",", "You may obtain a copy of the License at #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "= fh.read() setuptools.setup( name=\"mender-python-client-mendersoftware\", version=version_string, license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "if match: version_string = match.group(1) else: raise RuntimeError(\"Unable to find", "license=\"Apache 2.0\", author=\"Mendersoftware\", author_email=\"<EMAIL>\", description=\"A Python implementation of the Mender", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "re VERSIONFILE = \"src/mender/_version.py\" version_string_line = open(VERSIONFILE, \"rt\").read() VSRE =", "the Apache License, Version 2.0 (the \"License\"); # you may", "raise RuntimeError(\"Unable to find version string in %s.\" % (VERSIONFILE,))", "2021 Northern.tech AS # # Licensed under the Apache License," ]
[ "> len(self.hi): heappush(self.hi, -heappop(self.lo)) def findMedian(self) -> float: if len(self.hi)", "len(self.hi) > len(self.lo): return self.hi[0] if len(self.hi) == len(self.lo): return", "heappush(self.lo, -heappushpop(self.hi, num)) while len(self.lo) > len(self.hi): heappush(self.hi, -heappop(self.lo)) def", "\"\"\" initialize your data structure here. \"\"\" self.hi = []", "-> float: if len(self.hi) > len(self.lo): return self.hi[0] if len(self.hi)", "[] def addNum(self, num: int) -> None: heappush(self.lo, -heappushpop(self.hi, num))", "find median from data stream hard \"\"\" from heapq import", "None: heappush(self.lo, -heappushpop(self.hi, num)) while len(self.lo) > len(self.hi): heappush(self.hi, -heappop(self.lo))", "len(self.lo) > len(self.hi): heappush(self.hi, -heappop(self.lo)) def findMedian(self) -> float: if", "MedianFinder: # max heap and min heap def __init__(self): \"\"\"", "findMedian(self) -> float: if len(self.hi) > len(self.lo): return self.hi[0] if", "len(self.hi) == len(self.lo): return (self.hi[0] - self.lo[0]) / 2.0 sol", "\"\"\" from heapq import * class MedianFinder: # max heap", "heappush(self.hi, -heappop(self.lo)) def findMedian(self) -> float: if len(self.hi) > len(self.lo):", "- self.lo[0]) / 2.0 sol = MedianFinder() sol.addNum(1) print(sol.findMedian()) sol.addNum(2)", "heap def __init__(self): \"\"\" initialize your data structure here. \"\"\"", "-heappop(self.lo)) def findMedian(self) -> float: if len(self.hi) > len(self.lo): return", "[] self.lo = [] def addNum(self, num: int) -> None:", "from heapq import * class MedianFinder: # max heap and", "while len(self.lo) > len(self.hi): heappush(self.hi, -heappop(self.lo)) def findMedian(self) -> float:", "__init__(self): \"\"\" initialize your data structure here. \"\"\" self.hi =", "self.hi[0] if len(self.hi) == len(self.lo): return (self.hi[0] - self.lo[0]) /", "-heappushpop(self.hi, num)) while len(self.lo) > len(self.hi): heappush(self.hi, -heappop(self.lo)) def findMedian(self)", "if len(self.hi) == len(self.lo): return (self.hi[0] - self.lo[0]) / 2.0", "\"\"\" 295 find median from data stream hard \"\"\" from", "heapq import * class MedianFinder: # max heap and min", "initialize your data structure here. \"\"\" self.hi = [] self.lo", "num)) while len(self.lo) > len(self.hi): heappush(self.hi, -heappop(self.lo)) def findMedian(self) ->", "int) -> None: heappush(self.lo, -heappushpop(self.hi, num)) while len(self.lo) > len(self.hi):", "# max heap and min heap def __init__(self): \"\"\" initialize", "\"\"\" self.hi = [] self.lo = [] def addNum(self, num:", "hard \"\"\" from heapq import * class MedianFinder: # max", "self.lo = [] def addNum(self, num: int) -> None: heappush(self.lo,", "import * class MedianFinder: # max heap and min heap", "def addNum(self, num: int) -> None: heappush(self.lo, -heappushpop(self.hi, num)) while", "-> None: heappush(self.lo, -heappushpop(self.hi, num)) while len(self.lo) > len(self.hi): heappush(self.hi,", "len(self.lo): return (self.hi[0] - self.lo[0]) / 2.0 sol = MedianFinder()", "return (self.hi[0] - self.lo[0]) / 2.0 sol = MedianFinder() sol.addNum(1)", "return self.hi[0] if len(self.hi) == len(self.lo): return (self.hi[0] - self.lo[0])", "if len(self.hi) > len(self.lo): return self.hi[0] if len(self.hi) == len(self.lo):", "class MedianFinder: # max heap and min heap def __init__(self):", "min heap def __init__(self): \"\"\" initialize your data structure here.", "self.hi = [] self.lo = [] def addNum(self, num: int)", "= [] self.lo = [] def addNum(self, num: int) ->", "(self.hi[0] - self.lo[0]) / 2.0 sol = MedianFinder() sol.addNum(1) print(sol.findMedian())", "self.lo[0]) / 2.0 sol = MedianFinder() sol.addNum(1) print(sol.findMedian()) sol.addNum(2) print(sol.findMedian())", "= [] def addNum(self, num: int) -> None: heappush(self.lo, -heappushpop(self.hi,", "heap and min heap def __init__(self): \"\"\" initialize your data", "295 find median from data stream hard \"\"\" from heapq", "len(self.hi): heappush(self.hi, -heappop(self.lo)) def findMedian(self) -> float: if len(self.hi) >", "== len(self.lo): return (self.hi[0] - self.lo[0]) / 2.0 sol =", "stream hard \"\"\" from heapq import * class MedianFinder: #", "median from data stream hard \"\"\" from heapq import *", "structure here. \"\"\" self.hi = [] self.lo = [] def", "num: int) -> None: heappush(self.lo, -heappushpop(self.hi, num)) while len(self.lo) >", "> len(self.lo): return self.hi[0] if len(self.hi) == len(self.lo): return (self.hi[0]", "from data stream hard \"\"\" from heapq import * class", "def findMedian(self) -> float: if len(self.hi) > len(self.lo): return self.hi[0]", "data stream hard \"\"\" from heapq import * class MedianFinder:", "* class MedianFinder: # max heap and min heap def", "len(self.lo): return self.hi[0] if len(self.hi) == len(self.lo): return (self.hi[0] -", "addNum(self, num: int) -> None: heappush(self.lo, -heappushpop(self.hi, num)) while len(self.lo)", "your data structure here. \"\"\" self.hi = [] self.lo =", "here. \"\"\" self.hi = [] self.lo = [] def addNum(self,", "float: if len(self.hi) > len(self.lo): return self.hi[0] if len(self.hi) ==", "and min heap def __init__(self): \"\"\" initialize your data structure", "max heap and min heap def __init__(self): \"\"\" initialize your", "data structure here. \"\"\" self.hi = [] self.lo = []", "def __init__(self): \"\"\" initialize your data structure here. \"\"\" self.hi" ]
[ "ground = world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0, 0.0) pin1", "0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0,", "ball2, 0, np.zeros(3), 2.0) world.addStiffWire(pin3, 0, np.zeros(3), ball3, 0, np.zeros(3),", "pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0,", "np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0]", "0, np.zeros(3), 2.0) world.addStiffWire(pin4, 0, np.zeros(3), ball4, 0, np.zeros(3), 2.0)", "0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1, 0.8)", "0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0, 6.0)", "anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3, 0,", "math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world = raisim.World() ground", "= np.ones(anymalC.getDOF()) * 100.0 jointDgain = np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig)", "= world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 =", "1.0) ball2 = world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3, 0.0, 1.0) ball3", "0.8, \"steel\") ball1.setPosition(0, 0.0, 1.0) ball2 = world.addSphere(0.1499, 0.8, \"steel\")", "-0.03, -0.4, 0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF()) *", "0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0,", "3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0)", "0.8, \"steel\") ball2.setPosition(0.3, 0.0, 1.0) ball3 = world.addSphere(0.1499, 0.8, \"steel\")", "box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1, 0, np.zeros(3), ball1, 0, np.zeros(3), 2.0)", "np.zeros(3), ball3, 0, np.zeros(3), 2.0) world.addStiffWire(pin4, 0, np.zeros(3), ball4, 0,", "2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7, 0, np.zeros(3), anymalB, 0,", "\"steel\") ball1.setPosition(0, 0.0, 1.0) ball2 = world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3,", "0, np.zeros(3), ball1, 0, np.zeros(3), 2.0) world.addStiffWire(pin2, 0, np.zeros(3), ball2,", "pin1 = world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2", "raisim.World() ground = world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0, 0.0)", "ball4.setPosition(2.9, 0.0, 3.0) box = world.addBox(.1, .1, .1, 1) box.setPosition(0.9,", "0.03, 0.4, -0.8, -0.03, 0.4, -0.8, 0.03, -0.4, 0.8, -0.03,", "world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1, 0.8)", "ball2.setPosition(0.3, 0.0, 1.0) ball3 = world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6, 0.0,", "np.zeros(3), ball2, 0, np.zeros(3), 2.0) world.addStiffWire(pin3, 0, np.zeros(3), ball3, 0,", "world.addCustomWire(pin7, 0, np.zeros(3), anymalB, 0, np.zeros(3), 2.0) wire7.setTension(310) server =", "= world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 =", "0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1, 0.8)", "world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9, 0.0, 3.0) box = world.addBox(.1, .1,", "ball4 = world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9, 0.0, 3.0) box =", "pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6", "world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3, 0.0, 1.0) ball3 = world.addSphere(0.1499, 0.8,", "jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain)", "3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0)", "0.0, 4.2) world.addStiffWire(pin1, 0, np.zeros(3), ball1, 0, np.zeros(3), 2.0) world.addStiffWire(pin2,", "os import numpy as np import raisimpy as raisim import", "0, np.zeros(3), 2.0) wire7.setTension(310) server = raisim.RaisimServer(world) server.launchServer(8080) for i", "0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1, 0.8)", "ball1.setPosition(0, 0.0, 1.0) ball2 = world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3, 0.0,", "0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0, 7.0)", "ball2 = world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3, 0.0, 1.0) ball3 =", "world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0, 0.0) pin1 = world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\")", "= np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\")", "anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain,", "2.0) wire7.setTension(310) server = raisim.RaisimServer(world) server.launchServer(8080) for i in range(500000):", "0.0, 0.0, 0.03, 0.4, -0.8, -0.03, 0.4, -0.8, 0.03, -0.4,", "2.0) world.addStiffWire(pin2, 0, np.zeros(3), ball2, 0, np.zeros(3), 2.0) world.addStiffWire(pin3, 0,", "\"steel\") ball4.setPosition(2.9, 0.0, 3.0) box = world.addBox(.1, .1, .1, 1)", "3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0)", "= os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC", "np.array([-3, 0, 4.54, 1.0, 0.0, 0.0, 0.0, 0.03, 0.4, -0.8,", "anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498, 0.8,", "0.0) pin1 = world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC)", "-0.4, 0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF()) * 100.0", "anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig,", "0.8) pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1, 0.8) pin7.setPosition(-4.,", "pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC)", "0, np.zeros(3), anymalB, 0, np.zeros(3), 2.0) wire7.setTension(310) server = raisim.RaisimServer(world)", "world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1,", "-0.8, -0.03, 0.4, -0.8, 0.03, -0.4, 0.8, -0.03, -0.4, 0.8])", "0, np.zeros(3), ball2, 0, np.zeros(3), 2.0) world.addStiffWire(pin3, 0, np.zeros(3), ball3,", "pin2 = world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3", "-4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498,", "3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC)", "world.addStiffWire(pin1, 0, np.zeros(3), ball1, 0, np.zeros(3), 2.0) world.addStiffWire(pin2, 0, np.zeros(3),", "= world.addCompliantWire(pin5, 0, np.zeros(3), box, 0, np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH)", "time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world = raisim.World() ground = world.addGround()", "i in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe() if i == 5000: world.removeObject(wire7)", "import numpy as np import raisimpy as raisim import math", "ball1, 0, np.zeros(3), 2.0) world.addStiffWire(pin2, 0, np.zeros(3), ball2, 0, np.zeros(3),", "0.0, 1.0) ball2 = world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3, 0.0, 1.0)", "pin7 = world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file =", "1.0, 0.0) pin1 = world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0)", "0, np.zeros(3), anymalC, 0, np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 =", "ball1 = world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0, 0.0, 1.0) ball2 =", "= world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6, 0.0, 1.0) ball4 = world.addSphere(0.1499,", "= world.addCustomWire(pin7, 0, np.zeros(3), anymalB, 0, np.zeros(3), 2.0) wire7.setTension(310) server", "world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) +", "as np import raisimpy as raisim import math import time", "jointDgain = np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget)", "6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC)", "numpy as np import raisimpy as raisim import math import", "-0.8, 0.03, -0.4, 0.8, -0.03, -0.4, 0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()])", "pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\")", "pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) +", "100.0 jointDgain = np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig,", "0.0, 0.0, 0.0, 0.03, 0.4, -0.8, -0.03, 0.4, -0.8, 0.03,", "0.0, 3.0) box = world.addBox(.1, .1, .1, 1) box.setPosition(0.9, 0.0,", "anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498, 0.8, \"steel\")", "anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB =", "0, np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6, 0, np.zeros(3),", "world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1,", "+ \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig =", "pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1, 0.8) pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3,", "raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world = raisim.World() ground = world.addGround() world.setTimeStep(0.001)", "anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3, 0, 4.54, 1.0, 0.0,", "200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6, 0, np.zeros(3), anymalC, 0, np.zeros(3),", "pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC)", "2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6, 0, np.zeros(3), anymalC, 0,", "= world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0, 0.0, 1.0) ball2 = world.addSphere(0.1499,", "np.zeros(3), anymalB, 0, np.zeros(3), 2.0) wire7.setTension(310) server = raisim.RaisimServer(world) server.launchServer(8080)", "import math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world = raisim.World()", "anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0, 0.0,", "ball3.setPosition(0.6, 0.0, 1.0) ball4 = world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9, 0.0,", "np.ones(anymalC.getDOF()) * 100.0 jointDgain = np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain,", "= world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 =", "0.4, -0.8, 0.03, -0.4, 0.8, -0.03, -0.4, 0.8]) jointVelocityTarget =", "raisim import math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world =", "1.0) ball3 = world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6, 0.0, 1.0) ball4", "wire7 = world.addCustomWire(pin7, 0, np.zeros(3), anymalB, 0, np.zeros(3), 2.0) wire7.setTension(310)", "= world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3, 0, 4.54, 1.0, 0.0, 0.0,", "jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF()) * 100.0 jointDgain =", "world.addStiffWire(pin4, 0, np.zeros(3), ball4, 0, np.zeros(3), 2.0) wire5 = world.addCompliantWire(pin5,", "pin4 = world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5", "= world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__))", "= world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1,", "world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0, 0.0) pin1 = world.addSphere(0.1,", "7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC)", "np.zeros(3), box, 0, np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6,", "0.0, 1.0) ball3 = world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6, 0.0, 1.0)", "world = raisim.World() ground = world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1,", "\"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB", "wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7, 0, np.zeros(3), anymalB, 0, np.zeros(3), 2.0)", "server.launchServer(8080) for i in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe() if i ==", "pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6,", "pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC)", "pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1, 0.8) pin5.setPosition(0.9,", "anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\")", "os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig", "2.0) world.addStiffWire(pin3, 0, np.zeros(3), ball3, 0, np.zeros(3), 2.0) world.addStiffWire(pin4, 0,", "world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3, 0, 4.54, 1.0,", "-0.03, 0.4, -0.8, 0.03, -0.4, 0.8, -0.03, -0.4, 0.8]) jointVelocityTarget", "= world.addCompliantWire(pin6, 0, np.zeros(3), anymalC, 0, np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH)", "pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file", "\"steel\", 0.1, 1.0, 0.0) pin1 = world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0,", "0.8, \"steel\") ball4.setPosition(2.9, 0.0, 3.0) box = world.addBox(.1, .1, .1,", "pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9,", "0, np.zeros(3), ball4, 0, np.zeros(3), 2.0) wire5 = world.addCompliantWire(pin5, 0,", "world.addBox(.1, .1, .1, 1) box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1, 0, np.zeros(3),", "world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6, 0.0, 1.0) ball4 = world.addSphere(0.1499, 0.8,", "np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6, 0, np.zeros(3), anymalC,", "= world.addSphere(0.1499, 0.8, \"steel\") ball2.setPosition(0.3, 0.0, 1.0) ball3 = world.addSphere(0.1499,", "world.addStiffWire(pin2, 0, np.zeros(3), ball2, 0, np.zeros(3), 2.0) world.addStiffWire(pin3, 0, np.zeros(3),", "world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0, 0.0, 1.0) ball2 = world.addSphere(0.1499, 0.8,", "0, 4.54, 1.0, 0.0, 0.0, 0.0, 0.03, 0.4, -0.8, -0.03,", "np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF()) * 100.0 jointDgain = np.ones(anymalC.getDOF()) *", "0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF()) * 100.0 jointDgain", "world.addCompliantWire(pin5, 0, np.zeros(3), box, 0, np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6", "np.zeros(3), ball4, 0, np.zeros(3), 2.0) wire5 = world.addCompliantWire(pin5, 0, np.zeros(3),", "np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7, 0, np.zeros(3), anymalB,", "anymalC, 0, np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7, 0,", "= raisim.RaisimServer(world) server.launchServer(8080) for i in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe() if", "pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7", "import os import numpy as np import raisimpy as raisim", "0.03, -0.4, 0.8, -0.03, -0.4, 0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain", "0.8) pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\"", "1.0) ball4 = world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9, 0.0, 3.0) box", "= world.addBox(.1, .1, .1, 1) box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1, 0,", "0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file =", "* 100.0 jointDgain = np.ones(anymalC.getDOF()) * 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain)", "jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0, 0.0, 1.0)", "0.8, \"steel\") ball3.setPosition(0.6, 0.0, 1.0) ball4 = world.addSphere(0.1499, 0.8, \"steel\")", "np.zeros(3), ball1, 0, np.zeros(3), 2.0) world.addStiffWire(pin2, 0, np.zeros(3), ball2, 0,", "0, np.zeros(3), box, 0, np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 =", "pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0,", "raisim.RaisimServer(world) server.launchServer(8080) for i in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe() if i", "wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6, 0, np.zeros(3), anymalC, 0, np.zeros(3), 2.0,", "0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1, 0.8)", "+ \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file)", "= world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0, 0.0) pin1 =", "jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget)", "world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\") pin4.setPosition(0.9, 0.0, 3.0) pin4.setBodyType(raisim.BodyType.STATIC) pin5 = world.addSphere(0.1,", "ball3, 0, np.zeros(3), 2.0) world.addStiffWire(pin4, 0, np.zeros(3), ball4, 0, np.zeros(3),", "2.0) wire5 = world.addCompliantWire(pin5, 0, np.zeros(3), box, 0, np.zeros(3), 2.0,", "0.0, 0.03, 0.4, -0.8, -0.03, 0.4, -0.8, 0.03, -0.4, 0.8,", "= np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF()) * 100.0 jointDgain = np.ones(anymalC.getDOF())", "0.8) pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1, 0.8) pin6.setPosition(-3.,", "\"steel\") ball3.setPosition(0.6, 0.0, 1.0) ball4 = world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9,", "0, np.zeros(3), 2.0) world.addStiffWire(pin3, 0, np.zeros(3), ball3, 0, np.zeros(3), 2.0)", "wire7.setTension(310) server = raisim.RaisimServer(world) server.launchServer(8080) for i in range(500000): time.sleep(0.001)", "<reponame>mstoelzle/raisimLib import os import numpy as np import raisimpy as", "= world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3, 0, 4.54,", "world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1, 0.8)", "1) box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1, 0, np.zeros(3), ball1, 0, np.zeros(3),", "1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4", "= np.array([-3, 0, 4.54, 1.0, 0.0, 0.0, 0.0, 0.03, 0.4,", "= -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 =", "jointPgain = np.ones(anymalC.getDOF()) * 100.0 jointDgain = np.ones(anymalC.getDOF()) * 1.0", "jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0,", "pin3 = world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4", "box, 0, np.zeros(3), 2.0, 200) wire5.setStretchType(raisim.StretchType.BOTH) wire6 = world.addCompliantWire(pin6, 0,", "7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__))", "0.4, -0.8, -0.03, 0.4, -0.8, 0.03, -0.4, 0.8, -0.03, -0.4,", "= world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 =", "pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0, 7.0) pin7.setBodyType(raisim.BodyType.STATIC) anymalB_urdf_file", "\"steel\") ball2.setPosition(0.3, 0.0, 1.0) ball3 = world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6,", "+ \"/../../rsc/activation.raisim\") world = raisim.World() ground = world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\",", "anymalB_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\"", "world.addStiffWire(pin3, 0, np.zeros(3), ball3, 0, np.zeros(3), 2.0) world.addStiffWire(pin4, 0, np.zeros(3),", "0, np.zeros(3), 2.0) wire5 = world.addCompliantWire(pin5, 0, np.zeros(3), box, 0,", "ball3 = world.addSphere(0.1499, 0.8, \"steel\") ball3.setPosition(0.6, 0.0, 1.0) ball4 =", "server = raisim.RaisimServer(world) server.launchServer(8080) for i in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe()", "jointNominalConfig = np.array([-3, 0, 4.54, 1.0, 0.0, 0.0, 0.0, 0.03,", "world.addCompliantWire(pin6, 0, np.zeros(3), anymalC, 0, np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7", "-0.4, 0.8, -0.03, -0.4, 0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain =", "\"/../../rsc/activation.raisim\") world = raisim.World() ground = world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\",", "\"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3,", "2.0) world.addStiffWire(pin4, 0, np.zeros(3), ball4, 0, np.zeros(3), 2.0) wire5 =", "0.1, 1.0, 0.0) pin1 = world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0,", "= world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1,", "box = world.addBox(.1, .1, .1, 1) box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1,", "* 1.0 anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] =", "wire6 = world.addCompliantWire(pin6, 0, np.zeros(3), anymalC, 0, np.zeros(3), 2.0, 1000)", "np.zeros(3), 2.0) wire7.setTension(310) server = raisim.RaisimServer(world) server.launchServer(8080) for i in", "pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 = world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0,", "= raisim.World() ground = world.addGround() world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0,", "3.0) box = world.addBox(.1, .1, .1, 1) box.setPosition(0.9, 0.0, 4.2)", "ball4, 0, np.zeros(3), 2.0) wire5 = world.addCompliantWire(pin5, 0, np.zeros(3), box,", "4.2) world.addStiffWire(pin1, 0, np.zeros(3), ball1, 0, np.zeros(3), 2.0) world.addStiffWire(pin2, 0,", "in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe() if i == 5000: world.removeObject(wire7) server.killServer()", "pin6 = world.addSphere(0.1, 0.8) pin6.setPosition(-3., 0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 =", "raisimpy as raisim import math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\")", "jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig) anymalB.setPdGains(jointPgain, jointDgain) anymalB.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalB.setName(\"anymalB\") ball1", "import raisimpy as raisim import math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) +", "np.zeros(3), 2.0) world.addStiffWire(pin3, 0, np.zeros(3), ball3, 0, np.zeros(3), 2.0) world.addStiffWire(pin4,", "0.8, -0.03, -0.4, 0.8]) jointVelocityTarget = np.zeros([anymalC.getDOF()]) jointPgain = np.ones(anymalC.getDOF())", "os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal/urdf/anymal.urdf\" anymalC_urdf_file = os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC =", "anymalB, 0, np.zeros(3), 2.0) wire7.setTension(310) server = raisim.RaisimServer(world) server.launchServer(8080) for", "world.addSphere(0.1, 0.8) pin1.setAppearance(\"1,0,0,0.3\") pin1.setPosition(0.0, 0.0, 3.0) pin1.setBodyType(raisim.BodyType.STATIC) pin2 = world.addSphere(0.1,", "4.54, 1.0, 0.0, 0.0, 0.0, 0.03, 0.4, -0.8, -0.03, 0.4,", "np.zeros(3), anymalC, 0, np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7,", "np import raisimpy as raisim import math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__))", "np.zeros(3), 2.0) world.addStiffWire(pin4, 0, np.zeros(3), ball4, 0, np.zeros(3), 2.0) wire5", "0, np.zeros(3), ball3, 0, np.zeros(3), 2.0) world.addStiffWire(pin4, 0, np.zeros(3), ball4,", "for i in range(500000): time.sleep(0.001) server.integrateWorldThreadSafe() if i == 5000:", "world.setTimeStep(0.001) world.setMaterialPairProp(\"steel\", \"steel\", 0.1, 1.0, 0.0) pin1 = world.addSphere(0.1, 0.8)", "anymalC.setGeneralizedCoordinate(jointNominalConfig) anymalC.setPdGains(jointPgain, jointDgain) anymalC.setPdTarget(jointNominalConfig, jointVelocityTarget) anymalC.setName(\"anymalC\") jointNominalConfig[0] = -4 anymalB.setGeneralizedCoordinate(jointNominalConfig)", "pin5 = world.addSphere(0.1, 0.8) pin5.setPosition(0.9, 0.0, 6.0) pin5.setBodyType(raisim.BodyType.STATIC) pin6 =", ".1, .1, 1) box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1, 0, np.zeros(3), ball1,", "np.zeros(3), 2.0) wire5 = world.addCompliantWire(pin5, 0, np.zeros(3), box, 0, np.zeros(3),", "= os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/anymal_c/urdf/anymal.urdf\" anymalC = world.addArticulatedSystem(anymalC_urdf_file) anymalB = world.addArticulatedSystem(anymalB_urdf_file)", "as raisim import math import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world", "import time raisim.World.setLicenseFile(os.path.dirname(os.path.abspath(__file__)) + \"/../../rsc/activation.raisim\") world = raisim.World() ground =", "np.zeros(3), 2.0) world.addStiffWire(pin2, 0, np.zeros(3), ball2, 0, np.zeros(3), 2.0) world.addStiffWire(pin3,", "0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0,", "1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7, 0, np.zeros(3), anymalB, 0, np.zeros(3),", "1.0, 0.0, 0.0, 0.0, 0.03, 0.4, -0.8, -0.03, 0.4, -0.8,", "0.0, 1.0) ball4 = world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9, 0.0, 3.0)", "0.0, 7.0) pin6.setBodyType(raisim.BodyType.STATIC) pin7 = world.addSphere(0.1, 0.8) pin7.setPosition(-4., 0.0, 7.0)", "wire5 = world.addCompliantWire(pin5, 0, np.zeros(3), box, 0, np.zeros(3), 2.0, 200)", "0, np.zeros(3), 2.0) world.addStiffWire(pin2, 0, np.zeros(3), ball2, 0, np.zeros(3), 2.0)", ".1, 1) box.setPosition(0.9, 0.0, 4.2) world.addStiffWire(pin1, 0, np.zeros(3), ball1, 0,", "pin3.setAppearance(\"0,0,1,0.3\") pin3.setPosition(0.6, 0.0, 3.0) pin3.setBodyType(raisim.BodyType.STATIC) pin4 = world.addSphere(0.1, 0.8) pin4.setAppearance(\"1,0,0,0.3\")", "world.addArticulatedSystem(anymalB_urdf_file) jointNominalConfig = np.array([-3, 0, 4.54, 1.0, 0.0, 0.0, 0.0,", "anymalB.setName(\"anymalB\") ball1 = world.addSphere(0.1498, 0.8, \"steel\") ball1.setPosition(0, 0.0, 1.0) ball2", "0, np.zeros(3), 2.0, 1000) wire6.setStretchType(raisim.StretchType.BOTH) wire7 = world.addCustomWire(pin7, 0, np.zeros(3),", "= world.addSphere(0.1499, 0.8, \"steel\") ball4.setPosition(2.9, 0.0, 3.0) box = world.addBox(.1,", "pin2.setAppearance(\"0,1,0,0.3\") pin2.setPosition(0.3, 0.0, 3.0) pin2.setBodyType(raisim.BodyType.STATIC) pin3 = world.addSphere(0.1, 0.8) pin3.setAppearance(\"0,0,1,0.3\")" ]
[ "get_disk_resource_path(self, connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data']) if not disk_paths: vol_id =", "helper. conn = connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return", "disk_serial = connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path return", "qos_specs): supported_qos_specs = ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec')", "Management class for Storage-related functions (attach, detach, etc). \"\"\" import", "time from os_brick.initiator import connector from os_win import utilsfactory from", "self).attach_volume(*args, **kwargs) @export_path_synchronized def disconnect_volume(self, *args, **kwargs): # We synchronize", "vol_id) return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path): if self._is_block_dev: # We", "block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping: connection_info =", "( (no_bytes + constants.IOPS_BASE_SIZE - 1) // constants.IOPS_BASE_SIZE) @staticmethod def", "live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path,", "unsupported QoS specs: ' '%(unsupported_specs)s. ' 'Supported qos specs: %(supported_qos_specs)s')", "if self._is_block_dev: # We need the Msvm_DiskDrive resource path as", "return ( (no_bytes + constants.IOPS_BASE_SIZE - 1) // constants.IOPS_BASE_SIZE) @staticmethod", "\" \"to instance %(instance_name)s. \" \"Tries left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password(", "is about to be attached to an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args,", "total_iops_sec: disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver): _is_block_dev =", "connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info) serial = connection_info['serial'] disk_path", "\"\"\" def __init__(self): self._vmutils = utilsfactory.get_vmutils() self._default_root_device = 'vda' self.volume_drivers", "self._diskutils = utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils() @property def _connector(self): if", "increments) # as IOPS allocation units. return ( (no_bytes +", "SCSI controller for the vm ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name) slot", "set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs: msg = (_LW('Got unsupported QoS specs:", "connectors # do not use a root helper. conn =", "def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data'])", "tries_left: LOG.exception( _LE(\"Failed to attach volume %(connection_info)s \" \"to instance", "mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count", "self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial, vm_disk in vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial]", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "instance_name, 0) # Attaching to the first slot slot =", "total_iops_sec = int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec: disk_path =", "= int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec: disk_path = self.get_disk_resource_path(connection_info)", "connection_info = vol['connection_info'] volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info):", "specific language governing permissions and limitations # under the License.", "// constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs)", "def get_disk_resource_path(self, connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data']) if not disk_paths: vol_id", "def bytes_per_sec_to_iops(no_bytes): # Hyper-v uses normalized IOPS (8 KB increments)", "# not use this file except in compliance with the", "import utils from nova.virt import driver from nova.virt.hyperv import constants", "# Copyright 2012 <NAME> # Copyright 2013 Cloudbase Solutions Srl", "def _get_disk_ctrl_and_slot(self, instance_name, disk_bus): if disk_bus == constants.CTRL_TYPE_IDE: # Find", "(attach, detach, etc). \"\"\" import time from os_brick.initiator import connector", "volume # serial number, in order to be able to", "disk_path_mapping[disk_serial] = disk_path return disk_path_mapping def get_disk_resource_path(self, connection_info): volume_driver =", "= driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {} for vol in block_mapping: connection_info", "in compliance with the License. You may obtain # a", "initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False _protocol", "uses normalized IOPS (8 KB increments) # as IOPS allocation", "in block_mapping: connection_info = vol['connection_info'] disk_serial = connection_info['serial'] disk_path =", "actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self): # NOTE(lpetrut): the Windows os-brick", "number, in order to be able to retrieve them #", "volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name, block_device_info):", "You may obtain # a copy of the License at", "connection_info['data'].get('qos_specs') or {} if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self, connection_info):", "volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping: return # Mapping", "connection_info): volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching", "an instance. disk_number = self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number)", "instance_name): disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s \" \"from instance:", "tag physical disk resources with the volume # serial number,", "disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path = disk_path return", "= None self._diskutils = utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils() @property def", "self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "resource may not be the right one, # as physical", "_LE, _LI, _LW from nova import utils from nova.virt import", "else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot) def detach_volume(self, connection_info, instance_name): disk_path", "return wrapper def _get_export_path(self, connection_info): return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def", "if driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def", "detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching volume: %(connection_info)s \" \"from %(instance_name)s\", {'connection_info':", "{'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name)", "super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs = ['total_iops_sec',", "%(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info,", "<gh_stars>1-10 # Copyright 2012 <NAME> # Copyright 2013 Cloudbase Solutions", "slot def set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V volume driver", "vm ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path,", "specs: ' '%(unsupported_specs)s. ' 'Supported qos specs: %(supported_qos_specs)s') % {'unsupported_specs':", "\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'],", "with the volume # serial number, in order to be", "self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def attach_volumes(self, volumes, instance_name): for", "get_disk_path_mapping(self, block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {} for vol", "**kwargs) return inner() return wrapper def _get_export_path(self, connection_info): return connection_info['data']['export'].replace('/',", "# avoid the situation when a SMB share is unmounted", "this resource may not be the right one, # as", "os_brick.initiator import connector from os_win import utilsfactory from oslo_log import", "unsupported_specs: msg = (_LW('Got unsupported QoS specs: ' '%(unsupported_specs)s. '", "under the License is distributed on an \"AS IS\" BASIS,", "in order to be able to retrieve them # during", "driver_type = connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type)", "\" \"from instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def", "volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name, block_device_info): # Mapping containing the current", "not find disk path. Volume id: %s\") raise exception.DiskNotFound(err_msg %", "= self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name, block_device_info): #", "% {'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev =", "\" \"Tries left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name, 'tries_left':", "self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev: # We need to tag physical", "def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type not in", "if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self, connection_info): volume_driver = self._get_volume_driver(connection_info)", "connection_info, qos_specs): supported_qos_specs = ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec =", "Reserved. # # Licensed under the Apache License, Version 2.0", "super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized def disconnect_volume(self, *args, **kwargs): # We", "instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name,", "import _, _LE, _LI, _LW from nova import utils from", "under the License. \"\"\" Management class for Storage-related functions (attach,", "class for Storage-related functions (attach, detach, etc). \"\"\" import time", "2012 <NAME> # Copyright 2013 Cloudbase Solutions Srl # All", "LOG.debug(\"Detaching disk %(disk_path)s \" \"from instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name,", "self._connector.get_volume_paths(connection_info['data']) if not disk_paths: vol_id = connection_info['serial'] err_msg = _(\"Could", "import constants LOG = logging.getLogger(__name__) CONF = nova.conf.CONF class VolumeOps(object):", "= logging.getLogger(__name__) CONF = nova.conf.CONF class VolumeOps(object): \"\"\"Management class for", "attached to an instance. disk_number = self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path =", "import nova.conf from nova import exception from nova.i18n import _,", "connection_info, instance_name): LOG.debug(\"Detaching volume: %(connection_info)s \" \"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password(", "to retrieve them # during live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot,", "**kwargs): # We synchronize those operations based on the share", "= dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev =", "<NAME> # Copyright 2013 Cloudbase Solutions Srl # All Rights", "this file except in compliance with the License. You may", "actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self): #", "= dict(local_path_for_loopback=True) def export_path_synchronized(f): def wrapper(inst, connection_info, *args, **kwargs): export_path", "exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else: LOG.warning( _LW(\"Failed to attach volume %(connection_info)s", "def connect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping:", "ctrller_path, slot def set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V volume", "exported by it is about to be attached to an", "ctrller_path, slot, disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot) def", "the vm. ctrller_path = self._vmutils.get_vm_ide_controller( instance_name, 0) # Attaching to", "instance_name): LOG.debug(\"Detaching volume: %(connection_info)s \" \"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info),", "= constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args, **kwargs): self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list)", "from oslo_utils import strutils import nova.conf from nova import exception", "strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs", "mapping: connection_info = vol['connection_info'] volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self,", "LOG.warning( _LW(\"Failed to attach volume %(connection_info)s \" \"to instance %(instance_name)s.", "tries_left -= 1 if not tries_left: LOG.exception( _LE(\"Failed to attach", "disk_path return disk_path_mapping def get_disk_resource_path(self, connection_info): volume_driver = self._get_volume_driver(connection_info) return", "is attached to an instance. disk_number = self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path", "detach_volume(self, connection_info, instance_name): disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s \"", "connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self,", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "the right one, # as physical disk paths can get", "slot slot = 0 else: # Find the SCSI controller", "serial number, in order to be able to retrieve them", "disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot) def detach_volume(self, connection_info,", "err_msg = _(\"Could not find disk path. Volume id: %s\")", "need to tag physical disk resources with the volume #", "\"\"\" import time from os_brick.initiator import connector from os_win import", "log as logging from oslo_utils import strutils import nova.conf from", "units. return ( (no_bytes + constants.IOPS_BASE_SIZE - 1) // constants.IOPS_BASE_SIZE)", "driver.block_device_info_get_mapping(block_device_info) for vol in mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info, instance_name,", "resource path as this # will be used when the", "connection_info): return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver,", "(no_bytes + constants.IOPS_BASE_SIZE - 1) // constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs,", "exception.DiskNotFound(err_msg % vol_id) return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path): if self._is_block_dev:", "slot) def detach_volume(self, connection_info, instance_name): disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk", "right one, # as physical disk paths can get swapped", "path # associated with this resource may not be the", "file except in compliance with the License. You may obtain", "def _get_export_path(self, connection_info): return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def attach_volume(self, *args,", "self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self): # NOTE(lpetrut): the Windows os-brick connectors", "return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info): disk_paths", "_get_disk_res_path(self, disk_path): if self._is_block_dev: # We need the Msvm_DiskDrive resource", "if not disk_paths: vol_id = connection_info['serial'] err_msg = _(\"Could not", "= inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner(): return f(inst, connection_info, *args, **kwargs)", "can get swapped after host reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name)", "disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path = disk_path return disk_res_path", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "connector from os_win import utilsfactory from oslo_log import log as", "block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {} for vol in", "%(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev", "avoid the situation when a SMB share is unmounted while", "\"\"\"Management class for Volume-related tasks \"\"\" def __init__(self): self._vmutils =", "%(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name,", "def disconnect_volume(self, connection_info): volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info,", "0 else: # Find the SCSI controller for the vm", "under the Apache License, Version 2.0 (the \"License\"); you may", "based on the share path in order to # avoid", "controller for the vm. ctrller_path = self._vmutils.get_vm_ide_controller( instance_name, 0) #", "if self._is_block_dev: # We need to tag physical disk resources", "def _connector(self): if not self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval =", "Windows os-brick connectors # do not use a root helper.", "strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else:", "= CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval,", "disk_bus) qos_specs = connection_info['data'].get('qos_specs') or {} if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs)", "current disk paths for each volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if", "instance_name, disk_bus): if disk_bus == constants.CTRL_TYPE_IDE: # Find the IDE", "for vol in mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI):", "' 'Supported qos specs: %(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs})", "= connection_info['serial'] err_msg = _(\"Could not find disk path. Volume", "constants.CTRL_TYPE_IDE: # Find the IDE controller for the vm. ctrller_path", "volume: %(connection_info)s to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver =", "volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name, block_device_info): # Mapping containing", "# Mapping containing the current disk paths for each volume.", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "IOPS (8 KB increments) # as IOPS allocation units. return", "to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info,", "slot, disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot) def detach_volume(self,", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs)", "to in writing, software # distributed under the License is", "supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs: msg = (_LW('Got", "else: LOG.warning( _LW(\"Failed to attach volume %(connection_info)s \" \"to instance", "the IDE controller for the vm. ctrller_path = self._vmutils.get_vm_ide_controller( instance_name,", "attach_volumes(self, volumes, instance_name): for vol in volumes: self.attach_volume(vol['connection_info'], instance_name) def", "find disk path. Volume id: %s\") raise exception.DiskNotFound(err_msg % vol_id)", "1 if not tries_left: LOG.exception( _LE(\"Failed to attach volume %(connection_info)s", "retrieve them # during live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path,", "root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return conn def connect_volumes(self, block_device_info):", "_attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume: %(connection_info)s to %(instance_name)s\",", "self._conn = None self._diskutils = utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils() @property", "get_disk_resource_path(self, connection_info): volume_driver = self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes):", "situation when a SMB share is unmounted while a volume", "actual_disk_mapping: return # Mapping containing virtual disk resource path and", "self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path): if self._is_block_dev: # We need the", "\"to instance %(instance_name)s. \"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info)", "or agreed to in writing, software # distributed under the", "disk_path return disk_res_path def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info =", "= False _protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True) def export_path_synchronized(f):", "required by applicable law or agreed to in writing, software", "path for each volume serial number. The physical path #", "volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes): # Hyper-v uses normalized IOPS (8", "instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else: LOG.warning( _LW(\"Failed to", "= self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s \" \"from instance: %(instance_name)s\", dict(disk_path=disk_path,", "SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False _protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True)", "root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn def connect_volume(self, connection_info):", "instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info) serial = connection_info['serial'] disk_path =", "_extra_connector_args = dict(local_path_for_loopback=True) def export_path_synchronized(f): def wrapper(inst, connection_info, *args, **kwargs):", "= self._vmutils.get_vm_scsi_controller( instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot def", "not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def attach_volumes(self, volumes,", "self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol =", "use a root helper. conn = connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io,", "Apache License, Version 2.0 (the \"License\"); you may # not", "%(instance_name)s. \" \"Tries left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name,", "constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type')", "not support QoS. Ignoring QoS specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev", "functions (attach, detach, etc). \"\"\" import time from os_brick.initiator import", "the situation when a SMB share is unmounted while a", "get swapped after host reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name) for", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data']) if not", "a root helper. conn = connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True,", "time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume: %(connection_info)s", "def get_volume_connector(self): # NOTE(lpetrut): the Windows os-brick connectors # do", "_is_block_dev = False _protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True) def", "supported_qos_specs = ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec') or", "_protocol = constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args, **kwargs): self._extra_connector_args = dict(", "distributed under the License is distributed on an \"AS IS\"", "in mapping: connection_info = vol['connection_info'] volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def", "to an instance. disk_number = self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number(", "+ 1 while tries_left: try: self._attach_volume(connection_info, instance_name, disk_bus) break except", "nova import utils from nova.virt import driver from nova.virt.hyperv import", "def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs: msg", "path as this # will be used when the disk", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "def fix_instance_volume_disk_paths(self, instance_name, block_device_info): # Mapping containing the current disk", "for vol in volumes: self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self, block_device_info): mapping", "# exported by it is about to be attached to", "in mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left =", "normalized IOPS (8 KB increments) # as IOPS allocation units.", "connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V volume driver \" \"does not", "__init__(self, *args, **kwargs): self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs)", "self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs = connection_info['data'].get('qos_specs') or {} if", "vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial, vm_disk in vm_disk_mapping.items(): actual_disk_path", "**kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False _protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args", "from nova.i18n import _, _LE, _LI, _LW from nova import", "%s\") raise exception.DiskNotFound(err_msg % vol_id) return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path):", "return f(inst, connection_info, *args, **kwargs) return inner() return wrapper def", "def __init__(self): self._vmutils = utilsfactory.get_vmutils() self._default_root_device = 'vda' self.volume_drivers =", "None _extra_connector_args = {} def __init__(self): self._conn = None self._diskutils", "not use this file except in compliance with the License.", "not disk_paths: vol_id = connection_info['serial'] err_msg = _(\"Could not find", "%(disk_path)s \" \"from instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev)", "VolumeOps(object): \"\"\"Management class for Volume-related tasks \"\"\" def __init__(self): self._vmutils", "return volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes): # Hyper-v uses normalized IOPS", "volume # exported by it is about to be attached", "exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def attach_volumes(self, volumes, instance_name): for vol in", "self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot def set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s", "writing, software # distributed under the License is distributed on", "and limitations # under the License. \"\"\" Management class for", "set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V volume driver \" \"does", "attached to an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self, connection_info,", "a volume # exported by it is about to be", "physical path # associated with this resource may not be", "CONF = nova.conf.CONF class VolumeOps(object): \"\"\"Management class for Volume-related tasks", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching volume:", "else: # Find the SCSI controller for the vm ctrller_path", "# as IOPS allocation units. return ( (no_bytes + constants.IOPS_BASE_SIZE", "the License. You may obtain # a copy of the", "vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path)", "root helper. conn = connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host)", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "def __init__(self): self._conn = None self._diskutils = utilsfactory.get_diskutils() self._vmutils =", "use this file except in compliance with the License. You", "limitations # under the License. \"\"\" Management class for Storage-related", "return self.volume_drivers[driver_type] def attach_volumes(self, volumes, instance_name): for vol in volumes:", "logging from oslo_utils import strutils import nova.conf from nova import", "instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume: %(connection_info)s to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info),", "scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts,", "ctrller_path, slot) def detach_volume(self, connection_info, instance_name): disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching", "Msvm_DiskDrive resource path as this # will be used when", "ctrller_path = self._vmutils.get_vm_ide_controller( instance_name, 0) # Attaching to the first", "# Find the SCSI controller for the vm ctrller_path =", "constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self, connection_info): driver_type", "connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path return disk_path_mapping def", "self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count +", "{'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus)", "not use a root helper. conn = connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip,", "from oslo_log import log as logging from oslo_utils import strutils", "connection_info['serial'] err_msg = _(\"Could not find disk path. Volume id:", "return self._conn def connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info):", "2013 Cloudbase Solutions Srl # All Rights Reserved. # #", "%(connection_info)s \" \"to instance %(instance_name)s. \"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name':", "_extra_connector_args = {} def __init__(self): self._conn = None self._diskutils =", "% vol_id) return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path): if self._is_block_dev: #", "= self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol", "Hyper-v uses normalized IOPS (8 KB increments) # as IOPS", "instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs =", "total_bytes_sec)) if total_iops_sec: disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver):", "from os_brick.initiator import connector from os_win import utilsfactory from oslo_log", "permissions and limitations # under the License. \"\"\" Management class", "{'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex)", "raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else: LOG.warning( _LW(\"Failed to attach volume", "(_LW('Got unsupported QoS specs: ' '%(unsupported_specs)s. ' 'Supported qos specs:", "ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot", "# serial number, in order to be able to retrieve", "Copyright 2012 <NAME> # Copyright 2013 Cloudbase Solutions Srl #", "strutils import nova.conf from nova import exception from nova.i18n import", "volume: %(connection_info)s \" \"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name})", "reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial, vm_disk in vm_disk_mapping.items():", "dev_info = self.connect_volume(connection_info) serial = connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path,", "= disk_path return disk_path_mapping def get_disk_resource_path(self, connection_info): volume_driver = self._get_volume_driver(connection_info)", "class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol = constants.STORAGE_PROTOCOL_ISCSI def __init__(self,", "\"\"\" Management class for Storage-related functions (attach, detach, etc). \"\"\"", "f(inst, connection_info, *args, **kwargs) return inner() return wrapper def _get_export_path(self,", "etc). \"\"\" import time from os_brick.initiator import connector from os_win", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "KIND, either express or implied. See the # License for", "dict(local_path_for_loopback=True) def export_path_synchronized(f): def wrapper(inst, connection_info, *args, **kwargs): export_path =", "CONF.hyperv.volume_attach_retry_count + 1 while tries_left: try: self._attach_volume(connection_info, instance_name, disk_bus) break", "disk path for each volume serial number. The physical path", "order to # avoid the situation when a SMB share", "\"License\"); you may # not use this file except in", "LOG.debug( \"Attaching volume: %(connection_info)s to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name})", "_is_block_dev = True _protocol = constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args, **kwargs):", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "instance_name, disk_bus) break except Exception as ex: tries_left -= 1", "supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev = True _protocol = None", "instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug(", "express or implied. See the # License for the specific", "disk_number = self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path", "ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol = constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args,", "_is_block_dev = True _protocol = None _extra_connector_args = {} def", "self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name, disk_bus): if disk_bus ==", "the Apache License, Version 2.0 (the \"License\"); you may #", "disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev:", "self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else: LOG.warning( _LW(\"Failed to attach", "IOPS allocation units. return ( (no_bytes + constants.IOPS_BASE_SIZE - 1)", "to be able to retrieve them # during live migration.", "msg = (_LW('Got unsupported QoS specs: ' '%(unsupported_specs)s. ' 'Supported", "= {} for vol in block_mapping: connection_info = vol['connection_info'] disk_serial", "allocation units. return ( (no_bytes + constants.IOPS_BASE_SIZE - 1) //", "os-brick connectors # do not use a root helper. conn", "driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def attach_volumes(self,", "return disk_res_path def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info)", "inner(): return f(inst, connection_info, *args, **kwargs) return inner() return wrapper", "License. \"\"\" Management class for Storage-related functions (attach, detach, etc).", "physical disk paths can get swapped after host reboots. vm_disk_mapping", "See the # License for the specific language governing permissions", "LOG.info(_LI(\"The %(protocol)s Hyper-V volume driver \" \"does not support QoS.", "-= 1 if not tries_left: LOG.exception( _LE(\"Failed to attach volume", "disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s \" \"from instance: %(instance_name)s\",", "number. The physical path # associated with this resource may", "SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self, connection_info): driver_type =", "IDE controller for the vm. ctrller_path = self._vmutils.get_vm_ide_controller( instance_name, 0)", "- 1) // constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs =", "def get_disk_resource_path(self, connection_info): volume_driver = self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod def", "= vol['connection_info'] disk_serial = connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] =", "as IOPS allocation units. return ( (no_bytes + constants.IOPS_BASE_SIZE -", "the License. \"\"\" Management class for Storage-related functions (attach, detach,", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "utilsfactory.get_vmutils() self._default_root_device = 'vda' self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI:", "We need the Msvm_DiskDrive resource path as this # will", "conn def connect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in", "not be the right one, # as physical disk paths", "# as physical disk paths can get swapped after host", "self._is_block_dev: # We need the Msvm_DiskDrive resource path as this", "disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V volume driver \" \"does not support", "@property def _connector(self): if not self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval", "for the vm ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path)", "= self._vmutils.get_vm_ide_controller( instance_name, 0) # Attaching to the first slot", "= self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching volume: %(connection_info)s", "path in order to # avoid the situation when a", "from nova import utils from nova.virt import driver from nova.virt.hyperv", "self.connect_volume(connection_info) serial = connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path, slot =", "%(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name, disk_bus):", "instance %(instance_name)s. \" \"Tries left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name':", "be the right one, # as physical disk paths can", "law or agreed to in writing, software # distributed under", "Solutions Srl # All Rights Reserved. # # Licensed under", "= _(\"Could not find disk path. Volume id: %s\") raise", "['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec", "Mapping containing virtual disk resource path and the physical #", "_protocol = None _extra_connector_args = {} def __init__(self): self._conn =", "inner() return wrapper def _get_export_path(self, connection_info): return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized", "disconnect_volume(self, *args, **kwargs): # We synchronize those operations based on", "ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if", "The physical path # associated with this resource may not", "**kwargs) def set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs = ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs,", "the first slot slot = 0 else: # Find the", "nova.conf.CONF class VolumeOps(object): \"\"\"Management class for Volume-related tasks \"\"\" def", "constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args, **kwargs): self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver,", "implied. See the # License for the specific language governing", "QoS specs: ' '%(unsupported_specs)s. ' 'Supported qos specs: %(supported_qos_specs)s') %", "self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot)", "resources with the volume # serial number, in order to", "specs: %(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object):", "NOTE(lpetrut): the Windows os-brick connectors # do not use a", "raise exception.DiskNotFound(err_msg % vol_id) return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path): if", "def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count + 1", "def _get_disk_res_path(self, disk_path): if self._is_block_dev: # We need the Msvm_DiskDrive", "self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def", "self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path return disk_path_mapping def get_disk_resource_path(self, connection_info): volume_driver", "= disk_path return disk_res_path def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info", "%(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def", "**kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized def disconnect_volume(self, *args, **kwargs): #", "'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self,", "= connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return", "instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name,", "'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs =", "a SMB share is unmounted while a volume # exported", "volume_driver = self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes): # Hyper-v", "slot = self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot def set_disk_qos_specs(self, connection_info, disk_qos_specs):", "*args, **kwargs): self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class", "CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args)", "physical disk resources with the volume # serial number, in", "vol in mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left", "True _protocol = None _extra_connector_args = {} def __init__(self): self._conn", "def get_disk_path_mapping(self, block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {} for", "if not self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn", "be able to retrieve them # during live migration. self._vmutils.attach_volume_to_controller(instance_name,", "= CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None,", "swapped after host reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial,", "LOG = logging.getLogger(__name__) CONF = nova.conf.CONF class VolumeOps(object): \"\"\"Management class", "import utilsfactory from oslo_log import log as logging from oslo_utils", "vol['connection_info'] disk_serial = connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path", "def detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching volume: %(connection_info)s \" \"from %(instance_name)s\",", "_connector(self): if not self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval", "the SCSI controller for the vm ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name)", "instance_name) for serial, vm_disk in vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial] if", "constants.IOPS_BASE_SIZE - 1) // constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs", "those operations based on the share path in order to", "do not use a root helper. conn = connector.get_connector_properties( root_helper=None,", "language governing permissions and limitations # under the License. \"\"\"", "from nova.virt import driver from nova.virt.hyperv import constants LOG =", "connection_info, *args, **kwargs): export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner(): return", "= connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn", "int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec: disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path,", "tries_left: try: self._attach_volume(connection_info, instance_name, disk_bus) break except Exception as ex:", "multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return conn def connect_volumes(self, block_device_info): mapping =", "disk_res_path = disk_path return disk_res_path def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI):", "# Mapping containing virtual disk resource path and the physical", "tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume:", "def set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs = ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs)", "dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol = constants.STORAGE_PROTOCOL_ISCSI def", "to an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self, connection_info, qos_specs):", "disk paths for each volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if not", "= constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True) def export_path_synchronized(f): def wrapper(inst, connection_info,", "nova.virt.hyperv import constants LOG = logging.getLogger(__name__) CONF = nova.conf.CONF class", "BaseVolumeDriver(object): _is_block_dev = True _protocol = None _extra_connector_args = {}", "_get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers:", "instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name, disk_bus): if disk_bus", "conn = connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return conn", "vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self): # NOTE(lpetrut): the", "# will be used when the disk is attached to", "each volume serial number. The physical path # associated with", "volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info)", "connection_info = vol['connection_info'] disk_serial = connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial]", "block_device_info): # Mapping containing the current disk paths for each", "def detach_volume(self, connection_info, instance_name): disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s", "self._is_block_dev: # We need to tag physical disk resources with", "if disk_bus == constants.CTRL_TYPE_IDE: # Find the IDE controller for", "to # avoid the situation when a SMB share is", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "'instance_name': instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI):", "KB increments) # as IOPS allocation units. return ( (no_bytes", "disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver): _is_block_dev = True", "constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs) if", "= set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs: msg = (_LW('Got unsupported QoS", "# # Licensed under the Apache License, Version 2.0 (the", "# Copyright 2013 Cloudbase Solutions Srl # All Rights Reserved.", "nova.conf from nova import exception from nova.i18n import _, _LE,", "block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping: self.disconnect_volume(vol['connection_info']) def", "self._conn def connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data'])", "self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False _protocol = constants.STORAGE_PROTOCOL_SMBFS", "each volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping: return #", "Exception as ex: tries_left -= 1 if not tries_left: LOG.exception(", "for each volume serial number. The physical path # associated", "vol in mapping: connection_info = vol['connection_info'] volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info)", "instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot def set_disk_qos_specs(self, connection_info,", "# under the License. \"\"\" Management class for Storage-related functions", "disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data']) if", "**self._extra_connector_args) return self._conn def connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self,", "return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self, disk_path): if self._is_block_dev: # We need", "\" \"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) volume_driver =", "connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus) if", "# We synchronize those operations based on the share path", "enforce_multipath=True, host=CONF.host) return conn def connect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info)", "associated with this resource may not be the right one,", "VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec = int(qos_specs.get('total_iops_sec')", "= 'vda' self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC:", "containing virtual disk resource path and the physical # disk", "obtain # a copy of the License at # #", "qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self, connection_info): volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info)", "Version 2.0 (the \"License\"); you may # not use this", "'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec =", "{} for vol in block_mapping: connection_info = vol['connection_info'] disk_serial =", "to tag physical disk resources with the volume # serial", "while tries_left: try: self._attach_volume(connection_info, instance_name, disk_bus) break except Exception as", "ex: tries_left -= 1 if not tries_left: LOG.exception( _LE(\"Failed to", "volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching volume: %(connection_info)s \" \"from", "Storage-related functions (attach, detach, etc). \"\"\" import time from os_brick.initiator", "left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval)", "wrapper def _get_export_path(self, connection_info): return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def attach_volume(self,", "to be attached to an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def", "Attaching to the first slot slot = 0 else: #", "License for the specific language governing permissions and limitations #", "if vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self): # NOTE(lpetrut):", "disk_paths = self._connector.get_volume_paths(connection_info['data']) if not disk_paths: vol_id = connection_info['serial'] err_msg", "def __init__(self, *args, **kwargs): self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args,", "id: %s\") raise exception.DiskNotFound(err_msg % vol_id) return self._get_disk_res_path(disk_paths[0]) def _get_disk_res_path(self,", "attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info) serial = connection_info['serial']", "disk_bus) if self._is_block_dev: # We need to tag physical disk", "to the first slot slot = 0 else: # Find", "= self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs = connection_info['data'].get('qos_specs') or {}", "self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes): # Hyper-v uses normalized", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "\"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info)", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "class BaseVolumeDriver(object): _is_block_dev = True _protocol = None _extra_connector_args =", "except Exception as ex: tries_left -= 1 if not tries_left:", "about to be attached to an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs)", "volume_id=connection_info['serial'], reason=ex) else: LOG.warning( _LW(\"Failed to attach volume %(connection_info)s \"", "reason=ex) else: LOG.warning( _LW(\"Failed to attach volume %(connection_info)s \" \"to", "\" \"does not support QoS. Ignoring QoS specs.\"), dict(protocol=self._protocol)) class", "QoS specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol =", "block_mapping: connection_info = vol['connection_info'] disk_serial = connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info)", "after host reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial, vm_disk", "'vda' self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()}", "oslo_utils import strutils import nova.conf from nova import exception from", "= utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils() @property def _connector(self): if not", "# Attaching to the first slot slot = 0 else:", "supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec = int(qos_specs.get('total_iops_sec') or", "Rights Reserved. # # Licensed under the Apache License, Version", "with this resource may not be the right one, #", "= connection_info['data'].get('qos_specs') or {} if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self,", "disk_path, ctrller_path, slot) def detach_volume(self, connection_info, instance_name): disk_path = self.get_disk_resource_path(connection_info)", "'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev = True _protocol =", "We need to tag physical disk resources with the volume", "if not tries_left: LOG.exception( _LE(\"Failed to attach volume %(connection_info)s \"", "to attach volume %(connection_info)s \" \"to instance %(instance_name)s. \" \"Tries", "operations based on the share path in order to #", "connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return conn def connect_volumes(self,", "\"Attaching volume: %(connection_info)s to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver", "exception from nova.i18n import _, _LE, _LI, _LW from nova", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "'Supported qos specs: %(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg)", "vol_id = connection_info['serial'] err_msg = _(\"Could not find disk path.", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info): disk_paths =", "os_win import utilsfactory from oslo_log import log as logging from", "constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True) def export_path_synchronized(f): def wrapper(inst, connection_info, *args,", "= nova.conf.CONF class VolumeOps(object): \"\"\"Management class for Volume-related tasks \"\"\"", "instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs = connection_info['data'].get('qos_specs')", "= connector.get_connector_properties( root_helper=None, my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return conn def", "the disk is attached to an instance. disk_number = self._diskutils.get_device_number_from_device_name(", "self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot) def detach_volume(self, connection_info, instance_name): disk_path =", "by it is about to be attached to an instance.", "volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self, connection_info): volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def", "disconnect_volume(self, connection_info): volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info, instance_name):", "'instance_name': instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else: LOG.warning( _LW(\"Failed", "export_path_synchronized(f): def wrapper(inst, connection_info, *args, **kwargs): export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path)", "= ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec = int(qos_specs.get('total_bytes_sec') or 0)", "import log as logging from oslo_utils import strutils import nova.conf", "self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping: return # Mapping containing virtual disk", "%(instance_name)s. \"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed(", "disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume: %(connection_info)s to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name':", "as logging from oslo_utils import strutils import nova.conf from nova", "= self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev: # We need to tag", "physical # disk path for each volume serial number. The", "\"does not support QoS. Ignoring QoS specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver):", "+ constants.IOPS_BASE_SIZE - 1) // constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs, supported_qos_specs):", "= self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path = disk_path return disk_res_path def", "compliance with the License. You may obtain # a copy", "oslo_log import log as logging from oslo_utils import strutils import", "for vol in mapping: connection_info = vol['connection_info'] volume_driver = self._get_volume_driver(connection_info)", "import strutils import nova.conf from nova import exception from nova.i18n", "is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name, disk_bus): if disk_bus == constants.CTRL_TYPE_IDE: #", "attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized def disconnect_volume(self, *args,", "' '%(unsupported_specs)s. ' 'Supported qos specs: %(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs,", "logging.getLogger(__name__) CONF = nova.conf.CONF class VolumeOps(object): \"\"\"Management class for Volume-related", "volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs = connection_info['data'].get('qos_specs') or {} if qos_specs:", "not actual_disk_mapping: return # Mapping containing virtual disk resource path", "driver \" \"does not support QoS. Ignoring QoS specs.\"), dict(protocol=self._protocol))", "disk paths can get swapped after host reboots. vm_disk_mapping =", "connect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping: connection_info", "if total_iops_sec: disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver): _is_block_dev", "controller for the vm ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name) slot =", "**kwargs): self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver):", "# NOTE(lpetrut): the Windows os-brick connectors # do not use", "support QoS. Ignoring QoS specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev =", "the # License for the specific language governing permissions and", "= self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping: return # Mapping containing virtual", "import connector from os_win import utilsfactory from oslo_log import log", "instance_name, disk_bus) qos_specs = connection_info['data'].get('qos_specs') or {} if qos_specs: volume_driver.set_disk_qos_specs(connection_info,", "# # Unless required by applicable law or agreed to", "= self.connect_volume(connection_info) serial = connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path, slot", "import exception from nova.i18n import _, _LE, _LI, _LW from", "Mapping containing the current disk paths for each volume. actual_disk_mapping", "# We need the Msvm_DiskDrive resource path as this #", "connection_info), 'instance_name': instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info, instance_name,", "@staticmethod def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs:", "or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec: disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec)", "disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path return disk_path_mapping def get_disk_resource_path(self,", "self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path = disk_path", "protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn def connect_volume(self,", "volume_driver = self._get_volume_driver(connection_info) volume_driver.attach_volume(connection_info, instance_name, disk_bus) qos_specs = connection_info['data'].get('qos_specs') or", "actual_disk_path = actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def", "disk_bus) break except Exception as ex: tries_left -= 1 if", "= utilsfactory.get_vmutils() @property def _connector(self): if not self._conn: scan_attempts =", "from nova import exception from nova.i18n import _, _LE, _LI,", "if not actual_disk_mapping: return # Mapping containing virtual disk resource", "'\\\\') @export_path_synchronized def attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized", "= driver.block_device_info_get_mapping(block_device_info) for vol in mapping: connection_info = vol['connection_info'] volume_driver", "disk resources with the volume # serial number, in order", "the Windows os-brick connectors # do not use a root", "for the vm. ctrller_path = self._vmutils.get_vm_ide_controller( instance_name, 0) # Attaching", "False _protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True) def export_path_synchronized(f): def", "int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec = int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if", "instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name, block_device_info): # Mapping containing the", "= True _protocol = None _extra_connector_args = {} def __init__(self):", "disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info) serial = connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path'])", "2.0 (the \"License\"); you may # not use this file", "def disconnect_volume(self, *args, **kwargs): # We synchronize those operations based", "self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class FCVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol = constants.STORAGE_PROTOCOL_FC", "@utils.synchronized(export_path) def inner(): return f(inst, connection_info, *args, **kwargs) return inner()", "slot = 0 else: # Find the SCSI controller for", "= self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot def set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The", "vol in block_mapping: connection_info = vol['connection_info'] disk_serial = connection_info['serial'] disk_path", "governing permissions and limitations # under the License. \"\"\" Management", "path. Volume id: %s\") raise exception.DiskNotFound(err_msg % vol_id) return self._get_disk_res_path(disk_paths[0])", "set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs = ['total_iops_sec', 'total_bytes_sec'] VolumeOps.validate_qos_specs(qos_specs, supported_qos_specs) total_bytes_sec", "= None _extra_connector_args = {} def __init__(self): self._conn = None", "unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev = True _protocol", "True _protocol = constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args, **kwargs): self._extra_connector_args =", "= self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path =", "host reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial, vm_disk in", "by applicable law or agreed to in writing, software #", "Find the IDE controller for the vm. ctrller_path = self._vmutils.get_vm_ide_controller(", "volume %(connection_info)s \" \"to instance %(instance_name)s. \" \"Tries left: %(tries_left)s.\"),", "= 0 else: # Find the SCSI controller for the", "device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn def connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data'])", "VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec: disk_path = self.get_disk_resource_path(connection_info) self._vmutils.set_disk_qos_specs(disk_path, total_iops_sec) class", "connection_info, instance_name): disk_path = self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s \" \"from", "instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count + 1 while tries_left: try:", "{ constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self, connection_info):", "disk_number) else: disk_res_path = disk_path return disk_res_path def attach_volume(self, connection_info,", "= int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec = int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec))", "def wrapper(inst, connection_info, *args, **kwargs): export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path) def", "is unmounted while a volume # exported by it is", "during live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name,", "constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type", "disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name, disk_bus): if disk_bus == constants.CTRL_TYPE_IDE:", "= self._get_disk_res_path(dev_info['path']) ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev: #", "mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self,", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "attach volume %(connection_info)s \" \"to instance %(instance_name)s. \"), {'connection_info': strutils.mask_dict_password(", "Volume-related tasks \"\"\" def __init__(self): self._vmutils = utilsfactory.get_vmutils() self._default_root_device =", "to attach volume %(connection_info)s \" \"to instance %(instance_name)s. \"), {'connection_info':", "for vol in block_mapping: connection_info = vol['connection_info'] disk_serial = connection_info['serial']", "total_bytes_sec = int(qos_specs.get('total_bytes_sec') or 0) total_iops_sec = int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops(", "used when the disk is attached to an instance. disk_number", "volumes: self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for", "_LI, _LW from nova import utils from nova.virt import driver", "the physical # disk path for each volume serial number.", "as physical disk paths can get swapped after host reboots.", "return disk_path_mapping def get_disk_resource_path(self, connection_info): volume_driver = self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info)", "instance_name, block_device_info): # Mapping containing the current disk paths for", "attach volume %(connection_info)s \" \"to instance %(instance_name)s. \" \"Tries left:", "or 0) total_iops_sec = int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec:", "self._extra_connector_args = dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev", "driver.block_device_info_get_mapping(block_device_info) for vol in mapping: connection_info = vol['connection_info'] volume_driver =", "utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils() @property def _connector(self): if not self._conn:", "share path in order to # avoid the situation when", "nova.virt import driver from nova.virt.hyperv import constants LOG = logging.getLogger(__name__)", "{'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self,", "get_volume_connector(self): # NOTE(lpetrut): the Windows os-brick connectors # do not", "volume driver \" \"does not support QoS. Ignoring QoS specs.\"),", "scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory( protocol=self._protocol,", "volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {}", "connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def", "# disk path for each volume serial number. The physical", "driver from nova.virt.hyperv import constants LOG = logging.getLogger(__name__) CONF =", "Volume id: %s\") raise exception.DiskNotFound(err_msg % vol_id) return self._get_disk_res_path(disk_paths[0]) def", "try: self._attach_volume(connection_info, instance_name, disk_bus) break except Exception as ex: tries_left", "def inner(): return f(inst, connection_info, *args, **kwargs) return inner() return", "detach, etc). \"\"\" import time from os_brick.initiator import connector from", "from nova.virt.hyperv import constants LOG = logging.getLogger(__name__) CONF = nova.conf.CONF", "= vol['connection_info'] volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info): block_mapping", "may obtain # a copy of the License at #", "vol in volumes: self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self, block_device_info): mapping =", "QoS. Ignoring QoS specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True", "when a SMB share is unmounted while a volume #", "# All Rights Reserved. # # Licensed under the Apache", "instance %(instance_name)s. \"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info) raise", "'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching", "dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self, instance_name, disk_bus): if", "# Find the IDE controller for the vm. ctrller_path =", "bytes_per_sec_to_iops(no_bytes): # Hyper-v uses normalized IOPS (8 KB increments) #", "Unless required by applicable law or agreed to in writing,", "\"from instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path, is_physical=self._is_block_dev) def _get_disk_ctrl_and_slot(self,", "super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False _protocol =", "@export_path_synchronized def attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized def", "serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path, slot) def detach_volume(self, connection_info, instance_name):", "# do not use a root helper. conn = connector.get_connector_properties(", "connection_info): volume_driver = self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes): #", "raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def attach_volumes(self, volumes, instance_name): for vol", "self._attach_volume(connection_info, instance_name, disk_bus) break except Exception as ex: tries_left -=", "disk path. Volume id: %s\") raise exception.DiskNotFound(err_msg % vol_id) return", "self._vmutils.get_vm_ide_controller( instance_name, 0) # Attaching to the first slot slot", "in volumes: self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info)", "_LW from nova import utils from nova.virt import driver from", "device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn def connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data']) def", "not tries_left: LOG.exception( _LE(\"Failed to attach volume %(connection_info)s \" \"to", "Copyright 2013 Cloudbase Solutions Srl # All Rights Reserved. #", "!= actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self): # NOTE(lpetrut): the Windows", "if unsupported_specs: msg = (_LW('Got unsupported QoS specs: ' '%(unsupported_specs)s.", "them # during live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path, serial=serial)", "disk resource path and the physical # disk path for", "return ctrller_path, slot def set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V", "connection_info, *args, **kwargs) return inner() return wrapper def _get_export_path(self, connection_info):", "Srl # All Rights Reserved. # # Licensed under the", "Cloudbase Solutions Srl # All Rights Reserved. # # Licensed", "applicable law or agreed to in writing, software # distributed", "*args, **kwargs) return inner() return wrapper def _get_export_path(self, connection_info): return", "We synchronize those operations based on the share path in", "connection_info), 'instance_name': instance_name}) self.disconnect_volume(connection_info) raise exception.VolumeAttachFailed( volume_id=connection_info['serial'], reason=ex) else: LOG.warning(", "LOG.debug(\"Detaching volume: %(connection_info)s \" \"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name':", "instance_name): for vol in volumes: self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self, block_device_info):", "= self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod def bytes_per_sec_to_iops(no_bytes): # Hyper-v uses", "an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs", "\"to instance %(instance_name)s. \" \"Tries left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info),", "qos_specs) def disconnect_volume(self, connection_info): volume_driver = self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self,", "instance. disk_number = self._diskutils.get_device_number_from_device_name( disk_path) disk_res_path = self._vmutils.get_mounted_disk_by_drive_number( disk_number) else:", "OF ANY KIND, either express or implied. See the #", "share is unmounted while a volume # exported by it", "self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data']) if not disk_paths:", "SMB share is unmounted while a volume # exported by", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args,", "volume %(connection_info)s \" \"to instance %(instance_name)s. \"), {'connection_info': strutils.mask_dict_password( connection_info),", "ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev: # We need", "connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume: %(connection_info)s to %(instance_name)s\", {'connection_info':", "one, # as physical disk paths can get swapped after", "%(connection_info)s \" \"from %(instance_name)s\", {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) volume_driver", "the volume # serial number, in order to be able", "def attach_volume(self, *args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized def disconnect_volume(self,", "self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol", "disconnect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping: self.disconnect_volume(vol['connection_info'])", "= CONF.hyperv.volume_attach_retry_count + 1 while tries_left: try: self._attach_volume(connection_info, instance_name, disk_bus)", "def set_disk_qos_specs(self, connection_info, disk_qos_specs): LOG.info(_LI(\"The %(protocol)s Hyper-V volume driver \"", "disk is attached to an instance. disk_number = self._diskutils.get_device_number_from_device_name( disk_path)", "export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner(): return f(inst, connection_info, *args,", "*args, **kwargs): super(SMBFSVolumeDriver, self).attach_volume(*args, **kwargs) @export_path_synchronized def disconnect_volume(self, *args, **kwargs):", "be attached to an instance. super(SMBFSVolumeDriver, self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self,", "as this # will be used when the disk is", "nova.i18n import _, _LE, _LI, _LW from nova import utils", "_LE(\"Failed to attach volume %(connection_info)s \" \"to instance %(instance_name)s. \"),", "self._vmutils.get_mounted_disk_by_drive_number( disk_number) else: disk_res_path = disk_path return disk_res_path def attach_volume(self,", "migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path, serial=serial) else: self._vmutils.attach_drive(instance_name, disk_path, ctrller_path,", "self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info) def fix_instance_volume_disk_paths(self, instance_name, block_device_info): # Mapping", "utilsfactory.get_vmutils() @property def _connector(self): if not self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count", "0) total_iops_sec = int(qos_specs.get('total_iops_sec') or VolumeOps.bytes_per_sec_to_iops( total_bytes_sec)) if total_iops_sec: disk_path", "resource path and the physical # disk path for each", "disk %(disk_path)s \" \"from instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name)) self._vmutils.detach_vm_disk(instance_name, disk_path,", "serial, vm_disk in vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] !=", "= (_LW('Got unsupported QoS specs: ' '%(unsupported_specs)s. ' 'Supported qos", "# associated with this resource may not be the right", "self._default_root_device = 'vda' self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(),", "host=CONF.host) return conn def connect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for", "unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs: msg = (_LW('Got unsupported", "self._vmutils = utilsfactory.get_vmutils() @property def _connector(self): if not self._conn: scan_attempts", "strutils.mask_dict_password( connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info) volume_driver.detach_volume(connection_info, instance_name) volume_driver.disconnect_volume(connection_info)", "be used when the disk is attached to an instance.", "able to retrieve them # during live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path,", "either express or implied. See the # License for the", "_(\"Could not find disk path. Volume id: %s\") raise exception.DiskNotFound(err_msg", "in order to # avoid the situation when a SMB", "vm_disk in vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] != actual_disk_path:", "paths for each volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping:", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "1) // constants.IOPS_BASE_SIZE) @staticmethod def validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference(", "self.get_disk_resource_path(connection_info) LOG.debug(\"Detaching disk %(disk_path)s \" \"from instance: %(instance_name)s\", dict(disk_path=disk_path, instance_name=instance_name))", "_get_export_path(self, connection_info): return connection_info['data']['export'].replace('/', '\\\\') @export_path_synchronized def attach_volume(self, *args, **kwargs):", "return # Mapping containing virtual disk resource path and the", "may # not use this file except in compliance with", "self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory(", "= connection_info['serial'] disk_path = self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path return disk_path_mapping", "qos specs: %(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class", "connection_info): return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def get_disk_resource_path(self, connection_info):", "= {} def __init__(self): self._conn = None self._diskutils = utilsfactory.get_diskutils()", "# License for the specific language governing permissions and limitations", "with the License. You may obtain # a copy of", "FCVolumeDriver()} def _get_volume_driver(self, connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type not", "this # will be used when the disk is attached", "constants LOG = logging.getLogger(__name__) CONF = nova.conf.CONF class VolumeOps(object): \"\"\"Management", "vm. ctrller_path = self._vmutils.get_vm_ide_controller( instance_name, 0) # Attaching to the", "_protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args = dict(local_path_for_loopback=True) def export_path_synchronized(f): def wrapper(inst,", "**kwargs): export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner(): return f(inst, connection_info,", "block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {} for vol in block_mapping:", "else: disk_res_path = disk_path return disk_res_path def attach_volume(self, connection_info, instance_name,", "you may # not use this file except in compliance", "it is about to be attached to an instance. super(SMBFSVolumeDriver,", "def export_path_synchronized(f): def wrapper(inst, connection_info, *args, **kwargs): export_path = inst._get_export_path(connection_info)", "for Storage-related functions (attach, detach, etc). \"\"\" import time from", "volume serial number. The physical path # associated with this", "_, _LE, _LI, _LW from nova import utils from nova.virt", "first slot slot = 0 else: # Find the SCSI", "%(connection_info)s \" \"to instance %(instance_name)s. \" \"Tries left: %(tries_left)s.\"), {'connection_info':", "Find the SCSI controller for the vm ctrller_path = self._vmutils.get_vm_scsi_controller(", "disk_bus == constants.CTRL_TYPE_IDE: # Find the IDE controller for the", "serial number. The physical path # associated with this resource", "connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn def", "Ignoring QoS specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol", "dict( initiator_list=CONF.hyperv.iscsi_initiator_list) super(ISCSIVolumeDriver, self).__init__(*args, **kwargs) class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "from os_win import utilsfactory from oslo_log import log as logging", "%(protocol)s Hyper-V volume driver \" \"does not support QoS. Ignoring", "**kwargs) @export_path_synchronized def disconnect_volume(self, *args, **kwargs): # We synchronize those", "disk_path_mapping def get_disk_resource_path(self, connection_info): volume_driver = self._get_volume_driver(connection_info) return volume_driver.get_disk_resource_path(connection_info) @staticmethod", "# Hyper-v uses normalized IOPS (8 KB increments) # as", "may not be the right one, # as physical disk", "as ex: tries_left -= 1 if not tries_left: LOG.exception( _LE(\"Failed", "{} def __init__(self): self._conn = None self._diskutils = utilsfactory.get_diskutils() self._vmutils", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "break except Exception as ex: tries_left -= 1 if not", "containing the current disk paths for each volume. actual_disk_mapping =", "need the Msvm_DiskDrive resource path as this # will be", "@export_path_synchronized def disconnect_volume(self, *args, **kwargs): # We synchronize those operations", "on the share path in order to # avoid the", "self._get_volume_driver(connection_info) volume_driver.disconnect_volume(connection_info) def detach_volume(self, connection_info, instance_name): LOG.debug(\"Detaching volume: %(connection_info)s \"", "# We need to tag physical disk resources with the", "specs.\"), dict(protocol=self._protocol)) class ISCSIVolumeDriver(BaseVolumeDriver): _is_block_dev = True _protocol = constants.STORAGE_PROTOCOL_ISCSI", "for Volume-related tasks \"\"\" def __init__(self): self._vmutils = utilsfactory.get_vmutils() self._default_root_device", "virtual disk resource path and the physical # disk path", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count + 1 while tries_left:", "disk_paths: vol_id = connection_info['serial'] err_msg = _(\"Could not find disk", "= self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info): block_mapping = driver.block_device_info_get_mapping(block_device_info) disk_path_mapping", "the vm ctrller_path = self._vmutils.get_vm_scsi_controller( instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path) return", "= True _protocol = constants.STORAGE_PROTOCOL_ISCSI def __init__(self, *args, **kwargs): self._extra_connector_args", "\"Tries left: %(tries_left)s.\"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name, 'tries_left': tries_left})", "the Msvm_DiskDrive resource path as this # will be used", "= { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(), constants.STORAGE_PROTOCOL_ISCSI: ISCSIVolumeDriver(), constants.STORAGE_PROTOCOL_FC: FCVolumeDriver()} def _get_volume_driver(self,", "disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count + 1 while tries_left: try: self._attach_volume(connection_info,", "LOG.exception( _LE(\"Failed to attach volume %(connection_info)s \" \"to instance %(instance_name)s.", "qos_specs = connection_info['data'].get('qos_specs') or {} if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def", "the current disk paths for each volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info)", "return conn def connect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol", "connection_info): disk_paths = self._connector.get_volume_paths(connection_info['data']) if not disk_paths: vol_id = connection_info['serial']", "{} if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self, connection_info): volume_driver =", "1 while tries_left: try: self._attach_volume(connection_info, instance_name, disk_bus) break except Exception", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "*args, **kwargs): export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner(): return f(inst,", "volumes, instance_name): for vol in volumes: self.attach_volume(vol['connection_info'], instance_name) def disconnect_volumes(self,", "tries_left = CONF.hyperv.volume_attach_retry_count + 1 while tries_left: try: self._attach_volume(connection_info, instance_name,", "strutils.mask_dict_password( connection_info), 'instance_name': instance_name, 'tries_left': tries_left}) time.sleep(CONF.hyperv.volume_attach_retry_interval) def _attach_volume(self, connection_info,", "will be used when the disk is attached to an", "CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn = connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io,", "order to be able to retrieve them # during live", "mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping: connection_info = vol['connection_info']", "and the physical # disk path for each volume serial", "paths can get swapped after host reboots. vm_disk_mapping = self._vmutils.get_vm_physical_disk_mapping(", "validate_qos_specs(qos_specs, supported_qos_specs): unsupported_specs = set(qos_specs.keys()).difference( supported_qos_specs) if unsupported_specs: msg =", "disk_path): if self._is_block_dev: # We need the Msvm_DiskDrive resource path", "utilsfactory from oslo_log import log as logging from oslo_utils import", "for the specific language governing permissions and limitations # under", "supported_qos_specs) if unsupported_specs: msg = (_LW('Got unsupported QoS specs: '", "self).disconnect_volume(*args, **kwargs) def set_disk_qos_specs(self, connection_info, qos_specs): supported_qos_specs = ['total_iops_sec', 'total_bytes_sec']", "_LW(\"Failed to attach volume %(connection_info)s \" \"to instance %(instance_name)s. \"", "def _attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): LOG.debug( \"Attaching volume: %(connection_info)s to", "class SMBFSVolumeDriver(BaseVolumeDriver): _is_block_dev = False _protocol = constants.STORAGE_PROTOCOL_SMBFS _extra_connector_args =", "# during live migration. self._vmutils.attach_volume_to_controller(instance_name, ctrller_path, slot, disk_path, serial=serial) else:", "@staticmethod def bytes_per_sec_to_iops(no_bytes): # Hyper-v uses normalized IOPS (8 KB", "the share path in order to # avoid the situation", "for each volume. actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping: return", "except in compliance with the License. You may obtain #", "self._vmutils = utilsfactory.get_vmutils() self._default_root_device = 'vda' self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS:", "0) # Attaching to the first slot slot = 0", "LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev = True _protocol = None _extra_connector_args", "while a volume # exported by it is about to", "= self._vmutils.get_vm_physical_disk_mapping( instance_name) for serial, vm_disk in vm_disk_mapping.items(): actual_disk_path =", "def attach_volumes(self, volumes, instance_name): for vol in volumes: self.attach_volume(vol['connection_info'], instance_name)", "= utilsfactory.get_vmutils() self._default_root_device = 'vda' self.volume_drivers = { constants.STORAGE_PROTOCOL_SMBFS: SMBFSVolumeDriver(),", "fix_instance_volume_disk_paths(self, instance_name, block_device_info): # Mapping containing the current disk paths", "nova import exception from nova.i18n import _, _LE, _LI, _LW", "self._vmutils.get_vm_scsi_controller( instance_name) slot = self._vmutils.get_free_controller_slot(ctrller_path) return ctrller_path, slot def set_disk_qos_specs(self,", "License. You may obtain # a copy of the License", "not self._conn: scan_attempts = CONF.hyperv.mounted_disk_query_retry_count scan_interval = CONF.hyperv.mounted_disk_query_retry_interval self._conn =", "use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return self._conn def connect_volume(self, connection_info): return", "vol['connection_info'] volume_driver = self._get_volume_driver(connection_info) volume_driver.connect_volume(connection_info) def get_disk_path_mapping(self, block_device_info): block_mapping =", "= self._connector.get_volume_paths(connection_info['data']) if not disk_paths: vol_id = connection_info['serial'] err_msg =", "class for Volume-related tasks \"\"\" def __init__(self): self._vmutils = utilsfactory.get_vmutils()", "disk_res_path def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info) serial", "*args, **kwargs): # We synchronize those operations based on the", "def attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): dev_info = self.connect_volume(connection_info) serial =", "driver.block_device_info_get_mapping(block_device_info) disk_path_mapping = {} for vol in block_mapping: connection_info =", "ANY KIND, either express or implied. See the # License", "# distributed under the License is distributed on an \"AS", "def disconnect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in mapping:", "synchronize those operations based on the share path in order", "== constants.CTRL_TYPE_IDE: # Find the IDE controller for the vm.", "utils from nova.virt import driver from nova.virt.hyperv import constants LOG", "(8 KB increments) # as IOPS allocation units. return (", "slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev: # We need to", "# Unless required by applicable law or agreed to in", "self.volume_drivers[driver_type] def attach_volumes(self, volumes, instance_name): for vol in volumes: self.attach_volume(vol['connection_info'],", "__init__(self): self._vmutils = utilsfactory.get_vmutils() self._default_root_device = 'vda' self.volume_drivers = {", "my_ip=CONF.my_block_storage_ip, multipath=CONF.hyperv.use_multipath_io, enforce_multipath=True, host=CONF.host) return conn def connect_volumes(self, block_device_info): mapping", "when the disk is attached to an instance. disk_number =", "unmounted while a volume # exported by it is about", "serial = connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name,", "in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type] def attach_volumes(self, volumes, instance_name):", "{'unsupported_specs': unsupported_specs, 'supported_qos_specs': supported_qos_specs}) LOG.warning(msg) class BaseVolumeDriver(object): _is_block_dev = True", "self._get_disk_res_path(dev_info['path']) ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus) if self._is_block_dev: # We", "return inner() return wrapper def _get_export_path(self, connection_info): return connection_info['data']['export'].replace('/', '\\\\')", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "= actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'], actual_disk_path) def get_volume_connector(self):", "Hyper-V volume driver \" \"does not support QoS. Ignoring QoS", "%(connection_info)s to %(instance_name)s\", {'connection_info': strutils.mask_dict_password(connection_info), 'instance_name': instance_name}) volume_driver = self._get_volume_driver(connection_info)", "self._conn = connector.InitiatorConnector.factory( protocol=self._protocol, root_helper=None, use_multipath=CONF.hyperv.use_multipath_io, device_scan_attempts=scan_attempts, device_scan_interval=scan_interval, **self._extra_connector_args) return", "import time from os_brick.initiator import connector from os_win import utilsfactory", "'%(unsupported_specs)s. ' 'Supported qos specs: %(supported_qos_specs)s') % {'unsupported_specs': unsupported_specs, 'supported_qos_specs':", "\" \"to instance %(instance_name)s. \"), {'connection_info': strutils.mask_dict_password( connection_info), 'instance_name': instance_name})", "in vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial] if vm_disk['mounted_disk_path'] != actual_disk_path: self._vmutils.set_disk_host_res(vm_disk['resource_path'],", "= self.get_disk_resource_path(connection_info) disk_path_mapping[disk_serial] = disk_path return disk_path_mapping def get_disk_resource_path(self, connection_info):", "def connect_volume(self, connection_info): return self._connector.connect_volume(connection_info['data']) def disconnect_volume(self, connection_info): self._connector.disconnect_volume(connection_info['data']) def", "connection_info): driver_type = connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers: raise", "= connection_info['serial'] disk_path = self._get_disk_res_path(dev_info['path']) ctrller_path, slot = self._get_disk_ctrl_and_slot(instance_name, disk_bus)", "attach_volume(self, connection_info, instance_name, disk_bus=constants.CTRL_TYPE_SCSI): tries_left = CONF.hyperv.volume_attach_retry_count + 1 while", "for serial, vm_disk in vm_disk_mapping.items(): actual_disk_path = actual_disk_mapping[serial] if vm_disk['mounted_disk_path']", "wrapper(inst, connection_info, *args, **kwargs): export_path = inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner():", "actual_disk_path) def get_volume_connector(self): # NOTE(lpetrut): the Windows os-brick connectors #", "__init__(self): self._conn = None self._diskutils = utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils()", "class VolumeOps(object): \"\"\"Management class for Volume-related tasks \"\"\" def __init__(self):", "_get_disk_ctrl_and_slot(self, instance_name, disk_bus): if disk_bus == constants.CTRL_TYPE_IDE: # Find the", "actual_disk_mapping = self.get_disk_path_mapping(block_device_info) if not actual_disk_mapping: return # Mapping containing", "inst._get_export_path(connection_info) @utils.synchronized(export_path) def inner(): return f(inst, connection_info, *args, **kwargs) return", "import driver from nova.virt.hyperv import constants LOG = logging.getLogger(__name__) CONF", "instance_name) def disconnect_volumes(self, block_device_info): mapping = driver.block_device_info_get_mapping(block_device_info) for vol in", "or {} if qos_specs: volume_driver.set_disk_qos_specs(connection_info, qos_specs) def disconnect_volume(self, connection_info): volume_driver", "disk_path_mapping = {} for vol in block_mapping: connection_info = vol['connection_info']", "None self._diskutils = utilsfactory.get_diskutils() self._vmutils = utilsfactory.get_vmutils() @property def _connector(self):", "path and the physical # disk path for each volume", "= driver.block_device_info_get_mapping(block_device_info) for vol in mapping: self.disconnect_volume(vol['connection_info']) def attach_volume(self, connection_info,", "disk_bus): if disk_bus == constants.CTRL_TYPE_IDE: # Find the IDE controller", "connection_info.get('driver_volume_type') if driver_type not in self.volume_drivers: raise exception.VolumeDriverNotFound(driver_type=driver_type) return self.volume_drivers[driver_type]", "or implied. See the # License for the specific language", "tasks \"\"\" def __init__(self): self._vmutils = utilsfactory.get_vmutils() self._default_root_device = 'vda'" ]
[ "banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show = ['ApplicantIncome', 'Credit_History']", "'mean') print(avg_loan_amount) loan_approved_se = banks[ (banks['Self_Employed'] == \"Yes\") & (banks['Loan_Status']", "# code starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include", "(banks['Loan_Status'] == \"Y\") ] loan_approved_nse = banks[ (banks['Self_Employed'] == \"No\")", "numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) banks = bank.drop(columns=['Loan_ID']) bank_mode", "from scipy.stats import mode # code starts here bank =", "# Check the mean value mean_values=loan_groupby.agg([np.mean]) print(mean_values) # code ends", "starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object')", "import numpy as np import pandas as pd from scipy.stats", "columns_to_show = ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the mean value", "banks = bank.drop(columns=['Loan_ID']) bank_mode = banks.mode() banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum())", "pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include", "= bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number')", "bank.select_dtypes(include = 'number') print(numerical_var) banks = bank.drop(columns=['Loan_ID']) bank_mode = banks.mode()", "aggfunc = 'mean') print(avg_loan_amount) loan_approved_se = banks[ (banks['Self_Employed'] == \"Yes\")", "* 100 percentage_nse = (len(loan_approved_nse) / 614) * 100 #", "Importing header files import numpy as np import pandas as", "# Importing header files import numpy as np import pandas", "as pd from scipy.stats import mode # code starts here", "/ 614) * 100 percentage_nse = (len(loan_approved_nse) / 614) *", "header files import numpy as np import pandas as pd", "print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) banks = bank.drop(columns=['Loan_ID'])", "100 # loan amount term loan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12", "banks.mode() banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks, index=['Gender', 'Married',", "print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount', aggfunc =", "(len(loan_approved_nse) / 614) * 100 # loan amount term loan_term", "bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var", "scipy.stats import mode # code starts here bank = pd.read_csv(path)", "(len(loan_approved_se) / 614) * 100 percentage_nse = (len(loan_approved_nse) / 614)", "# loan amount term loan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 )", "= bank.drop(columns=['Loan_ID']) bank_mode = banks.mode() banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount", "= banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount',", "= banks[ (banks['Self_Employed'] == \"No\") & (banks['Loan_Status'] == \"Y\") ]", "code starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include =", "loan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show =", "(banks['Self_Employed'] == \"Yes\") & (banks['Loan_Status'] == \"Y\") ] loan_approved_nse =", "pd from scipy.stats import mode # code starts here bank", "] loan_approved_nse = banks[ (banks['Self_Employed'] == \"No\") & (banks['Loan_Status'] ==", "100 percentage_nse = (len(loan_approved_nse) / 614) * 100 # loan", "banks[ (banks['Self_Employed'] == \"Yes\") & (banks['Loan_Status'] == \"Y\") ] loan_approved_nse", "= (len(loan_approved_se) / 614) * 100 percentage_nse = (len(loan_approved_nse) /", "= banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show = ['ApplicantIncome',", "\"Y\") ] percentage_se = (len(loan_approved_se) / 614) * 100 percentage_nse", "Check the mean value mean_values=loan_groupby.agg([np.mean]) print(mean_values) # code ends here", "amount term loan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term)", "-------------- # Importing header files import numpy as np import", "= banks[ (banks['Self_Employed'] == \"Yes\") & (banks['Loan_Status'] == \"Y\") ]", "= 'number') print(numerical_var) banks = bank.drop(columns=['Loan_ID']) bank_mode = banks.mode() banks", "== \"Yes\") & (banks['Loan_Status'] == \"Y\") ] loan_approved_nse = banks[", "numpy as np import pandas as pd from scipy.stats import", "bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var)", "614) * 100 # loan amount term loan_term = banks['Loan_Amount_Term'].apply(lambda", "= ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the mean value mean_values=loan_groupby.agg([np.mean])", "mode # code starts here bank = pd.read_csv(path) categorical_var =", "= (len(loan_approved_nse) / 614) * 100 # loan amount term", "'Self_Employed'], values='LoanAmount', aggfunc = 'mean') print(avg_loan_amount) loan_approved_se = banks[ (banks['Self_Employed']", "# -------------- # Importing header files import numpy as np", "= bank.select_dtypes(include = 'number') print(numerical_var) banks = bank.drop(columns=['Loan_ID']) bank_mode =", "pandas as pd from scipy.stats import mode # code starts", "bank_mode = banks.mode() banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks,", "\"Y\") ] loan_approved_nse = banks[ (banks['Self_Employed'] == \"No\") & (banks['Loan_Status']", "big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show = ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the", "loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the mean value mean_values=loan_groupby.agg([np.mean]) print(mean_values) # code", "/ 614) * 100 # loan amount term loan_term =", "as np import pandas as pd from scipy.stats import mode", "percentage_nse = (len(loan_approved_nse) / 614) * 100 # loan amount", "print(numerical_var) banks = bank.drop(columns=['Loan_ID']) bank_mode = banks.mode() banks = banks.fillna(bank_mode.iloc[0])", "\"Yes\") & (banks['Loan_Status'] == \"Y\") ] loan_approved_nse = banks[ (banks['Self_Employed']", "* 100 # loan amount term loan_term = banks['Loan_Amount_Term'].apply(lambda x:", "banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'],", "index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount', aggfunc = 'mean') print(avg_loan_amount) loan_approved_se =", "percentage_se = (len(loan_approved_se) / 614) * 100 percentage_nse = (len(loan_approved_nse)", "term loan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show", "614) * 100 percentage_nse = (len(loan_approved_nse) / 614) * 100", "& (banks['Loan_Status'] == \"Y\") ] loan_approved_nse = banks[ (banks['Self_Employed'] ==", "np import pandas as pd from scipy.stats import mode #", ") big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show = ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check", "banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount', aggfunc", "categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include =", "= banks.mode() banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount = pd.pivot_table(banks, index=['Gender',", "files import numpy as np import pandas as pd from", "& (banks['Loan_Status'] == \"Y\") ] percentage_se = (len(loan_approved_se) / 614)", "== \"Y\") ] loan_approved_nse = banks[ (banks['Self_Employed'] == \"No\") &", "\"No\") & (banks['Loan_Status'] == \"Y\") ] percentage_se = (len(loan_approved_se) /", "= 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) banks", "'number') print(numerical_var) banks = bank.drop(columns=['Loan_ID']) bank_mode = banks.mode() banks =", "import pandas as pd from scipy.stats import mode # code", "== \"No\") & (banks['Loan_Status'] == \"Y\") ] percentage_se = (len(loan_approved_se)", "(banks['Loan_Status'] == \"Y\") ] percentage_se = (len(loan_approved_se) / 614) *", "banks[ (banks['Self_Employed'] == \"No\") & (banks['Loan_Status'] == \"Y\") ] percentage_se", "avg_loan_amount = pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount', aggfunc = 'mean')", "= pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount', aggfunc = 'mean') print(avg_loan_amount)", "print(big_loan_term) columns_to_show = ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the mean", "loan_approved_nse = banks[ (banks['Self_Employed'] == \"No\") & (banks['Loan_Status'] == \"Y\")", "x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show = ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show]", "pd.pivot_table(banks, index=['Gender', 'Married', 'Self_Employed'], values='LoanAmount', aggfunc = 'mean') print(avg_loan_amount) loan_approved_se", "int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25]) print(big_loan_term) columns_to_show = ['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] #", "== \"Y\") ] percentage_se = (len(loan_approved_se) / 614) * 100", "loan amount term loan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12 ) big_loan_term=len(loan_term[loan_term>=25])", "= 'mean') print(avg_loan_amount) loan_approved_se = banks[ (banks['Self_Employed'] == \"Yes\") &", "bank.drop(columns=['Loan_ID']) bank_mode = banks.mode() banks = banks.fillna(bank_mode.iloc[0]) print(banks.isnull().sum()) avg_loan_amount =", "here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var)", "'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the mean value mean_values=loan_groupby.agg([np.mean]) print(mean_values) #", "import mode # code starts here bank = pd.read_csv(path) categorical_var", "['ApplicantIncome', 'Credit_History'] loan_groupby=banks.groupby(['Loan_Status'])[columns_to_show] # Check the mean value mean_values=loan_groupby.agg([np.mean]) print(mean_values)", "values='LoanAmount', aggfunc = 'mean') print(avg_loan_amount) loan_approved_se = banks[ (banks['Self_Employed'] ==", "= pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var =", "'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) banks =", "] percentage_se = (len(loan_approved_se) / 614) * 100 percentage_nse =", "print(avg_loan_amount) loan_approved_se = banks[ (banks['Self_Employed'] == \"Yes\") & (banks['Loan_Status'] ==", "(banks['Self_Employed'] == \"No\") & (banks['Loan_Status'] == \"Y\") ] percentage_se =", "'Married', 'Self_Employed'], values='LoanAmount', aggfunc = 'mean') print(avg_loan_amount) loan_approved_se = banks[", "loan_approved_se = banks[ (banks['Self_Employed'] == \"Yes\") & (banks['Loan_Status'] == \"Y\")" ]
[ "p.requires_grad, model.parameters()), 1) # update parameters cap_train_loss = cap_loss.item() cms_train_loss", "%.6f, cms_train_loss = %.6f,' ' current step = %d, current", "opt['att_max_len'] # model initialization. from model.S2VTModel import S2VTModel model =", "VideoDataset from model.transformer.Optim import ScheduledOptim def train(loader, model, optimizer, opt,", "= non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item() cap_loss", "model.parameters()), betas=(0.9, 0.98), eps=1e-09), 512, opt['warm_up_steps']) # note: though we", "or stronger video feature # may lead performance boost, however", "cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show the intermediate generations", "opt['show_predict']: cap_pr, cap_gt = show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab, caption=True) cms_pr,", "+= 1 if iteration % opt['print_loss_every'] ==0: print('iter %d (epoch", "from previous checkpoint if indicated if opt['load_checkpoint'] and opt['resume']: cap_state_dict", "-0.5), # grid search indicates different LR may improve the", "model initialization. from model.S2VTModel import S2VTModel model = S2VTModel( dataset.get_cap_vocab_size(),", "S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) #", "in model_parameters]) print('number of learnable parameters are {}'.format(params)) if opt['cuda']:", "opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path) print('model saved to %s'", "opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if not os.path.exists(dir): os.makedirs(dir) #", "as f: f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n') # log file directory", "optimizer = ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09), 512,", "Scropt for V2C captioning task. ''' __author__ = '<NAME>' import", "as np from opts import * from utils.utils import *", "cap_labels, cap_pos, cms_labels, cms_pos) cap_probs, _, cms_probs, _ = model(fc_feats,", "% (cms_pr, cms_gt)) f.write('\\n') if epoch % opt['save_checkpoint_every'] == 0:", "checkpoint if indicated if opt['load_checkpoint'] and opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint'])", "= data['int_labels'] elif opt['cms'] == 'eff': cms_labels = data['eff_labels'] else:", "loader: torch.cuda.synchronize() if opt['cms'] == 'int': cms_labels = data['int_labels'] elif", "search indicates different LR may improve the results. opt['init_lr'] =", "cap_train_loss, cms_train_loss)) f.write('\\n %s \\n %s' % (cap_pr, cap_gt)) f.write('\\n", "rate as np.power(d_model, -0.5), # grid search indicates different LR", "% (epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt): # load and define", "not os.path.exists(dir): os.makedirs(dir) # save the model snapshot to local", "cms_labels[:, 1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item() cap_loss /= n_word cms_loss /=", "== 'int': cms_labels = data['int_labels'] elif opt['cms'] == 'eff': cms_labels", "video feature # may lead performance boost, however is not", "f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss, cms_train_loss))", "cap_vocab, caption=True) cms_pr, cms_gt = show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab, caption=False)", "betas=(0.9, 0.98), eps=1e-09), 512, opt['warm_up_steps']) # note: though we set", "model.cuda() # resume from previous checkpoint if indicated if opt['load_checkpoint']", "= os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'],", "optimizer, opt, cap_vocab, cms_vocab): model.train() for epoch in range(opt['epochs']): iteration", "cms_gt = show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab, caption=False) print(' \\n') with", "dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number", "not necessary in newer PyTorch version or on single GPU.", "%d (epoch %d), cap_train_loss = %.6f, cms_train_loss = %.6f,' '", "opt['cms'] == 'eff': cms_labels = data['eff_labels'] else: cms_labels = data['att_labels']", "resume from previous checkpoint if indicated if opt['load_checkpoint'] and opt['resume']:", "x: x.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09), 512, opt['warm_up_steps']) # note:", "opt['warm_up_steps']) # note: though we set the init learning rate", "numpy as np from opts import * from utils.utils import", "in range(opt['epochs']): iteration = 0 for data in loader: torch.cuda.synchronize()", "like SELF-CRIT, different loss weights or stronger video feature #", "for V2C captioning task. ''' __author__ = '<NAME>' import os", "f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss, cms_train_loss)) f.write('\\n", "training objective, # advanced loss func. like SELF-CRIT, different loss", "torch.cuda.synchronize() iteration += 1 if iteration % opt['print_loss_every'] ==0: print('iter", "define dataloader dataset = VideoDataset(opt, 'train') dataloader = DataLoader(dataset, batch_size=opt['batch_size'],", "iteration = 0 for data in loader: torch.cuda.synchronize() if opt['cms']", "else: cms_labels = data['att_labels'] if opt['cuda']: fc_feats = data['fc_feats'].cuda() cap_labels", "= 0 for data in loader: torch.cuda.synchronize() if opt['cms'] ==", "utils.utils import * import torch.optim as optim from model.Model import", "the init learning rate as np.power(d_model, -0.5), # grid search", "p: p.requires_grad, model.parameters()), 1) # update parameters cap_train_loss = cap_loss.item()", "% (epoch, cap_train_loss, cms_train_loss)) f.write('\\n %s \\n %s' % (cap_pr,", "0: # save the checkpoint model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'],", "\\n %s' % (cms_pr, cms_gt)) f.write('\\n') if epoch % opt['save_checkpoint_every']", "% model_path) with open(opt['model_info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f,", "if opt['cuda']: torch.cuda.synchronize() iteration += 1 if iteration % opt['print_loss_every']", "= cap_loss.item() cms_train_loss = cms_loss.item() # multi-gpu case, not necessary", "opt['cms'] == 'int': cms_labels = data['int_labels'] elif opt['cms'] == 'eff':", "# log file directory opt['output_dir'] = dir opt['info_path'] = info_path", "cms_labels = data['int_labels'] elif opt['cms'] == 'eff': cms_labels = data['eff_labels']", "= %d, current lr = %.3E, cap_acc = %.3f, cms_acc", "cms_text_length = opt['att_max_len'] # model initialization. from model.S2VTModel import S2VTModel", "# save the model snapshot to local info_path = os.path.join(dir,", "''' __author__ = '<NAME>' import os import numpy as np", "number of parameters model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params", "optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show the intermediate generations if opt['show_predict']:", "+ cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()), 1) #", "show the intermediate generations if opt['show_predict']: cap_pr, cap_gt = show_prediction(cap_probs,", "initialization. from model.S2VTModel import S2VTModel model = S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(),", "'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if not", "'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch,", "intermediate generations if opt['show_predict']: cap_pr, cap_gt = show_prediction(cap_probs, cap_labels[:, :-1],", "= dir opt['info_path'] = info_path opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader,", "= dataset.get_cap_vocab_size() if opt['cms'] == 'int': cms_text_length = opt['int_max_len'] elif", "'iteration_info_log.log') print('model architecture saved to {} \\n {}'.format(info_path, str(model))) with", "print('model architecture saved to {} \\n {}'.format(info_path, str(model))) with open(info_path,", "in newer PyTorch version or on single GPU. if opt['cuda']:", "cms_labels[:, 1:], smoothing=True) # compute the token prediction Acc. non_pad_mask", "# number of parameters model_parameters = filter(lambda p: p.requires_grad, model.parameters())", "if opt['cuda']: fc_feats = data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda() cms_labels =", "= cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True) # compute the token", "opt['save_checkpoint_every'] == 0: # save the checkpoint model_path = os.path.join(opt['output_dir'],", "opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path) print('model saved to %s' %", "cap_acc = %.3f, cms_acc = %.3f' % (iteration, epoch, cap_train_loss,", "for epoch in range(opt['epochs']): iteration = 0 for data in", "captioning task. ''' __author__ = '<NAME>' import os import numpy", "open(info_path, 'a') as f: f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n') # log", "1) # update parameters cap_train_loss = cap_loss.item() cms_train_loss = cms_loss.item()", "round(optimizer.init_lr, 3) # create checkpoint output directory dir = os.path.join(opt['checkpoint_path'],", "cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True) cms_loss, cms_n_correct", "as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss/n_word,", "opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number of parameters model_parameters = filter(lambda", "# cap_probs, cms_probs = model(fc_feats, cap_labels, cap_pos, cms_labels, cms_pos) cap_probs,", "from model.Model import Model from torch.utils.data import DataLoader from utils.dataloader", "prediction Acc. non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item() cms_non_pad_mask", "if opt['cms'] == 'int': cms_text_length = opt['int_max_len'] elif opt['cms'] ==", "cap_loss /= n_word cms_loss /= n_word loss = cms_loss +", "import Model from torch.utils.data import DataLoader from utils.dataloader import VideoDataset", "cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt):", "if opt['show_predict']: cap_pr, cap_gt = show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab, caption=True)", "feature # may lead performance boost, however is not the", "model, optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__ == '__main__': opt", "(epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt): # load and define dataloader", "# create checkpoint output directory dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'],", "data['eff_labels'] else: cms_labels = data['att_labels'] if opt['cuda']: fc_feats = data['fc_feats'].cuda()", "non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:,", "cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True) cms_loss, cms_n_correct =", "opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint']) model_dict = model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer", "we set the init learning rate as np.power(d_model, -0.5), #", "caption=False) print(' \\n') with open(opt['info_path'], 'a') as f: f.write('model_%d, cap_loss:", "just used most naive cross-entropy as training objective, # advanced", "3) # create checkpoint output directory dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}'", "V2C captioning task. ''' __author__ = '<NAME>' import os import", "opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number of parameters model_parameters =", "cms_probs, _ = model(fc_feats, cap_labels, cms_labels) # note: currently we", "(iteration, epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show", "# grid search indicates different LR may improve the results.", "opt['load_checkpoint'] and opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint']) model_dict = model.state_dict() model_dict.update(cap_state_dict)", "from opts import * from utils.utils import * import torch.optim", "# note: currently we just used most naive cross-entropy as", "cap_train_loss = cap_loss.item() cms_train_loss = cms_loss.item() # multi-gpu case, not", "GPU. if opt['cuda']: torch.cuda.synchronize() iteration += 1 if iteration %", "f.write('\\n') # log file directory opt['output_dir'] = dir opt['info_path'] =", "cms_train_loss/n_word)) def main(opt): # load and define dataloader dataset =", "f.write('\\n') if epoch % opt['save_checkpoint_every'] == 0: # save the", "most naive cross-entropy as training objective, # advanced loss func.", "ScheduledOptim def train(loader, model, optimizer, opt, cap_vocab, cms_vocab): model.train() for", "log file directory opt['output_dir'] = dir opt['info_path'] = info_path opt['model_info_path']", "model snapshot to local info_path = os.path.join(dir, 'iteration_info_log.log') print('model architecture", "model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09),", "f.write('\\n %s \\n %s' % (cms_pr, cms_gt)) f.write('\\n') if epoch", "% (iteration, epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) #", "create checkpoint output directory dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'],", "= data['eff_labels'] else: cms_labels = data['att_labels'] if opt['cuda']: fc_feats =", "model_path) with open(opt['model_info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss:", "cms_loss + cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()), 1)", "of this work. cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:],", "= cap_labels[:, 1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD)", "cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item() cap_loss /= n_word", "cms_acc = %.3f' % (iteration, epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'],", "= %.6f, cms_train_loss = %.6f,' ' current step = %d,", "%.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt): #", "cms_labels) # note: currently we just used most naive cross-entropy", "\\n %s' % (cap_pr, cap_gt)) f.write('\\n %s \\n %s' %", "== 'eff': cms_text_length = opt['eff_max_len'] else: cms_text_length = opt['att_max_len'] #", "_ = model(fc_feats, cap_labels, cms_labels) # note: currently we just", "if not os.path.exists(dir): os.makedirs(dir) # save the model snapshot to", "%.6f,' ' current step = %d, current lr = %.3E,", "elif opt['cms'] == 'eff': cms_labels = data['eff_labels'] else: cms_labels =", "elif opt['cms'] == 'eff': cms_text_length = opt['eff_max_len'] else: cms_text_length =", "%.6f\\n' % (epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt): # load and", "1 if iteration % opt['print_loss_every'] ==0: print('iter %d (epoch %d),", "the goal of this work. cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]),", "= data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda() cms_labels = cms_labels.cuda() optimizer.zero_grad() #", "cms_vocab): model.train() for epoch in range(opt['epochs']): iteration = 0 for", "print('number of learnable parameters are {}'.format(params)) if opt['cuda']: model =", "and opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint']) model_dict = model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict)", "cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()), 1) # update", "1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item() cap_loss /= n_word cms_loss /= n_word", "cap_gt)) f.write('\\n %s \\n %s' % (cms_pr, cms_gt)) f.write('\\n') if", "improve the results. opt['init_lr'] = round(optimizer.init_lr, 3) # create checkpoint", "cap_labels[:, 1:], smoothing=True) cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:],", "goal of this work. cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:,", "cms_text_length = opt['int_max_len'] elif opt['cms'] == 'eff': cms_text_length = opt['eff_max_len']", "cms_labels.cuda() optimizer.zero_grad() # cap_probs, cms_probs = model(fc_feats, cap_labels, cap_pos, cms_labels,", "if epoch % opt['save_checkpoint_every'] == 0: # save the checkpoint", "the results. opt['init_lr'] = round(optimizer.init_lr, 3) # create checkpoint output", "f.write('\\n %s \\n %s' % (cap_pr, cap_gt)) f.write('\\n %s \\n", "architecture saved to {} \\n {}'.format(info_path, str(model))) with open(info_path, 'a')", "cap_probs, _, cms_probs, _ = model(fc_feats, cap_labels, cms_labels) # note:", "torch.load(opt['load_checkpoint']) model_dict = model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda x:", "{} \\n {}'.format(info_path, str(model))) with open(info_path, 'a') as f: f.write(str(model))", "cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True) # compute the", "(epoch, cap_train_loss, cms_train_loss)) f.write('\\n %s \\n %s' % (cap_pr, cap_gt))", "f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss/n_word, cms_train_loss/n_word))", "model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), betas=(0.9,", "%s' % (cms_pr, cms_gt)) f.write('\\n') if epoch % opt['save_checkpoint_every'] ==", "optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show the intermediate generations if", "opts import * from utils.utils import * import torch.optim as", "cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True) cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]),", "== 'eff': cms_labels = data['eff_labels'] else: cms_labels = data['att_labels'] if", "0 for data in loader: torch.cuda.synchronize() if opt['cms'] == 'int':", "= cms_labels[:, 1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item() cap_loss /= n_word cms_loss", "batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if opt['cms']", "import os import numpy as np from opts import *", "%s \\n %s' % (cap_pr, cap_gt)) f.write('\\n %s \\n %s'", "if opt['load_checkpoint'] and opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint']) model_dict = model.state_dict()", "= show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab, caption=False) print(' \\n') with open(opt['info_path'],", "os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model, optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__", "generations if opt['show_predict']: cap_pr, cap_gt = show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab,", "results. opt['init_lr'] = round(optimizer.init_lr, 3) # create checkpoint output directory", "opt['init_lr'] = round(optimizer.init_lr, 3) # create checkpoint output directory dir", "dataset = VideoDataset(opt, 'train') dataloader = DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size']", "cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt): # load and define dataloader dataset", "for p in model_parameters]) print('number of learnable parameters are {}'.format(params))", "of parameters model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params =", "model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) print('number of", "compute the token prediction Acc. non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD) n_word", "Model from torch.utils.data import DataLoader from utils.dataloader import VideoDataset from", "snapshot to local info_path = os.path.join(dir, 'iteration_info_log.log') print('model architecture saved", "info_path = os.path.join(dir, 'iteration_info_log.log') print('model architecture saved to {} \\n", "caption=True) cms_pr, cms_gt = show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab, caption=False) print('", "= cms_labels.cuda() optimizer.zero_grad() # cap_probs, cms_probs = model(fc_feats, cap_labels, cap_pos,", "model(fc_feats, cap_labels, cms_labels) # note: currently we just used most", "cms_labels[:, :-1], cms_vocab, caption=False) print(' \\n') with open(opt['info_path'], 'a') as", "dataloader dataset = VideoDataset(opt, 'train') dataloader = DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True)", "os.path.join(dir, 'iteration_info_log.log') print('model architecture saved to {} \\n {}'.format(info_path, str(model)))", "optim from model.Model import Model from torch.utils.data import DataLoader from", "dataset.get_cms_vocab()) if __name__ == '__main__': opt = parse_opt() opt =", "the intermediate generations if opt['show_predict']: cap_pr, cap_gt = show_prediction(cap_probs, cap_labels[:,", "opt['dim_model'], opt['rnn_layer'])) if not os.path.exists(dir): os.makedirs(dir) # save the model", "% opt['print_loss_every'] ==0: print('iter %d (epoch %d), cap_train_loss = %.6f,", "cms_pr, cms_gt = show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab, caption=False) print(' \\n')", "directory opt['output_dir'] = dir opt['info_path'] = info_path opt['model_info_path'] = os.path.join(opt['output_dir'],", "opt, cap_vocab, cms_vocab): model.train() for epoch in range(opt['epochs']): iteration =", "single GPU. if opt['cuda']: torch.cuda.synchronize() iteration += 1 if iteration", "filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in", "opt['eff_max_len'] else: cms_text_length = opt['att_max_len'] # model initialization. from model.S2VTModel", "{}'.format(info_path, str(model))) with open(info_path, 'a') as f: f.write(str(model)) f.write('\\n') f.write(str(params))", "= model(fc_feats, cap_labels, cms_labels) # note: currently we just used", "to local info_path = os.path.join(dir, 'iteration_info_log.log') print('model architecture saved to", "'<NAME>' import os import numpy as np from opts import", "objective, # advanced loss func. like SELF-CRIT, different loss weights", "%s' % model_path) with open(opt['model_info_path'], 'a') as f: f.write('model_%d, cap_loss:", "iteration % opt['print_loss_every'] ==0: print('iter %d (epoch %d), cap_train_loss =", "with open(opt['model_info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n'", "cap_labels, cms_labels) # note: currently we just used most naive", "cap_pos, cms_labels, cms_pos) cap_probs, _, cms_probs, _ = model(fc_feats, cap_labels,", "iteration += 1 if iteration % opt['print_loss_every'] ==0: print('iter %d", "with open(opt['info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n'", "stronger video feature # may lead performance boost, however is", "cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True) # compute the token prediction Acc.", "as training objective, # advanced loss func. like SELF-CRIT, different", "train(loader, model, optimizer, opt, cap_vocab, cms_vocab): model.train() for epoch in", "(cms_pr, cms_gt)) f.write('\\n') if epoch % opt['save_checkpoint_every'] == 0: #", "work. cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True) cms_loss,", "opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if opt['cms'] == 'int':", "info_path opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model, optimizer, opt, dataset.get_cap_vocab(),", ".format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path)", "= '<NAME>' import os import numpy as np from opts", "epoch in range(opt['epochs']): iteration = 0 for data in loader:", "S2VTModel model = S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"],", "opt['cuda']: torch.cuda.synchronize() iteration += 1 if iteration % opt['print_loss_every'] ==0:", "x.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09), 512, opt['warm_up_steps']) # note: though", "= ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09), 512, opt['warm_up_steps'])", "VideoDataset(opt, 'train') dataloader = DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size()", "model = model.cuda() # resume from previous checkpoint if indicated", "= %.3E, cap_acc = %.3f, cms_acc = %.3f' % (iteration,", "cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number of parameters model_parameters", "Acc. non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item() cms_non_pad_mask =", "model_parameters]) print('number of learnable parameters are {}'.format(params)) if opt['cuda']: model", "cms_probs = model(fc_feats, cap_labels, cap_pos, cms_labels, cms_pos) cap_probs, _, cms_probs,", "the checkpoint model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'],", "% (cap_pr, cap_gt)) f.write('\\n %s \\n %s' % (cms_pr, cms_gt))", "load and define dataloader dataset = VideoDataset(opt, 'train') dataloader =", "= torch.load(opt['load_checkpoint']) model_dict = model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda", "performance boost, however is not the goal of this work.", "import * from utils.utils import * import torch.optim as optim", "optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__ == '__main__': opt =", "opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__ == '__main__': opt = parse_opt()", "cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True) # compute", "checkpoint model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'],", "'train') dataloader = DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size']", "= os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model, optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if", "different LR may improve the results. opt['init_lr'] = round(optimizer.init_lr, 3)", "cap_vocab, cms_vocab): model.train() for epoch in range(opt['epochs']): iteration = 0", "open(opt['model_info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' %", "opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path) print('model saved", "torch.save(model.state_dict(), model_path) print('model saved to %s' % model_path) with open(opt['model_info_path'],", "= filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p", "= dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if opt['cms'] == 'int': cms_text_length", "sum([np.prod(p.size()) for p in model_parameters]) print('number of learnable parameters are", "model.parameters()), 1) # update parameters cap_train_loss = cap_loss.item() cms_train_loss =", "advanced loss func. like SELF-CRIT, different loss weights or stronger", "torch.optim as optim from model.Model import Model from torch.utils.data import", "directory dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'],", "= cms_non_pad_mask.sum().item() cap_loss /= n_word cms_loss /= n_word loss =", "as np.power(d_model, -0.5), # grid search indicates different LR may", "SELF-CRIT, different loss weights or stronger video feature # may", "# show the intermediate generations if opt['show_predict']: cap_pr, cap_gt =", "though we set the init learning rate as np.power(d_model, -0.5),", "indicated if opt['load_checkpoint'] and opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint']) model_dict =", "n_word = non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item()", "%s \\n %s' % (cms_pr, cms_gt)) f.write('\\n') if epoch %", "(epoch %d), cap_train_loss = %.6f, cms_train_loss = %.6f,' ' current", "dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'],", "%d), cap_train_loss = %.6f, cms_train_loss = %.6f,' ' current step", "' current step = %d, current lr = %.3E, cap_acc", "%.3f, cms_acc = %.3f' % (iteration, epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps,", "data['cap_labels'].cuda() cms_labels = cms_labels.cuda() optimizer.zero_grad() # cap_probs, cms_probs = model(fc_feats,", "__name__ == '__main__': opt = parse_opt() opt = vars(opt) main(opt)", "model.Model import Model from torch.utils.data import DataLoader from utils.dataloader import", "opt['print_loss_every'] ==0: print('iter %d (epoch %d), cap_train_loss = %.6f, cms_train_loss", "parameters model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size())", "dataset.get_cap_vocab_size() if opt['cms'] == 'int': cms_text_length = opt['int_max_len'] elif opt['cms']", "'int': cms_text_length = opt['int_max_len'] elif opt['cms'] == 'eff': cms_text_length =", "may improve the results. opt['init_lr'] = round(optimizer.init_lr, 3) # create", "os import numpy as np from opts import * from", "# may lead performance boost, however is not the goal", "%.3E, cap_acc = %.3f, cms_acc = %.3f' % (iteration, epoch,", "{}'.format(params)) if opt['cuda']: model = model.cuda() # resume from previous", "open(opt['info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' %", "not the goal of this work. cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1,", "model = S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'],", "n_word loss = cms_loss + cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p:", "import * import torch.optim as optim from model.Model import Model", "update parameters cap_train_loss = cap_loss.item() cms_train_loss = cms_loss.item() # multi-gpu", "version or on single GPU. if opt['cuda']: torch.cuda.synchronize() iteration +=", "'checkpoint_loss_log.log') train(dataloader, model, optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__ ==", "import VideoDataset from model.transformer.Optim import ScheduledOptim def train(loader, model, optimizer,", "cms_labels = cms_labels.cuda() optimizer.zero_grad() # cap_probs, cms_probs = model(fc_feats, cap_labels,", "model.transformer.Optim import ScheduledOptim def train(loader, model, optimizer, opt, cap_vocab, cms_vocab):", "DataLoader from utils.dataloader import VideoDataset from model.transformer.Optim import ScheduledOptim def", "from utils.dataloader import VideoDataset from model.transformer.Optim import ScheduledOptim def train(loader,", ".format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if not os.path.exists(dir):", "cap_labels = data['cap_labels'].cuda() cms_labels = cms_labels.cuda() optimizer.zero_grad() # cap_probs, cms_probs", "torch.utils.data import DataLoader from utils.dataloader import VideoDataset from model.transformer.Optim import", "print(' \\n') with open(opt['info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f,", "main(opt): # load and define dataloader dataset = VideoDataset(opt, 'train')", "show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab, caption=True) cms_pr, cms_gt = show_prediction(cms_probs, cms_labels[:,", "cms_train_loss = cms_loss.item() # multi-gpu case, not necessary in newer", "# load and define dataloader dataset = VideoDataset(opt, 'train') dataloader", "opt['cuda']: fc_feats = data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda() cms_labels = cms_labels.cuda()", "__author__ = '<NAME>' import os import numpy as np from", "# model initialization. from model.S2VTModel import S2VTModel model = S2VTModel(", "the model snapshot to local info_path = os.path.join(dir, 'iteration_info_log.log') print('model", "= cms_loss.item() # multi-gpu case, not necessary in newer PyTorch", "to %s' % model_path) with open(opt['model_info_path'], 'a') as f: f.write('model_%d,", "parameters are {}'.format(params)) if opt['cuda']: model = model.cuda() # resume", "f.write('\\n') f.write(str(params)) f.write('\\n') # log file directory opt['output_dir'] = dir", "cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show the intermediate", "= cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True) cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1,", "current step = %d, current lr = %.3E, cap_acc =", "'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(),", "cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss, cms_train_loss)) f.write('\\n %s", "cms_labels = data['eff_labels'] else: cms_labels = data['att_labels'] if opt['cuda']: fc_feats", "cms_loss: %.6f\\n' % (epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def main(opt): # load", "opt['output_dir'] = dir opt['info_path'] = info_path opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log')", "and define dataloader dataset = VideoDataset(opt, 'train') dataloader = DataLoader(dataset,", "= DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size()", "opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if not os.path.exists(dir): os.makedirs(dir)", "grid search indicates different LR may improve the results. opt['init_lr']", "% opt['save_checkpoint_every'] == 0: # save the checkpoint model_path =", "cap_labels[:, 1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD) cms_n_word", "opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if not os.path.exists(dir): os.makedirs(dir) # save", "= round(optimizer.init_lr, 3) # create checkpoint output directory dir =", "currently we just used most naive cross-entropy as training objective,", "may lead performance boost, however is not the goal of", "* from utils.utils import * import torch.optim as optim from", "opt['cms'] == 'int': cms_text_length = opt['int_max_len'] elif opt['cms'] == 'eff':", "%s' % (cap_pr, cap_gt)) f.write('\\n %s \\n %s' % (cms_pr,", "512, opt['warm_up_steps']) # note: though we set the init learning", "f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n') # log file directory opt['output_dir'] =", "= info_path opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model, optimizer, opt,", "= show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab, caption=True) cms_pr, cms_gt = show_prediction(cms_probs,", "''' Training Scropt for V2C captioning task. ''' __author__ =", "= S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer'])", "'int': cms_labels = data['int_labels'] elif opt['cms'] == 'eff': cms_labels =", "if __name__ == '__main__': opt = parse_opt() opt = vars(opt)", "== 0: # save the checkpoint model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth'", "np from opts import * from utils.utils import * import", "model.S2VTModel import S2VTModel model = S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length,", "epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show the", "previous checkpoint if indicated if opt['load_checkpoint'] and opt['resume']: cap_state_dict =", "used most naive cross-entropy as training objective, # advanced loss", "model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'],", "PyTorch version or on single GPU. if opt['cuda']: torch.cuda.synchronize() iteration", "==0: print('iter %d (epoch %d), cap_train_loss = %.6f, cms_train_loss =", "opt['cms'] == 'eff': cms_text_length = opt['eff_max_len'] else: cms_text_length = opt['att_max_len']", "# update parameters cap_train_loss = cap_loss.item() cms_train_loss = cms_loss.item() #", "'a') as f: f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n') # log file", "case, not necessary in newer PyTorch version or on single", "for data in loader: torch.cuda.synchronize() if opt['cms'] == 'int': cms_labels", "naive cross-entropy as training objective, # advanced loss func. like", "data['att_labels'] if opt['cuda']: fc_feats = data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda() cms_labels", "p in model_parameters]) print('number of learnable parameters are {}'.format(params)) if", "lr = %.3E, cap_acc = %.3f, cms_acc = %.3f' %", "shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if opt['cms'] ==", "import DataLoader from utils.dataloader import VideoDataset from model.transformer.Optim import ScheduledOptim", "the token prediction Acc. non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD) n_word =", "Training Scropt for V2C captioning task. ''' __author__ = '<NAME>'", "model(fc_feats, cap_labels, cap_pos, cms_labels, cms_pos) cap_probs, _, cms_probs, _ =", "note: currently we just used most naive cross-entropy as training", "import ScheduledOptim def train(loader, model, optimizer, opt, cap_vocab, cms_vocab): model.train()", "# compute the token prediction Acc. non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD)", "init learning rate as np.power(d_model, -0.5), # grid search indicates", "= data['cap_labels'].cuda() cms_labels = cms_labels.cuda() optimizer.zero_grad() # cap_probs, cms_probs =", "cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True) cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:,", "= opt['int_max_len'] elif opt['cms'] == 'eff': cms_text_length = opt['eff_max_len'] else:", "ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09), 512, opt['warm_up_steps']) #", "(cap_pr, cap_gt)) f.write('\\n %s \\n %s' % (cms_pr, cms_gt)) f.write('\\n')", "cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True) # compute the token prediction", "model_path) print('model saved to %s' % model_path) with open(opt['model_info_path'], 'a')", "newer PyTorch version or on single GPU. if opt['cuda']: torch.cuda.synchronize()", "= %.6f,' ' current step = %d, current lr =", "os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if", "f: f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n') # log file directory opt['output_dir']", "%.3f' % (iteration, epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word, cms_n_correct/cms_n_word))", "model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for", "set the init learning rate as np.power(d_model, -0.5), # grid", "\\n {}'.format(info_path, str(model))) with open(info_path, 'a') as f: f.write(str(model)) f.write('\\n')", "<filename>others/train_RNN.py ''' Training Scropt for V2C captioning task. ''' __author__", "= cms_loss + cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()),", "cap_labels[:, :-1], cap_vocab, caption=True) cms_pr, cms_gt = show_prediction(cms_probs, cms_labels[:, :-1],", "print('iter %d (epoch %d), cap_train_loss = %.6f, cms_train_loss = %.6f,'", "cms_train_loss)) f.write('\\n %s \\n %s' % (cap_pr, cap_gt)) f.write('\\n %s", "save the checkpoint model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'],", "cms_train_loss = %.6f,' ' current step = %d, current lr", "= os.path.join(dir, 'iteration_info_log.log') print('model architecture saved to {} \\n {}'.format(info_path,", "cap_pr, cap_gt = show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab, caption=True) cms_pr, cms_gt", "as f: f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss,", "%.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss, cms_train_loss)) f.write('\\n %s \\n", "= %.3f, cms_acc = %.3f' % (iteration, epoch, cap_train_loss, cms_train_loss,", "model_dict = model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad,", "cap_gt = show_prediction(cap_probs, cap_labels[:, :-1], cap_vocab, caption=True) cms_pr, cms_gt =", "if opt['cms'] == 'int': cms_labels = data['int_labels'] elif opt['cms'] ==", "1:], smoothing=True) # compute the token prediction Acc. non_pad_mask =", "file directory opt['output_dir'] = dir opt['info_path'] = info_path opt['model_info_path'] =", "show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab, caption=False) print(' \\n') with open(opt['info_path'], 'a')", "p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) print('number", "loss = cms_loss + cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad,", "cap_probs, cms_probs = model(fc_feats, cap_labels, cap_pos, cms_labels, cms_pos) cap_probs, _,", "== 'int': cms_text_length = opt['int_max_len'] elif opt['cms'] == 'eff': cms_text_length", "opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number of parameters", "cap_loss.item() cms_train_loss = cms_loss.item() # multi-gpu case, not necessary in", "/= n_word cms_loss /= n_word loss = cms_loss + cap_loss", "saved to %s' % model_path) with open(opt['model_info_path'], 'a') as f:", "cms_gt)) f.write('\\n') if epoch % opt['save_checkpoint_every'] == 0: # save", "os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch))", "lead performance boost, however is not the goal of this", ":-1], cap_vocab, caption=True) cms_pr, cms_gt = show_prediction(cms_probs, cms_labels[:, :-1], cms_vocab,", "os.path.exists(dir): os.makedirs(dir) # save the model snapshot to local info_path", "cms_loss.item() # multi-gpu case, not necessary in newer PyTorch version", "%d, current lr = %.3E, cap_acc = %.3f, cms_acc =", "are {}'.format(params)) if opt['cuda']: model = model.cuda() # resume from", "cms_n_word = cms_non_pad_mask.sum().item() cap_loss /= n_word cms_loss /= n_word loss", "local info_path = os.path.join(dir, 'iteration_info_log.log') print('model architecture saved to {}", "from utils.utils import * import torch.optim as optim from model.Model", "current lr = %.3E, cap_acc = %.3f, cms_acc = %.3f'", "cms_text_length = opt['eff_max_len'] else: cms_text_length = opt['att_max_len'] # model initialization.", "dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__ == '__main__': opt = parse_opt() opt", "as optim from model.Model import Model from torch.utils.data import DataLoader", "data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda() cms_labels = cms_labels.cuda() optimizer.zero_grad() # cap_probs,", "os.makedirs(dir) # save the model snapshot to local info_path =", "dir opt['info_path'] = info_path opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model,", "model, optimizer, opt, cap_vocab, cms_vocab): model.train() for epoch in range(opt['epochs']):", "def train(loader, model, optimizer, opt, cap_vocab, cms_vocab): model.train() for epoch", "from torch.utils.data import DataLoader from utils.dataloader import VideoDataset from model.transformer.Optim", "loss weights or stronger video feature # may lead performance", "# multi-gpu case, not necessary in newer PyTorch version or", "opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model, optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab())", "fc_feats = data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda() cms_labels = cms_labels.cuda() optimizer.zero_grad()", "params = sum([np.prod(p.size()) for p in model_parameters]) print('number of learnable", "smoothing=True) cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True) #", "in loader: torch.cuda.synchronize() if opt['cms'] == 'int': cms_labels = data['int_labels']", "non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD) cms_n_word = cms_non_pad_mask.sum().item() cap_loss /=", "from model.transformer.Optim import ScheduledOptim def train(loader, model, optimizer, opt, cap_vocab,", "= %.3f' % (iteration, epoch, cap_train_loss, cms_train_loss, optimizer.n_current_steps, optimizer._optimizer.param_groups[0]['lr'], cap_n_correct/n_word,", "cms_loss /= n_word loss = cms_loss + cap_loss loss.backward() optimizer.step_and_update_lr()", "loss func. like SELF-CRIT, different loss weights or stronger video", "import S2VTModel model = S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"],", "we just used most naive cross-entropy as training objective, #", "opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if opt['cms'] == 'int': cms_text_length = opt['int_max_len']", "smoothing=True) # compute the token prediction Acc. non_pad_mask = cap_labels[:,", "checkpoint output directory dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'],", "np.power(d_model, -0.5), # grid search indicates different LR may improve", "or on single GPU. if opt['cuda']: torch.cuda.synchronize() iteration += 1", "optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()), 1) # update parameters cap_train_loss", "opt['info_path'] = info_path opt['model_info_path'] = os.path.join(opt['output_dir'], 'checkpoint_loss_log.log') train(dataloader, model, optimizer,", "= opt['att_max_len'] # model initialization. from model.S2VTModel import S2VTModel model", "1:], smoothing=True) cms_loss, cms_n_correct = cal_performance(cms_probs.view(-1, cms_probs.shape[-1]), cms_labels[:, 1:], smoothing=True)", "import numpy as np from opts import * from utils.utils", "f.write(str(params)) f.write('\\n') # log file directory opt['output_dir'] = dir opt['info_path']", "save the model snapshot to local info_path = os.path.join(dir, 'iteration_info_log.log')", "= model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()),", "'eff': cms_labels = data['eff_labels'] else: cms_labels = data['att_labels'] if opt['cuda']:", "saved to {} \\n {}'.format(info_path, str(model))) with open(info_path, 'a') as", "* import torch.optim as optim from model.Model import Model from", "output directory dir = os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'],", "= data['att_labels'] if opt['cuda']: fc_feats = data['fc_feats'].cuda() cap_labels = data['cap_labels'].cuda()", "opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number of parameters model_parameters = filter(lambda p:", "data in loader: torch.cuda.synchronize() if opt['cms'] == 'int': cms_labels =", "0.98), eps=1e-09), 512, opt['warm_up_steps']) # note: though we set the", "/= n_word loss = cms_loss + cap_loss loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda", "opt['int_max_len'] elif opt['cms'] == 'eff': cms_text_length = opt['eff_max_len'] else: cms_text_length", "dataloader = DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size'] =", "'eff': cms_text_length = opt['eff_max_len'] else: cms_text_length = opt['att_max_len'] # model", "torch.cuda.synchronize() if opt['cms'] == 'int': cms_labels = data['int_labels'] elif opt['cms']", "= sum([np.prod(p.size()) for p in model_parameters]) print('number of learnable parameters", "LR may improve the results. opt['init_lr'] = round(optimizer.init_lr, 3) #", "opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path) print('model saved to %s' % model_path)", "learning rate as np.power(d_model, -0.5), # grid search indicates different", "cms_pos) cap_probs, _, cms_probs, _ = model(fc_feats, cap_labels, cms_labels) #", "# save the checkpoint model_path = os.path.join(opt['output_dir'], 'CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}_epoch_{}.pth' .format(opt['cms'], opt['init_lr'],", "boost, however is not the goal of this work. cap_loss,", "cap_train_loss = %.6f, cms_train_loss = %.6f,' ' current step =", ":-1], cms_vocab, caption=False) print(' \\n') with open(opt['info_path'], 'a') as f:", "opt['cuda']: model = model.cuda() # resume from previous checkpoint if", "different loss weights or stronger video feature # may lead", "= model.cuda() # resume from previous checkpoint if indicated if", "model.train() for epoch in range(opt['epochs']): iteration = 0 for data", "_, cms_probs, _ = model(fc_feats, cap_labels, cms_labels) # note: currently", "weights or stronger video feature # may lead performance boost,", "cms_loss: %.6f\\n' % (epoch, cap_train_loss, cms_train_loss)) f.write('\\n %s \\n %s'", "# advanced loss func. like SELF-CRIT, different loss weights or", "opt['rnn_layer'])) if not os.path.exists(dir): os.makedirs(dir) # save the model snapshot", "cms_n_correct/cms_n_word)) # show the intermediate generations if opt['show_predict']: cap_pr, cap_gt", "func. like SELF-CRIT, different loss weights or stronger video feature", "this work. cap_loss, cap_n_correct = cal_performance(cap_probs.view(-1, cap_probs.shape[-1]), cap_labels[:, 1:], smoothing=True)", "cap_n_correct/n_word, cms_n_correct/cms_n_word)) # show the intermediate generations if opt['show_predict']: cap_pr,", "to {} \\n {}'.format(info_path, str(model))) with open(info_path, 'a') as f:", "dataset.get_cms_vocab_size(), opt['cap_max_len'], cms_text_length, opt[\"dim_model\"], opt[\"dim_word\"], opt['dim_vis_feat'], n_layers=opt['rnn_layer']) # number of", "cms_non_pad_mask.sum().item() cap_loss /= n_word cms_loss /= n_word loss = cms_loss", "opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path) print('model", "step = %d, current lr = %.3E, cap_acc = %.3f,", "task. ''' __author__ = '<NAME>' import os import numpy as", "1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item() cms_non_pad_mask = cms_labels[:, 1:].ne(Constants.PAD) cms_n_word =", "loss.backward() optimizer.step_and_update_lr() torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()), 1) # update parameters", "n_layers=opt['rnn_layer']) # number of parameters model_parameters = filter(lambda p: p.requires_grad,", "cap_state_dict = torch.load(opt['load_checkpoint']) model_dict = model.state_dict() model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer =", "eps=1e-09), 512, opt['warm_up_steps']) # note: though we set the init", "if indicated if opt['load_checkpoint'] and opt['resume']: cap_state_dict = torch.load(opt['load_checkpoint']) model_dict", "indicates different LR may improve the results. opt['init_lr'] = round(optimizer.init_lr,", "optimizer.zero_grad() # cap_probs, cms_probs = model(fc_feats, cap_labels, cap_pos, cms_labels, cms_pos)", "however is not the goal of this work. cap_loss, cap_n_correct", "dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if opt['cms'] == 'int': cms_text_length =", "f.write('model_%d, cap_loss: %.6f, cms_loss: %.6f\\n' % (epoch, cap_train_loss/n_word, cms_train_loss/n_word)) def", "with open(info_path, 'a') as f: f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n') #", "= model(fc_feats, cap_labels, cap_pos, cms_labels, cms_pos) cap_probs, _, cms_probs, _", "\\n') with open(opt['info_path'], 'a') as f: f.write('model_%d, cap_loss: %.6f, cms_loss:", "= os.path.join(opt['checkpoint_path'], 'S2VT_CMS_CAP_MODEL_{}_lr_{}_BS_{}_Layer_{}_ATTHEAD_{}_HID_{}_RNNLayer_{}' .format(opt['cms'], opt['init_lr'], opt['batch_size'], opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer']))", "# note: though we set the init learning rate as", "from model.S2VTModel import S2VTModel model = S2VTModel( dataset.get_cap_vocab_size(), dataset.get_cms_vocab_size(), opt['cap_max_len'],", "else: cms_text_length = opt['att_max_len'] # model initialization. from model.S2VTModel import", "on single GPU. if opt['cuda']: torch.cuda.synchronize() iteration += 1 if", "train(dataloader, model, optimizer, opt, dataset.get_cap_vocab(), dataset.get_cms_vocab()) if __name__ == '__main__':", "str(model))) with open(info_path, 'a') as f: f.write(str(model)) f.write('\\n') f.write(str(params)) f.write('\\n')", "learnable parameters are {}'.format(params)) if opt['cuda']: model = model.cuda() #", "cms_vocab, caption=False) print(' \\n') with open(opt['info_path'], 'a') as f: f.write('model_%d,", "if opt['cuda']: model = model.cuda() # resume from previous checkpoint", "opt['num_head'], opt['dim_model'], opt['rnn_layer'])) if not os.path.exists(dir): os.makedirs(dir) # save the", "necessary in newer PyTorch version or on single GPU. if", "is not the goal of this work. cap_loss, cap_n_correct =", "# resume from previous checkpoint if indicated if opt['load_checkpoint'] and", "utils.dataloader import VideoDataset from model.transformer.Optim import ScheduledOptim def train(loader, model,", "def main(opt): # load and define dataloader dataset = VideoDataset(opt,", "= VideoDataset(opt, 'train') dataloader = DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] =", "%.6f\\n' % (epoch, cap_train_loss, cms_train_loss)) f.write('\\n %s \\n %s' %", "note: though we set the init learning rate as np.power(d_model,", "data['int_labels'] elif opt['cms'] == 'eff': cms_labels = data['eff_labels'] else: cms_labels", "epoch % opt['save_checkpoint_every'] == 0: # save the checkpoint model_path", "import torch.optim as optim from model.Model import Model from torch.utils.data", "= opt['eff_max_len'] else: cms_text_length = opt['att_max_len'] # model initialization. from", "if iteration % opt['print_loss_every'] ==0: print('iter %d (epoch %d), cap_train_loss", "cms_labels, cms_pos) cap_probs, _, cms_probs, _ = model(fc_feats, cap_labels, cms_labels)", "p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters])", "of learnable parameters are {}'.format(params)) if opt['cuda']: model = model.cuda()", "opt['num_layer'], opt['num_head'], opt['dim_model'], opt['rnn_layer'], epoch)) torch.save(model.state_dict(), model_path) print('model saved to", "cms_labels = data['att_labels'] if opt['cuda']: fc_feats = data['fc_feats'].cuda() cap_labels =", "print('model saved to %s' % model_path) with open(opt['model_info_path'], 'a') as", "DataLoader(dataset, batch_size=opt['batch_size'], shuffle=True) opt['cms_vocab_size'] = dataset.get_cms_vocab_size() opt['cap_vocab_size'] = dataset.get_cap_vocab_size() if", "cross-entropy as training objective, # advanced loss func. like SELF-CRIT,", "n_word cms_loss /= n_word loss = cms_loss + cap_loss loss.backward()", "token prediction Acc. non_pad_mask = cap_labels[:, 1:].ne(Constants.PAD) n_word = non_pad_mask.sum().item()", "multi-gpu case, not necessary in newer PyTorch version or on", "model_dict.update(cap_state_dict) model.load_state_dict(model_dict) optimizer = ScheduledOptim(optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), betas=(0.9, 0.98),", "range(opt['epochs']): iteration = 0 for data in loader: torch.cuda.synchronize() if", "parameters cap_train_loss = cap_loss.item() cms_train_loss = cms_loss.item() # multi-gpu case,", "epoch)) torch.save(model.state_dict(), model_path) print('model saved to %s' % model_path) with", "torch.nn.utils.clip_grad_norm_(filter(lambda p: p.requires_grad, model.parameters()), 1) # update parameters cap_train_loss =" ]
[ "= \"http://localhost:9999\" client = InfluxDBClient(url=url, token=token, org=org) writeApi = client.write_api()", "org = \"Energy Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\"", "\"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\": {\"location\": \"coyote_creek\"}, \"fields\": {\"water_level\": 1}, \"time\":", "= client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\": {\"location\": \"coyote_creek\"}, \"fields\":", "client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\": {\"location\": \"coyote_creek\"}, \"fields\": {\"water_level\":", "<filename>new-influx-client.py<gh_stars>0 import influxdb_client from influxdb_client import InfluxDBClient bucket = \"python-client-sandbox\"", "= InfluxDBClient(url=url, token=token, org=org) writeApi = client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\":", "bucket = \"python-client-sandbox\" org = \"Energy Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\"", "client = InfluxDBClient(url=url, token=token, org=org) writeApi = client.write_api() write_api.write(\"my-bucket\", \"my-org\",", "influxdb_client import InfluxDBClient bucket = \"python-client-sandbox\" org = \"Energy Monitor\"", "writeApi = client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\": {\"location\": \"coyote_creek\"},", "\"Energy Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\" client =", "token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\" client = InfluxDBClient(url=url, token=token,", "token=token, org=org) writeApi = client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\":", "Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\" client = InfluxDBClient(url=url,", "= \"Energy Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\" client", "from influxdb_client import InfluxDBClient bucket = \"python-client-sandbox\" org = \"Energy", "url = \"http://localhost:9999\" client = InfluxDBClient(url=url, token=token, org=org) writeApi =", "\"http://localhost:9999\" client = InfluxDBClient(url=url, token=token, org=org) writeApi = client.write_api() write_api.write(\"my-bucket\",", "org=org) writeApi = client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\": {\"location\":", "= \"python-client-sandbox\" org = \"Energy Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url", "\"python-client-sandbox\" org = \"Energy Monitor\" token = \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url =", "write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\", \"tags\": {\"location\": \"coyote_creek\"}, \"fields\": {\"water_level\": 1},", "import InfluxDBClient bucket = \"python-client-sandbox\" org = \"Energy Monitor\" token", "= \"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\" client = InfluxDBClient(url=url, token=token, org=org)", "import influxdb_client from influxdb_client import InfluxDBClient bucket = \"python-client-sandbox\" org", "\"miQdAvNXHiNDVVzPzV5FpkCaR_8qdQ-L1FlPCOXQPI325Kbrh1fgfhkcDUZ4FepaebDdpZ-A1gmtnnjU0_hViA==\" url = \"http://localhost:9999\" client = InfluxDBClient(url=url, token=token, org=org) writeApi", "influxdb_client from influxdb_client import InfluxDBClient bucket = \"python-client-sandbox\" org =", "InfluxDBClient bucket = \"python-client-sandbox\" org = \"Energy Monitor\" token =", "InfluxDBClient(url=url, token=token, org=org) writeApi = client.write_api() write_api.write(\"my-bucket\", \"my-org\", [{\"measurement\": \"h2o_feet\",", "[{\"measurement\": \"h2o_feet\", \"tags\": {\"location\": \"coyote_creek\"}, \"fields\": {\"water_level\": 1}, \"time\": 1}])" ]
[ "in instance.users.items(): if user == username and passwd == password:", "we should have added. for _, instance in manhole.protocol.portal.checkers.items(): found", "self.assertRaises(AssertionError): manhole_factory({}, None, \"\") with self.assertRaises(AssertionError): manhole_factory({}, \"\", None) def", "setUp(self): TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT = False", "b, c, d, e = True, 1, \"yes\", {}, 0.0", "Portal) # There could be multiple password checkers, check for", "2.0 (the \"License\"); # you may not use this file", "self.assertEqual(output, \"objects: ['bob', 'pp', 'show']\") def test_custom_object(self): class Foobar(object): a,", "\"pp\": pprint, \"show\": show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal)", "patch from twisted.internet.protocol import ServerFactory from twisted.cred.portal import Portal from", "self.assertRaises(AssertionError): manhole_factory({}, \"\", None) def test_instance_one(self): namespace = {\"bob\": None}", "test_wrap_long_line(self): class Foobar(object): a = \" \" * 90 output", "0 class terminal(object): RIGHT_ARROW, LEFT_ARROW = None, None class transport(object):", "\"\"\" + \"\"\" '... \"\"\").strip()) class TestLoggingManhole(TestManholeBase): def test_line_received(self): f", "for the one # we know we should have added.", "os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) with self.assertRaises(AssertionError): manhole_factory(namespace,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "manhole_factory(None, \"\", \"\") with self.assertRaises(AssertionError): manhole_factory({}, None, \"\") with self.assertRaises(AssertionError):", "TelnetRealm, manhole_factory, show) Peer = namedtuple(\"Peer\", (\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole):", "password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) output = StringIO() with", "a : True b : 1 c : yes d", "manhole.protocol.portal.checkers.items(): found = False for user, passwd in instance.users.items(): if", "class transport(object): @classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1 return Peer(os.urandom(12).encode(\"hex\"),", "with self.assertRaises(AssertionError): manhole_factory(namespace, username, password) def test_instance(self): namespace = {\"bob\":", "user == username and passwd == password: found = True", "twisted.cred.portal import Portal from twisted.conch.telnet import ( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport)", "ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm = TelnetRealm() with", "Foobar(object): a = \" \" * 90 output = StringIO()", "StringIO import StringIO from textwrap import dedent try: from unittest.mock", "use this file except in compliance with the License. #", "class terminal(object): RIGHT_ARROW, LEFT_ARROW = None, None class transport(object): @classmethod", "# limitations under the License. import os from collections import", "= manhole_factory(namespace, username, password) self.assertEqual(namespace, {\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\":", "output.getvalue().strip() self.assertEqual(output, \"objects: ['bob', 'pp', 'show']\") def test_custom_object(self): class Foobar(object):", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "ImportError: # pragma: no cover from mock import patch from", "License. # You may obtain a copy of the License", "manhole_factory(namespace, username, password) def test_instance(self): namespace = {\"bob\": None} username", "@classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535))", "output): show(Foobar) output.seek(0) output = output.getvalue().strip() self.assertEqual( output, dedent(\"\"\" data", "under the License is distributed on an \"AS IS\" BASIS,", "2014 <NAME> # # Licensed under the Apache License, Version", "License for the specific language governing permissions and # limitations", "line, this module is meant to be imported # #", "could be multiple password checkers, check for the one #", "test_uses_namespace(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password =", "e : 0.0 \"\"\").strip()) def test_wrap_long_line(self): class Foobar(object): a =", "of <class 'tests.test_agent.test_manhole.Foobar'> a : ' \"\"\" + \"\"\" '...", "test_protocol_factory(self): factory = TransportProtocolFactory(None) transport = factory() self.assertIsInstance(transport, TelnetTransport) class", "= os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) with self.assertRaises(AssertionError):", ": {} (0 elements) e : 0.0 \"\"\").strip()) def test_wrap_long_line(self):", "manhole = manhole_factory(namespace, username, password) self.assertEqual(namespace, {\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE,", "terminal(object): RIGHT_ARROW, LEFT_ARROW = None, None class transport(object): @classmethod def", "random import randint from StringIO import StringIO from textwrap import", "Copyright 2014 <NAME> # # Licensed under the Apache License,", "and password.\") def test_request_avatar(self): realm = TelnetRealm() avatar = realm.requestAvatar(None,", "+ \"\"\" '... \"\"\").strip()) class TestLoggingManhole(TestManholeBase): def test_line_received(self): f =", "StringIO from textwrap import dedent try: from unittest.mock import patch", "in compliance with the License. # You may obtain a", "username = os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) with", "software # distributed under the License is distributed on an", "self.assertEqual(namespace, {\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\": pprint, \"show\":", "user, passwd in instance.users.items(): if user == username and passwd", "class Foobar(object): a = \" \" * 90 output =", "= True if found: break else: self.fail(\"Failed to find correct", "output, dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : True", "def test_uses_namespace(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password", "= None FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT = False class TestManholeFactory(TestManholeBase):", "self.assertIsInstance(manhole.protocol.portal, Portal) # There could be multiple password checkers, check", "the License. import os from collections import namedtuple from pprint", "= TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def test_protocol_factory(self): factory =", "'tests.test_agent.test_manhole.Foobar'> a : True b : 1 c : yes", "import Portal from twisted.conch.telnet import ( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from", "class FakeLoggingManhole(LoggingManhole): QUIT = False GET_PEER_CALLS = 0 class terminal(object):", "except ImportError: # pragma: no cover from mock import patch", "self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm = TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None)", "1, \"yes\", {}, 0.0 output = StringIO() with patch(\"sys.stdout\", output):", "from collections import namedtuple from pprint import pprint from random", "def test_protocol_factory(self): factory = TransportProtocolFactory(None) transport = factory() self.assertIsInstance(transport, TelnetTransport)", "= TransportProtocolFactory(None) transport = factory() self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase): def", "manhole_factory({}, \"\", None) def test_instance_one(self): namespace = {\"bob\": None} username", "passwd == password: found = True if found: break else:", "one # we know we should have added. for _,", "<PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace, username, password) self.assertEqual(namespace, {\"bob\": None}) self.assertEqual(", "= <PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace, username, password) self.assertEqual(namespace, {\"bob\": None})", "= output.getvalue().strip() self.assertEqual(output, \"objects: ['bob', 'pp', 'show']\") def test_custom_object(self): class", "( LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory, show) Peer = namedtuple(\"Peer\", (\"host\",", "test_request_avatar_error(self): realm = TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def test_protocol_factory(self):", ": 1 c : yes d : {} (0 elements)", "output.seek(0) output = output.getvalue().strip() self.assertEqual( output, dedent(\"\"\" data attributes of", "class TestManholeFactory(TestManholeBase): def test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\") with", "'show']\") def test_custom_object(self): class Foobar(object): a, b, c, d, e", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "output = output.getvalue().strip() self.assertEqual( output, dedent(\"\"\" data attributes of <class", "mock import patch from twisted.internet.protocol import ServerFactory from twisted.cred.portal import", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "# See the License for the specific language governing permissions", "this module is meant to be imported # # Copyright", "pyfarm.agent.testutil import TestCase from pyfarm.agent.manhole import ( LoggingManhole, TransportProtocolFactory, TelnetRealm,", "1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def handle_QUIT(self): self.QUIT = True", "{}, 0.0 output = StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0)", "or agreed to in writing, software # distributed under the", "False class TestManholeFactory(TestManholeBase): def test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\")", "pprint from random import randint from StringIO import StringIO from", "required by applicable law or agreed to in writing, software", "handle_QUIT(self): self.QUIT = True class TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self):", "with the License. # You may obtain a copy of", "show() output.seek(0) output = output.getvalue().strip() self.assertEqual(output, \"objects: ['bob', 'pp', 'show']\")", "for _, instance in manhole.protocol.portal.checkers.items(): found = False for user,", "True, 1, \"yes\", {}, 0.0 output = StringIO() with patch(\"sys.stdout\",", "= os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) output = StringIO() with patch(\"sys.stdout\",", "in manhole.protocol.portal.checkers.items(): found = False for user, passwd in instance.users.items():", "found: break else: self.fail(\"Failed to find correct username and password.\")", "twisted.conch.telnet import ( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil import TestCase", "multiple password checkers, check for the one # we know", "\"\") with self.assertRaises(AssertionError): manhole_factory({}, None, \"\") with self.assertRaises(AssertionError): manhole_factory({}, \"\",", "= True, 1, \"yes\", {}, 0.0 output = StringIO() with", "compliance with the License. # You may obtain a copy", "d, e = True, 1, \"yes\", {}, 0.0 output =", "agreed to in writing, software # distributed under the License", "no cover from mock import patch from twisted.internet.protocol import ServerFactory", "distributed under the License is distributed on an \"AS IS\"", "== password: found = True if found: break else: self.fail(\"Failed", "TransportProtocolFactory(None) transport = factory() self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase): def test_uses_namespace(self):", "import StringIO from textwrap import dedent try: from unittest.mock import", "from unittest.mock import patch except ImportError: # pragma: no cover", "express or implied. # See the License for the specific", "= {\"bob\": None} username = os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\") manhole", "password checkers, check for the one # we know we", "except in compliance with the License. # You may obtain", "None) def test_instance_one(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\")", "pprint, \"show\": show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) #", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "should have added. for _, instance in manhole.protocol.portal.checkers.items(): found =", "not use this file except in compliance with the License.", "(\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole): QUIT = False GET_PEER_CALLS = 0", "\" \" * 90 output = StringIO() with patch(\"sys.stdout\", output):", "writing, software # distributed under the License is distributed on", "namedtuple from pprint import pprint from random import randint from", "you may not use this file except in compliance with", "import ( LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory, show) Peer = namedtuple(\"Peer\",", "realm.requestAvatar(None, None) def test_protocol_factory(self): factory = TransportProtocolFactory(None) transport = factory()", "= False for user, passwd in instance.users.items(): if user ==", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "= os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) output =", "username and passwd == password: found = True if found:", "( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil import TestCase from pyfarm.agent.manhole", "we know we should have added. for _, instance in", "None, \"pp\": pprint, \"show\": show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal,", "dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : True b", "permissions and # limitations under the License. import os from", "def handle_QUIT(self): self.QUIT = True class TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE", "CONDITIONS OF ANY KIND, either express or implied. # See", "os from collections import namedtuple from pprint import pprint from", "output = output.getvalue().strip() self.assertEqual(output, \"objects: ['bob', 'pp', 'show']\") def test_custom_object(self):", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "\" * 90 output = StringIO() with patch(\"sys.stdout\", output): show(Foobar)", "= {\"bob\": None} username = os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace,", "for user, passwd in instance.users.items(): if user == username and", "= True class TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS", "\"\", None) def test_instance_one(self): namespace = {\"bob\": None} username =", "False for user, passwd in instance.users.items(): if user == username", "with patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output = output.getvalue().strip() self.assertEqual( output,", "{\"bob\": None} username = os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username,", "namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\")", "# No shebang line, this module is meant to be", "= realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2]))", "def test_custom_object(self): class Foobar(object): a, b, c, d, e =", "self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm", "None) def test_protocol_factory(self): factory = TransportProtocolFactory(None) transport = factory() self.assertIsInstance(transport,", "TelnetRealm() avatar = realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1],", "_, instance in manhole.protocol.portal.checkers.items(): found = False for user, passwd", "with self.assertRaises(AssertionError): manhole_factory({}, None, \"\") with self.assertRaises(AssertionError): manhole_factory({}, \"\", None)", "a, b, c, d, e = True, 1, \"yes\", {},", "= 0 class terminal(object): RIGHT_ARROW, LEFT_ARROW = None, None class", "FakeLoggingManhole(LoggingManhole): QUIT = False GET_PEER_CALLS = 0 class terminal(object): RIGHT_ARROW,", "def test_wrap_long_line(self): class Foobar(object): a = \" \" * 90", "None} username = os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace,", "def setUp(self): TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT =", "import patch from twisted.internet.protocol import ServerFactory from twisted.cred.portal import Portal", "False GET_PEER_CALLS = 0 class terminal(object): RIGHT_ARROW, LEFT_ARROW = None,", "username = os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) output", "username, password) self.assertEqual(namespace, {\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\":", "self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\") with self.assertRaises(AssertionError): manhole_factory({}, None, \"\") with", "== username and passwd == password: found = True if", "know we should have added. for _, instance in manhole.protocol.portal.checkers.items():", "under the License. import os from collections import namedtuple from", "\"\") with self.assertRaises(AssertionError): manhole_factory({}, \"\", None) def test_instance_one(self): namespace =", "OR CONDITIONS OF ANY KIND, either express or implied. #", "governing permissions and # limitations under the License. import os", "= StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output = output.getvalue().strip()", "= 0 FakeLoggingManhole.QUIT = False class TestManholeFactory(TestManholeBase): def test_assertions(self): with", "find correct username and password.\") def test_request_avatar(self): realm = TelnetRealm()", "the License is distributed on an \"AS IS\" BASIS, #", "\"show\": show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) # There", "self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\": pprint, \"show\": show}) self.assertIsInstance(manhole, ServerFactory)", "from pyfarm.agent.manhole import ( LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory, show) Peer", "= namedtuple(\"Peer\", (\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole): QUIT = False GET_PEER_CALLS", "try: from unittest.mock import patch except ImportError: # pragma: no", "class TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS = 0", "class TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace = {\"bob\": None} username =", "['bob', 'pp', 'show']\") def test_custom_object(self): class Foobar(object): a, b, c,", "TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT", "There could be multiple password checkers, check for the one", "import ( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil import TestCase from", "* 90 output = StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0)", "\"\", \"\") with self.assertRaises(AssertionError): manhole_factory({}, None, \"\") with self.assertRaises(AssertionError): manhole_factory({},", "have added. for _, instance in manhole.protocol.portal.checkers.items(): found = False", "and passwd == password: found = True if found: break", "self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm = TelnetRealm()", "TestCase from pyfarm.agent.manhole import ( LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory, show)", "check for the one # we know we should have", "\"objects: ['bob', 'pp', 'show']\") def test_custom_object(self): class Foobar(object): a, b,", "password) with self.assertRaises(AssertionError): manhole_factory(namespace, username, password) def test_instance(self): namespace =", "from twisted.conch.telnet import ( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil import", "TransportProtocolFactory, TelnetRealm, manhole_factory, show) Peer = namedtuple(\"Peer\", (\"host\", \"port\")) class", "# we know we should have added. for _, instance", "GET_PEER_CALLS = 0 class terminal(object): RIGHT_ARROW, LEFT_ARROW = None, None", "output.getvalue().strip() self.assertEqual( output, dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a", "law or agreed to in writing, software # distributed under", "c : yes d : {} (0 elements) e :", "= StringIO() with patch(\"sys.stdout\", output): show() output.seek(0) output = output.getvalue().strip()", "from twisted.cred.portal import Portal from twisted.conch.telnet import ( ITelnetProtocol, TelnetBootstrapProtocol,", "= \" \" * 90 output = StringIO() with patch(\"sys.stdout\",", "patch except ImportError: # pragma: no cover from mock import", "yes d : {} (0 elements) e : 0.0 \"\"\").strip())", "to find correct username and password.\") def test_request_avatar(self): realm =", "else: self.fail(\"Failed to find correct username and password.\") def test_request_avatar(self):", "instance in manhole.protocol.portal.checkers.items(): found = False for user, passwd in", "may obtain a copy of the License at # #", "os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace, username, password) self.assertEqual(namespace,", "from StringIO import StringIO from textwrap import dedent try: from", "password: found = True if found: break else: self.fail(\"Failed to", ": yes d : {} (0 elements) e : 0.0", "import namedtuple from pprint import pprint from random import randint", "True if found: break else: self.fail(\"Failed to find correct username", "def test_instance_one(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password", "\"\"\").strip()) def test_wrap_long_line(self): class Foobar(object): a = \" \" *", "to be imported # # Copyright 2014 <NAME> # #", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "import pprint from random import randint from StringIO import StringIO", "username = os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace, username,", "realm = TelnetRealm() avatar = realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0],", "may not use this file except in compliance with the", "transport(object): @classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024,", "None, \"\") with self.assertRaises(AssertionError): manhole_factory({}, \"\", None) def test_instance_one(self): namespace", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) # There could", "with patch(\"sys.stdout\", output): show() output.seek(0) output = output.getvalue().strip() self.assertEqual(output, \"objects:", "this file except in compliance with the License. # You", "with self.assertRaises(AssertionError): manhole_factory({}, \"\", None) def test_instance_one(self): namespace = {\"bob\":", "be multiple password checkers, check for the one # we", "= os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace, username, password)", "'tests.test_agent.test_manhole.Foobar'> a : ' \"\"\" + \"\"\" '... \"\"\").strip()) class", "<NAME> # # Licensed under the Apache License, Version 2.0", "True b : 1 c : yes d : {}", "LEFT_ARROW = None, None class transport(object): @classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "= None, None class transport(object): @classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS +=", "\"\"\").strip()) class TestLoggingManhole(TestManholeBase): def test_line_received(self): f = FakeLoggingManhole() f.lineReceived(\"exit\") self.assertTrue(f.QUIT)", "def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "\"yes\", {}, 0.0 output = StringIO() with patch(\"sys.stdout\", output): show(Foobar)", "from twisted.internet.protocol import ServerFactory from twisted.cred.portal import Portal from twisted.conch.telnet", "class Foobar(object): a, b, c, d, e = True, 1,", "TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) # There could be multiple password checkers,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "QUIT = False GET_PEER_CALLS = 0 class terminal(object): RIGHT_ARROW, LEFT_ARROW", ": 0.0 \"\"\").strip()) def test_wrap_long_line(self): class Foobar(object): a = \"", "\"port\")) class FakeLoggingManhole(LoggingManhole): QUIT = False GET_PEER_CALLS = 0 class", "language governing permissions and # limitations under the License. import", "and # limitations under the License. import os from collections", "self.assertEqual( output, dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a :", "is meant to be imported # # Copyright 2014 <NAME>", "manhole_factory(namespace, username, password) output = StringIO() with patch(\"sys.stdout\", output): show()", "True class TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS =", "import dedent try: from unittest.mock import patch except ImportError: #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "meant to be imported # # Copyright 2014 <NAME> #", "output, dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : '", "self.assertRaises(AssertionError): manhole_factory(namespace, username, password) def test_instance(self): namespace = {\"bob\": None}", "0.0 \"\"\").strip()) def test_wrap_long_line(self): class Foobar(object): a = \" \"", "or implied. # See the License for the specific language", "= factory() self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace =", "'pp', 'show']\") def test_custom_object(self): class Foobar(object): a, b, c, d,", "FakeLoggingManhole.QUIT = False class TestManholeFactory(TestManholeBase): def test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None,", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "username, password) def test_instance(self): namespace = {\"bob\": None} username =", "if user == username and passwd == password: found =", "data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : True b :", "dedent try: from unittest.mock import patch except ImportError: # pragma:", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "username, password) output = StringIO() with patch(\"sys.stdout\", output): show() output.seek(0)", "FakeLoggingManhole.GET_PEER_CALLS += 1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def handle_QUIT(self): self.QUIT", "output = StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output =", "factory = TransportProtocolFactory(None) transport = factory() self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase):", "d : {} (0 elements) e : 0.0 \"\"\").strip()) def", "def test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\") with self.assertRaises(AssertionError): manhole_factory({},", "0 FakeLoggingManhole.QUIT = False class TestManholeFactory(TestManholeBase): def test_assertions(self): with self.assertRaises(AssertionError):", "dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : ' \"\"\"", "'... \"\"\").strip()) class TestLoggingManhole(TestManholeBase): def test_line_received(self): f = FakeLoggingManhole() f.lineReceived(\"exit\")", "import ServerFactory from twisted.cred.portal import Portal from twisted.conch.telnet import (", "(the \"License\"); # you may not use this file except", "attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : True b : 1", "TestManholeFactory(TestManholeBase): def test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\") with self.assertRaises(AssertionError):", "# you may not use this file except in compliance", ": True b : 1 c : yes d :", "if found: break else: self.fail(\"Failed to find correct username and", "{} (0 elements) e : 0.0 \"\"\").strip()) def test_wrap_long_line(self): class", "attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : ' \"\"\" + \"\"\"", "TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def test_protocol_factory(self): factory = TransportProtocolFactory(None)", "StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output = output.getvalue().strip() self.assertEqual(", "data attributes of <class 'tests.test_agent.test_manhole.Foobar'> a : ' \"\"\" +", "ServerFactory from twisted.cred.portal import Portal from twisted.conch.telnet import ( ITelnetProtocol,", "# # Unless required by applicable law or agreed to", "RIGHT_ARROW, LEFT_ARROW = None, None class transport(object): @classmethod def getPeer(cls):", "show) Peer = namedtuple(\"Peer\", (\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole): QUIT =", "self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) # There could be multiple password", "from pyfarm.agent.testutil import TestCase from pyfarm.agent.manhole import ( LoggingManhole, TransportProtocolFactory,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "pprint import pprint from random import randint from StringIO import", "# There could be multiple password checkers, check for the", "Version 2.0 (the \"License\"); # you may not use this", "username, password) with self.assertRaises(AssertionError): manhole_factory(namespace, username, password) def test_instance(self): namespace", "added. for _, instance in manhole.protocol.portal.checkers.items(): found = False for", "from pprint import pprint from random import randint from StringIO", "e = True, 1, \"yes\", {}, 0.0 output = StringIO()", "transport = factory() self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace", "TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm = TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None,", "implied. # See the License for the specific language governing", "manhole_factory(namespace, username, password) self.assertEqual(namespace, {\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None,", "under the Apache License, Version 2.0 (the \"License\"); # you", "import TestCase from pyfarm.agent.manhole import ( LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory,", "LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory, show) Peer = namedtuple(\"Peer\", (\"host\", \"port\"))", "a : ' \"\"\" + \"\"\" '... \"\"\").strip()) class TestLoggingManhole(TestManholeBase):", "test_instance_one(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password =", "c, d, e = True, 1, \"yes\", {}, 0.0 output", "<class 'tests.test_agent.test_manhole.Foobar'> a : True b : 1 c :", "return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def handle_QUIT(self): self.QUIT = True class", "by applicable law or agreed to in writing, software #", "TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\")", "os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) with self.assertRaises(AssertionError): manhole_factory(namespace, username, password) def", "show(Foobar) output.seek(0) output = output.getvalue().strip() self.assertEqual( output, dedent(\"\"\" data attributes", "\"\"\" '... \"\"\").strip()) class TestLoggingManhole(TestManholeBase): def test_line_received(self): f = FakeLoggingManhole()", "{\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\": pprint, \"show\": show})", "None class transport(object): @classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1 return", "StringIO() with patch(\"sys.stdout\", output): show() output.seek(0) output = output.getvalue().strip() self.assertEqual(output,", "test_custom_object(self): class Foobar(object): a, b, c, d, e = True,", "{\"bob\": None} username = os.urandom(32).encode(\"hex\") password = <PASSWORD>andom(32).encode(\"hex\") manhole =", "pyfarm.agent.manhole import ( LoggingManhole, TransportProtocolFactory, TelnetRealm, manhole_factory, show) Peer =", "TelnetRealm.NAMESPACE = None FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT = False class", "{\"bob\": None, \"pp\": pprint, \"show\": show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory)", "90 output = StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output", "import patch except ImportError: # pragma: no cover from mock", "elements) e : 0.0 \"\"\").strip()) def test_wrap_long_line(self): class Foobar(object): a", "None, None class transport(object): @classmethod def getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1", "# Copyright 2014 <NAME> # # Licensed under the Apache", "from random import randint from StringIO import StringIO from textwrap", "with self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\") with self.assertRaises(AssertionError): manhole_factory({}, None, \"\")", "self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) # There could be", "def test_request_avatar(self): realm = TelnetRealm() avatar = realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar),", "randint(1024, 65535)) def handle_QUIT(self): self.QUIT = True class TestManholeBase(TestCase): def", "output.seek(0) output = output.getvalue().strip() self.assertEqual(output, \"objects: ['bob', 'pp', 'show']\") def", "test_instance(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password =", "password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) with self.assertRaises(AssertionError): manhole_factory(namespace, username,", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "password = <PASSWORD>andom(32).encode(\"hex\") manhole = manhole_factory(namespace, username, password) self.assertEqual(namespace, {\"bob\":", "Foobar(object): a, b, c, d, e = True, 1, \"yes\",", "from mock import patch from twisted.internet.protocol import ServerFactory from twisted.cred.portal", "Unless required by applicable law or agreed to in writing,", "randint from StringIO import StringIO from textwrap import dedent try:", "manhole_factory(namespace, username, password) with self.assertRaises(AssertionError): manhole_factory(namespace, username, password) def test_instance(self):", "os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) output = StringIO()", "the specific language governing permissions and # limitations under the", "65535)) def handle_QUIT(self): self.QUIT = True class TestManholeBase(TestCase): def setUp(self):", "def test_instance(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password", "applicable law or agreed to in writing, software # distributed", "a = \" \" * 90 output = StringIO() with", "(0 elements) e : 0.0 \"\"\").strip()) def test_wrap_long_line(self): class Foobar(object):", "Peer = namedtuple(\"Peer\", (\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole): QUIT = False", "found = False for user, passwd in instance.users.items(): if user", "manhole_factory({}, None, \"\") with self.assertRaises(AssertionError): manhole_factory({}, \"\", None) def test_instance_one(self):", "TelnetTransport) class TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace = {\"bob\": None} username", "ServerFactory) self.assertIsInstance(manhole.protocol, TransportProtocolFactory) self.assertIsInstance(manhole.protocol.portal, Portal) # There could be multiple", "textwrap import dedent try: from unittest.mock import patch except ImportError:", "in writing, software # distributed under the License is distributed", "# # Copyright 2014 <NAME> # # Licensed under the", "import os from collections import namedtuple from pprint import pprint", "Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def handle_QUIT(self): self.QUIT = True class TestManholeBase(TestCase):", "passwd in instance.users.items(): if user == username and passwd ==", "pragma: no cover from mock import patch from twisted.internet.protocol import", "FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT = False class TestManholeFactory(TestManholeBase): def test_assertions(self):", "with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def test_protocol_factory(self): factory = TransportProtocolFactory(None) transport", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None, \"\", \"\") with self.assertRaises(AssertionError): manhole_factory({}, None,", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\": pprint, \"show\": show}) self.assertIsInstance(manhole, ServerFactory) self.assertIsInstance(manhole.protocol,", "self.QUIT = True class TestManholeBase(TestCase): def setUp(self): TelnetRealm.NAMESPACE = None", "self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm = TelnetRealm() with self.assertRaises(NotImplementedError):", "self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace = {\"bob\": None}", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "password) self.assertEqual(namespace, {\"bob\": None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\": pprint,", "password) def test_instance(self): namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\")", "= TelnetRealm() avatar = realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol)", "= output.getvalue().strip() self.assertEqual( output, dedent(\"\"\" data attributes of <class 'tests.test_agent.test_manhole.Foobar'>", "of <class 'tests.test_agent.test_manhole.Foobar'> a : True b : 1 c", "the one # we know we should have added. for", "No shebang line, this module is meant to be imported", "imported # # Copyright 2014 <NAME> # # Licensed under", "patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output = output.getvalue().strip() self.assertEqual( output, dedent(\"\"\"", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "TelnetTransport) from pyfarm.agent.testutil import TestCase from pyfarm.agent.manhole import ( LoggingManhole,", "instance.users.items(): if user == username and passwd == password: found", "+= 1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def handle_QUIT(self): self.QUIT =", "unittest.mock import patch except ImportError: # pragma: no cover from", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "import randint from StringIO import StringIO from textwrap import dedent", "realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def", "twisted.internet.protocol import ServerFactory from twisted.cred.portal import Portal from twisted.conch.telnet import", "b : 1 c : yes d : {} (0", "def test_request_avatar_error(self): realm = TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def", "<class 'tests.test_agent.test_manhole.Foobar'> a : ' \"\"\" + \"\"\" '... \"\"\").strip())", "= False GET_PEER_CALLS = 0 class terminal(object): RIGHT_ARROW, LEFT_ARROW =", "break else: self.fail(\"Failed to find correct username and password.\") def", "os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) output = StringIO() with patch(\"sys.stdout\", output):", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "Portal from twisted.conch.telnet import ( ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil", "username and password.\") def test_request_avatar(self): realm = TelnetRealm() avatar =", "module is meant to be imported # # Copyright 2014", "# pragma: no cover from mock import patch from twisted.internet.protocol", "3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol) self.assertTrue(callable(avatar[2])) def test_request_avatar_error(self): realm =", "correct username and password.\") def test_request_avatar(self): realm = TelnetRealm() avatar", ": ' \"\"\" + \"\"\" '... \"\"\").strip()) class TestLoggingManhole(TestManholeBase): def", "None} username = os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password)", "= False class TestManholeFactory(TestManholeBase): def test_assertions(self): with self.assertRaises(AssertionError): manhole_factory(None, \"\",", "namespace = {\"bob\": None} username = os.urandom(32).encode(\"hex\") password = os.urandom(32).encode(\"hex\")", "output): show() output.seek(0) output = output.getvalue().strip() self.assertEqual(output, \"objects: ['bob', 'pp',", "checkers, check for the one # we know we should", "None FakeLoggingManhole.GET_PEER_CALLS = 0 FakeLoggingManhole.QUIT = False class TestManholeFactory(TestManholeBase): def", "ITelnetProtocol, TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil import TestCase from pyfarm.agent.manhole import", "1 c : yes d : {} (0 elements) e", "cover from mock import patch from twisted.internet.protocol import ServerFactory from", "found = True if found: break else: self.fail(\"Failed to find", "\"License\"); # you may not use this file except in", "self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def test_protocol_factory(self): factory = TransportProtocolFactory(None) transport =", "= os.urandom(32).encode(\"hex\") manhole_factory(namespace, username, password) with self.assertRaises(AssertionError): manhole_factory(namespace, username, password)", "getPeer(cls): FakeLoggingManhole.GET_PEER_CALLS += 1 return Peer(os.urandom(12).encode(\"hex\"), randint(1024, 65535)) def handle_QUIT(self):", "None}) self.assertEqual( TelnetRealm.NAMESPACE, {\"bob\": None, \"pp\": pprint, \"show\": show}) self.assertIsInstance(manhole,", "password.\") def test_request_avatar(self): realm = TelnetRealm() avatar = realm.requestAvatar(None, ITelnetProtocol)", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# distributed under the License is distributed on an \"AS", "patch(\"sys.stdout\", output): show() output.seek(0) output = output.getvalue().strip() self.assertEqual(output, \"objects: ['bob',", "# Unless required by applicable law or agreed to in", "self.fail(\"Failed to find correct username and password.\") def test_request_avatar(self): realm", "manhole_factory, show) Peer = namedtuple(\"Peer\", (\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole): QUIT", "0.0 output = StringIO() with patch(\"sys.stdout\", output): show(Foobar) output.seek(0) output", "' \"\"\" + \"\"\" '... \"\"\").strip()) class TestLoggingManhole(TestManholeBase): def test_line_received(self):", "TelnetBootstrapProtocol, TelnetTransport) from pyfarm.agent.testutil import TestCase from pyfarm.agent.manhole import (", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "be imported # # Copyright 2014 <NAME> # # Licensed", "You may obtain a copy of the License at #", "namedtuple(\"Peer\", (\"host\", \"port\")) class FakeLoggingManhole(LoggingManhole): QUIT = False GET_PEER_CALLS =", "limitations under the License. import os from collections import namedtuple", "test_request_avatar(self): realm = TelnetRealm() avatar = realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3)", "collections import namedtuple from pprint import pprint from random import", "realm = TelnetRealm() with self.assertRaises(NotImplementedError): realm.requestAvatar(None, None) def test_protocol_factory(self): factory", "password) output = StringIO() with patch(\"sys.stdout\", output): show() output.seek(0) output", "shebang line, this module is meant to be imported #", "the Apache License, Version 2.0 (the \"License\"); # you may", "factory() self.assertIsInstance(transport, TelnetTransport) class TestManholeShow(TestManholeBase): def test_uses_namespace(self): namespace = {\"bob\":", "output = StringIO() with patch(\"sys.stdout\", output): show() output.seek(0) output =", "License. import os from collections import namedtuple from pprint import", "avatar = realm.requestAvatar(None, ITelnetProtocol) self.assertEqual(len(avatar), 3) self.assertIs(avatar[0], ITelnetProtocol) self.assertIsInstance(avatar[1], TelnetBootstrapProtocol)", "from textwrap import dedent try: from unittest.mock import patch except" ]
[ "# coding: utf-8 \"\"\" 插入所有需要的库,和函数 \"\"\" #---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\"", "if self.mode == 'deal': self.canvas.updateSig(self.signalsOpen) self.mode = 'dealOpen' else: self.canvas.updateSig(self.signals)", "'deal': self.canvas.updateSig(self.signalsOpen) self.mode = 'dealOpen' else: self.canvas.updateSig(self.signals) self.mode = 'deal'", "\"\"\" 插入所有需要的库,和函数 \"\"\" #---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\" if self.mode ==", "插入所有需要的库,和函数 \"\"\" #---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\" if self.mode == 'deal':", "utf-8 \"\"\" 插入所有需要的库,和函数 \"\"\" #---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\" if self.mode", "#---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\" if self.mode == 'deal': self.canvas.updateSig(self.signalsOpen) self.mode", "\"\"\"查找模式\"\"\" if self.mode == 'deal': self.canvas.updateSig(self.signalsOpen) self.mode = 'dealOpen' else:", "coding: utf-8 \"\"\" 插入所有需要的库,和函数 \"\"\" #---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\" if", "\"\"\" #---------------------------------------------------------------------- def klSigmode(self): \"\"\"查找模式\"\"\" if self.mode == 'deal': self.canvas.updateSig(self.signalsOpen)", "klSigmode(self): \"\"\"查找模式\"\"\" if self.mode == 'deal': self.canvas.updateSig(self.signalsOpen) self.mode = 'dealOpen'", "def klSigmode(self): \"\"\"查找模式\"\"\" if self.mode == 'deal': self.canvas.updateSig(self.signalsOpen) self.mode =", "<gh_stars>100-1000 # coding: utf-8 \"\"\" 插入所有需要的库,和函数 \"\"\" #---------------------------------------------------------------------- def klSigmode(self):", "self.mode == 'deal': self.canvas.updateSig(self.signalsOpen) self.mode = 'dealOpen' else: self.canvas.updateSig(self.signals) self.mode", "== 'deal': self.canvas.updateSig(self.signalsOpen) self.mode = 'dealOpen' else: self.canvas.updateSig(self.signals) self.mode =" ]
[ "exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png')) if geoloc: if exportJSON: project_name", "nodes_grid[x, y]: end = True else: end = True return", "degrees of the nodes (2=endpoint, 4=crossroads of 3 streets, 5=crossroads", "segments: coords = [] for point in segment: coords.append((point[1], point[0]))", "given start node and direction until the next node, and", "image of the road network nodes_grid: grid of the nodes", "stats = stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels ==", "' -s -o ' + svg_path) return simple_segments, full_segments, nodes_grid", "in diagonal[d]): new_address.append(d) else: new_address.append(d) return new_address def explorePath(start_x: int,", "w.field('streetname', 'C', 41, 0) w.field('note', 'C', 32, 0) for i", "new_x, new_y if nodes_grid[x, y]: end = True else: end", "np.ndarray): ''' Follow the path from one given start node", "\\n', ' brew install potrace\\n') if exportPNG: png_path = export_file_path", "= x-1, y+1 elif way == 3: x_, y_ =", "if exportJSON: with open(export_file_path.replace('png', 'json'), 'w') as outfile: json.dump(simple_segments_JSON, outfile)", "nodes[:,1], 'degree': degree, 'address': addresses }) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes", "a bitmap image from the road network. Input(s): segments: list", "+ ',' + str(way) + '), way \\ should be", "nodes in the road network skeleton image. Input(s): image: skeletonized", "of type int.') return x_, y_ def noTurnBack(direction: int): wrong_paths", "if len(degree) < 0: return [], [], np.zeros((image.shape[1], image.shape[0])) df_nodes", "(np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap = Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap) for", "+ 1) df['address'] = new_addresses df['degree'] = new_degree return df", "node y-coordinate start_dir: starting direction ({0, 1, 2, 3, -,", "''' Save a given set of segments as a bitmap", "try: with open(os.path.join('save', project_name, 'match' , 'primary', image_name + '.json'))", "ways: list of segments, containing all the pixels on the", "= 'black', width=0) bitmap.save(out_path) def toShapefile(simple_ways, out_path): w = shp.Writer(out_path)", "= os.path.join('workshop', 'thin.png') pnm_path = os.path.join('workshop', 'thin.pnm') svg_path = export_file_path.replace('png',", "+ pnm_path) os.system('potrace ' + pnm_path + ' -s -o", "from PIL import Image, ImageDraw from utils.utils import * from", "coordinates n_neighbours = np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood == True)[0] last_ds", "''' Thinning/skeletonization of the road network image to a wired", "direction == 6: wrong_paths = [1, 5] elif direction ==", "this to our list of coordinates n_neighbours = np.sum(pix_neighbourhood) direction_set", "False, exportSVG: bool = False, exportSHP: bool = False, geoloc:", "+ str(y) + ',' + str(way) + '), way \\", "the next node, and stores the pixels on the way.", "direction_set = direction_set[direction_set != 4] last_ds.append(direction_set) direction_set = direction_set[direction_set !=", "thinning.guo_hall_thinning(img) vectorized[vectorized > 100] = 255 vectorized[vectorized <= 100] =", "degree ''' img = image.copy() done, ways = [], []", "def toShapefile(simple_ways, out_path): w = shp.Writer(out_path) w.field('DeletionFlag', 'C', 1, 0)", "r > 0 and c > 0 and r <", "must be grayscale image' img = cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized", "and check for non-zero locations pix_neighbourhood = img[row_neigh, col_neigh].ravel() !=", "= True else: end = True return way, direction, nodes_grid[x,", "the path from one given start node and direction until", "255 vectorized[vectorized <= 100] = 0 if largest_component: try: _,", "should be of type int.') return x_, y_ def noTurnBack(direction:", "else: print('La géolocalisation du réseau filaire ne fonctionne que pour", "({0, 1, 2, 3, -, 5, 6, 7, 8}) image:", "ways.append(way) if return_simple_ways: simple_ways = [] for way in ways:", "8: [5, 7]} new_address = [] for r in right:", "nodes.append((r, c)) degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood == True)[0] direction_set =", "elif way == 6: x_, y_ = x+1, y-1 elif", "0) w.field('streetname', 'C', 41, 0) w.field('note', 'C', 32, 0) for", "as outfile: json.dump(simple_segments_JSON, outfile) if exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments,", "nodes found in the image and their degree ''' img", "image.copy() road_network[road_network < 254] = 0 road_network[road_network < 255/2] =", "= Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap) for segment in segments: coords", "only the largest road network component will be kept Output(s):", "https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n', ' brew install imagemagick') print('Pour installer", ">= 4): nodes.append((r, c)) degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood == True)[0]", "fill = 'black', width=0) bitmap.save(out_path) def toShapefile(simple_ways, out_path): w =", "of each segment and return it. Input(s): df_nodes: list of", "pd import shapefile as shp from skimage.measure import approximate_polygon from", "bool = False, geoloc: bool = False): assert (exportPNG or", "== main_component).astype('uint8')*255 except: 'Warning: Skeletonization failed to apply largest_component =", "if True, only the largest road network component will be", "2) or (degree == 2))): done.append(str(way[-1][0]) + '_' + str(way[-1][1])", "= image.copy() road_network[road_network < 254] = 0 road_network[road_network < 255/2]", "and c > 0 and r < image.shape[0]-1 and c", "from utils.utils import * from utils.match import toLatLon Image.MAX_IMAGE_PIXELS =", "df_nodes[df_nodes['degree'] != 3] if (exportJSON or exportSHP): simple_segments, full_segments, nodes_grid", "to index into image col_neigh = col_neigh.astype('int') row_neigh = row_neigh.astype('int')", "all the pixels on the way between each couple of", "end = True else: end = True return way, direction,", "np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1, y, y+1])) # Cast to int", "as np import pandas as pd import shapefile as shp", "path: str = \"workshop/vectorized.png\", largest_component: bool = False): ''' Thinning/skeletonization", "toShapefile(simple_ways, out_path): w = shp.Writer(out_path) w.field('DeletionFlag', 'C', 1, 0) w.field('gid',", "7] elif direction == 3: wrong_paths = [2, 8] elif", "direction == 3: wrong_paths = [2, 8] elif direction ==", "the road segments in the network. Keep the ones that", "import pandas as pd import shapefile as shp from skimage.measure", "simple itinerary of each segment and return it Output(s): (Optional)(simple_ways:", "c+1]), np.array([r-1, r, r+1])) # Cast to int to index", "géolocalisation du réseau filaire ne fonctionne que pour le format", "the way between each couple of nodes vectorized: skeletonized image", "= False): ''' Thinning/skeletonization of the road network image to", "M[:, 2:3].transpose()).tolist()) except: print(\"La géolocalisation de l'image {} n'a pas", "elif direction == 8: wrong_paths = [1, 3] return wrong_paths", "nodes (2=endpoint, 4=crossroads of 3 streets, 5=crossroads of 4 streets,", "image. Input(s): image: skeletonized image Output(s): nodes: array of nodes", "Convert into a single 1D array and check for non-zero", "if return_simple_ways: simple_ways = [] for way in ways: inv_way", "address) and not(diagonal[d][1] in address): if direction != None: if", "road_network: black and white image of the road network (streets", "return it. Input(s): df_nodes: list of nodes image: skeletonized image", "de l'image {} n'a pas encore été calculée. Par conséquent,", "pd.DataFrame): df = df_nodes.copy() new_addresses, new_degree = [], [] for", "segment in simple_segments: s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) +", "array of nodes coordinates (x, y) degree: degrees of the", "Find all the road segments in the network. Keep the", "' + svg_path) return simple_segments, full_segments, nodes_grid def toPNG(segments: list,", "actuellement.') else: simple_segments_JSON = simple_segments if exportJSON: with open(export_file_path.replace('png', 'json'),", "to our list of coordinates n_neighbours = np.sum(pix_neighbourhood) direction_set =", "this to our list of coordinates n_neighbours = np.sum(pix_neighbourhood) if", "de son réseau filaire\".format(image_name)) simple_segments_JSON = simple_segments else: print('La géolocalisation", "in simple_segments: s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:,", "== 6: wrong_paths = [1, 5] elif direction == 7:", "of the road network nodes_grid: grid of the nodes of", "direction to reach the 2nd node nodes_grid[x, y]: degree of", "== 5: x_, y_ = x, y+1 elif way ==", "while not(end): if x > 0 and y > 0", "il n'est pas possible de calculer la géolocalisation de son", "[1, 3], 2: [1, 5], 6: [3, 7], 8: [5,", "min_length: min segment length if the segment is terminal return_simple_ways:", "et Potrace via le terminal.\\n\") print('Pour installer Homebrew:\\n', ' /usr/bin/ruby", "# Coded by <NAME> https://github.com/RPetitpierre # For Bibliothèque nationale de", "= np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1, r, r+1])) # Cast to", "np.ndarray, image_name: str, export_file_path: str, exportPNG: bool = False, exportJSON:", "c, c+1]), np.array([r-1, r, r+1])) # Cast to int to", "BackThen Maps # Coded by <NAME> https://github.com/RPetitpierre # For Bibliothèque", "coords = [] for point in segment: coords.append((point[1], point[0])) draw.line(coords,", "image from the road network. Input(s): segments: list of segments,", "bitmap image from the road network. Input(s): segments: list of", "image.copy() # Find row and column locations that are non-zero", "of the crossing roads, with regard to the node '''", "path, where the output bitmap image should be save '''", "noTurnBack(direction: int): wrong_paths = [] if direction == 0: wrong_paths", "= image[row_neigh, col_neigh].transpose().ravel() != 0 except: print(x, y, image.shape, )", "+ pnm_path + ' -s -o ' + svg_path) return", "and != 4. x, y and way should be of", "exportSVG: print(\"\\nAvertissement: Si vous n'avez jamais utilisé cette commande, \\", "be saved largest_component: if True, only the largest road network", "degree, addresses = findNodes(vectorized) if len(degree) < 0: return [],", "diagonal[d]): new_address.append(d) else: new_address.append(d) return new_address def explorePath(start_x: int, start_y:", "direction) assert image[new_x, new_y] != 0, 'ERROR: 2nd point is", "largest_component = True param. Skipping.' cv2.imwrite(path, vectorized) return vectorized def", "= pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1], 'degree': degree, 'address': addresses })", "Output(s): vectorized: skeletonized image ''' assert len(road_network.shape) == 2, 'ERROR:", "image of the road network (streets in white) path: path", "row_neigh = col_neigh.astype('int'), row_neigh.astype('int') # Convert into a single 1D", "direction == 1: wrong_paths = [6, 8] elif direction ==", "vectorized) return vectorized def findNodes(image: np.ndarray): ''' Find the nodes", "return it Output(s): (Optional)(simple_ways: the Douglas-Peucker simple itinerary of each", "return vectorized def findNodes(image: np.ndarray): ''' Find the nodes in", "= np.sum(pix_neighbourhood) if (n_neighbours == 2) or (n_neighbours >= 4):", "= x, y+1 elif way == 6: x_, y_ =", "'Warning: Skeletonization failed to apply largest_component = True param. Skipping.'", "new_addresses df['degree'] = new_degree return df def avoidDiagonalEdges(address: list, direction:", "degree: degrees of the nodes (2=endpoint, 4=crossroads of 3 streets,", "if exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name)) if", "[] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape) for ind, row", "y_ = x-1, y+1 elif way == 3: x_, y_", "bool = False): ''' Thinning/skeletonization of the road network image", "geoloc: if exportJSON: project_name = getProjectName() try: with open(os.path.join('save', project_name,", "7] elif direction == 1: wrong_paths = [6, 8] elif", "way = [(x, y)] # First iteration new_x, new_y =", "np.zeros(image.shape) for ind, row in df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']]", "node x-coordinate start_y: start node y-coordinate start_dir: starting direction ({0,", "list of segments, containing all the pixels on the way", "given set of segments as a bitmap image from the", "== 0: x_, y_ = x-1, y-1 elif way ==", "str(x) + ',' + str(y) + ',' + str(way) +", "next node, and stores the pixels on the way. Input(s):", "r < image.shape[0]-1 and c < image.shape[1]-1: # Extract an", "y+1])) # Cast to int to index into image col_neigh,", "skeleton image. Input(s): image: skeletonized image Output(s): nodes: array of", "[1, 3] return wrong_paths direction = start_dir x, y =", "str = \"workshop/vectorized.png\", largest_component: bool = False): ''' Thinning/skeletonization of", "= stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels == main_component).astype('uint8')*255", "<filename>utils/thin.py # 2020, BackThen Maps # Coded by <NAME> https://github.com/RPetitpierre", "''' img = image.copy() # Find row and column locations", "check for non-zero locations pix_neighbourhood = img[row_neigh, col_neigh].ravel() != 0", "locations try: pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel() != 0 except: print(x,", "network component will be kept Output(s): vectorized: skeletonized image '''", "if wrong_paths_active: for wrong_path in wrong_paths: direction_set = direction_set[direction_set !=", "a given set of segments as a bitmap image from", "as pd import shapefile as shp from skimage.measure import approximate_polygon", "= export_file_path.replace('png', 'svg') os.system('convert ' + png_path + pnm_path) os.system('potrace", "image of the road network min_length: min segment length if", "True if nodes_grid[x, y]: end = True direction = 8-start_dir", "df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']] = row['degree'] nodes_grid = nodes_grid.astype('int')", "= np.where(pix_neighbourhood == True)[0] direction_set = direction_set[direction_set != 4] addresses.append(direction_set)", "(row_neigh, col_neigh) = np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1, y, y+1])) #", "((node['degree'] == 2) or (degree == 2))): done.append(str(way[-1][0]) + '_'", "exportSHP: bool = False, geoloc: bool = False): assert (exportPNG", "nodes_grid: image containing all the nodes found in the image", "== 3: x_, y_ = x, y-1 elif way ==", "road network (streets in white) path: path where the skeletonized", "1D array and check for non-zero locations try: pix_neighbourhood =", "in address) and not(diagonal[d][1] in address): if direction != None:", "d'abord Homebrew, ImageMagick et Potrace via le terminal.\\n\") print('Pour installer", "= 255 vectorized[vectorized <= 100] = 0 if largest_component: try:", "nodes_grid.astype('int') for ind, node in df_nodes.iterrows(): for direct in node['address']:", "' brew install imagemagick') print('Pour installer Potrace: \\n', ' brew", "between each couple of nodes vectorized: skeletonized image of the", "export_file_path: str, exportPNG: bool = False, exportJSON: bool = False,", "8-start_dir while not(end): if x > 0 and y >", "direction_set[direction_set != wrong_path] wrong_paths_active = False if len(direction_set) != 1:", "for direct in node['address']: code = str(node['x']) + '_' +", "new_address def explorePath(start_x: int, start_y: int, start_dir: int, image: np.ndarray,", "+ str(8-last_direct)) ways.append(way) if return_simple_ways: simple_ways = [] for way", "and stores the pixels on the way. Input(s): start_x: start", "a single 1D array and check for non-zero locations try:", "wrong_paths direction = start_dir x, y = start_x, start_y assert", "import * from utils.match import toLatLon Image.MAX_IMAGE_PIXELS = 500000000 def", "not((len(way) <= min_length) and ((node['degree'] == 2) or (degree ==", "of nodes vectorized: skeletonized image of the road network out_path:", "== 1: x_, y_ = x-1, y elif way ==", "w.field('note', 'C', 32, 0) for i in range(len(simple_ways)): w.line([simple_ways[i]]) w.record('01',", "addresses.append(direction_set) nodes = np.asarray(nodes) return nodes, degree, addresses def cleanNodesEdges(df_nodes:", "'black', width=0) bitmap.save(out_path) def toShapefile(simple_ways, out_path): w = shp.Writer(out_path) w.field('DeletionFlag',", "os.system('potrace ' + pnm_path + ' -s -o ' +", "row_neigh) = np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1, r, r+1])) # Cast", "y]: degree of the arrival node ''' def absoluteWay(x: int,", "png_path = os.path.join('workshop', 'thin.png') pnm_path = os.path.join('workshop', 'thin.pnm') svg_path =", "6: [3, 7], 8: [5, 7]} new_address = [] for", "x_, y_ = x, y-1 elif way == 5: x_,", "np.nonzero(img) nodes, degree, addresses = [], [], [] for (r,c)", "way == 7: x_, y_ = x+1, y elif way", "def toPNG(segments: list, vectorized: np.ndarray, out_path: str): ''' Save a", "the way direction: last direction to reach the 2nd node", "== 2) or (n_neighbours >= 4): nodes.append((r, c)) degree.append(n_neighbours) direction_set", "os.path.join('workshop', 'thin.png') pnm_path = os.path.join('workshop', 'thin.pnm') svg_path = export_file_path.replace('png', 'svg')", "== 2) or (degree == 2))): done.append(str(way[-1][0]) + '_' +", "return ways, nodes_grid def thinImage(image: np.ndarray, image_name: str, export_file_path: str,", "255 vectorized = skeletonize(road_network, largest_component = True) nodes, degree, addresses", "in zip(rows, cols): if r > 0 and c >", "list of coordinates n_neighbours = np.sum(pix_neighbourhood) if (n_neighbours == 2)", "nodes_grid[x, y]: end = True direction = 8-start_dir while not(end):", "vectorized[vectorized <= 100] = 0 if largest_component: try: _, labels,", "np.array([y-1, y, y+1])) # Cast to int to index into", "nodes_grid[x, y] def findSegments(df_nodes: pd.DataFrame, image: np.ndarray, min_length: int =", "image: np.ndarray, min_length: int = 30, return_simple_ways: bool = True):", "of the road network out_path: the path, where the output", "return_simple_ways = False) simple_segments = [] if exportPNG: toPNG(full_segments, vectorized,", "df = df_nodes.copy() new_addresses, new_degree = [], [] for ind,", "ones that are longer than a given length or non-terminal.", "= [], [] for ind, address in df['address'].iteritems(): new_address =", "is terminal return_simple_ways: if True, compute the Douglas-Peucker simple itinerary", "road network skeleton image. Input(s): image: skeletonized image Output(s): nodes:", "nodes_grid[x, y]: degree of the arrival node ''' def absoluteWay(x:", "+ '), way \\ should be comprised between 0 and", "= direction_set[direction_set != 4] last_ds.append(direction_set) direction_set = direction_set[direction_set != (8-direction)]", "''' Find the nodes in the road network skeleton image.", "itinerary of each segment and return it. Input(s): df_nodes: list", "comprised between 0 and 8, and != 4. x, y", "iteration new_x, new_y = absoluteWay(x, y, direction) assert image[new_x, new_y]", "simple_ways = [] for way in ways: inv_way = np.asarray([np.asarray(way)[:,1],", "skeletonize(road_network: np.ndarray, path: str = \"workshop/vectorized.png\", largest_component: bool = False):", "and white image of the road network (streets in white)", "str(way) + '), way \\ should be comprised between 0", "str(direct) if not(code in done): way, last_direct, degree = explorePath(start_x=node['x'],", "an 8-connected neighbourhood (row_neigh, col_neigh) = np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1,", "= absoluteWay(x, y, direction) way.append((new_x, new_y)) x, y = new_x,", "= [(x, y)] # First iteration new_x, new_y = absoluteWay(x,", "3: x_, y_ = x, y-1 elif way == 5:", "# First iteration new_x, new_y = absoluteWay(x, y, direction) assert", "s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:, 2:3].transpose()).tolist()) except:", "os.path.join(export_file_path.replace('.png', ''), image_name)) if exportSVG: print(\"\\nAvertissement: Si vous n'avez jamais", "avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) + 1) df['address'] = new_addresses df['degree'] =", "of the nodes (2=endpoint, 4=crossroads of 3 streets, 5=crossroads of", "int): if way == 0: x_, y_ = x-1, y-1", "np.ndarray, out_path: str): ''' Save a given set of segments", "{0: [1, 3], 2: [1, 5], 6: [3, 7], 8:", "in the image and their degree ''' img = image.copy()", "output bitmap image should be save ''' canvas = (np.ones(vectorized.shape)*255).astype('uint8')", "bitmap.save(out_path) def toShapefile(simple_ways, out_path): w = shp.Writer(out_path) w.field('DeletionFlag', 'C', 1,", "assert (exportPNG or exportJSON or exportSVG or exportSHP) # Convert", "[6, 8] elif direction == 2: wrong_paths = [3, 7]", "= 0 road_network[road_network >= 255/2] = 255 vectorized = skeletonize(road_network,", "last_ds.append(direction_set) if wrong_paths_active: for wrong_path in wrong_paths: direction_set = direction_set[direction_set", "saved largest_component: if True, only the largest road network component", "not white' end = False way = [(x, y)] #", "= None): right, diagonal = [1, 3, 5, 7], {0:", "direction ({0, 1, 2, 3, -, 5, 6, 7, 8})", "done.append(str(way[-1][0]) + '_' + str(way[-1][1]) + '_' + str(8-last_direct)) ways.append(way)", "in address: if not(diagonal[d][0] in address) and not(diagonal[d][1] in address):", "if not(diagonal[d][0] in address) and not(diagonal[d][1] in address): if direction", "else: simple_segments_JSON = simple_segments if exportJSON: with open(export_file_path.replace('png', 'json'), 'w')", "int, start_dir: int, image: np.ndarray, nodes_grid: np.ndarray): ''' Follow the", "0) for i in range(len(simple_ways)): w.line([simple_ways[i]]) w.record('01', i, '', '')", "non-zero locations equals 2, add this to our list of", "out_path: the path, where the output bitmap image should be", "2: x_, y_ = x-1, y+1 elif way == 3:", "white image of the road network (streets in white) path:", "_, labels, stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats =", "= df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape) for ind, row in df_nodes[['x',", "= findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways = True) else:", "findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways = True) else: full_segments,", "of the skeletonized image Output(s): way: list of pixel coordinates", "way, direction, nodes_grid[x, y] def findSegments(df_nodes: pd.DataFrame, image: np.ndarray, min_length:", "Si vous n'avez jamais utilisé cette commande, \\ installez d'abord", "ind, row in df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']] = row['degree']", "new_address = avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) + 1) df['address'] = new_addresses", "largest_component: bool = False): ''' Thinning/skeletonization of the road network", "= direction_set[direction_set != (8-direction)] last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set)", "vectorized, min_length = 15, return_simple_ways = False) simple_segments = []", "= noTurnBack(direction) wrong_paths_active = True if nodes_grid[x, y]: end =", "Douglas-Peucker simple itinerary of each segment and return it Output(s):", "None: if not((8-direction) in diagonal[d]): new_address.append(d) else: new_address.append(d) return new_address", "new_degree.append(len(new_address) + 1) df['address'] = new_addresses df['degree'] = new_degree return", "way: int): if way == 0: x_, y_ = x-1,", "Input(s): segments: list of segments, containing all the pixels on", "<= 100] = 0 if largest_component: try: _, labels, stats,", "100] = 0 if largest_component: try: _, labels, stats, _", "8-connected neighbourhood (col_neigh, row_neigh) = np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1, r,", "Find row and column locations that are non-zero (rows, cols)", "France (BnF) import cv2, thinning, os import numpy as np", "!= 1: end = True break direction = direction_set[0] new_x,", "degree of the arrival node ''' def absoluteWay(x: int, y:", "simple_segments_JSON = simple_segments else: print('La géolocalisation du réseau filaire ne", "col_neigh, row_neigh = col_neigh.astype('int'), row_neigh.astype('int') # Convert into a single", "image: skeletonized image of the road network min_length: min segment", "7], {0: [1, 3], 2: [1, 5], 6: [3, 7],", "= absoluteWay(x, y, direction) assert image[new_x, new_y] != 0, 'ERROR:", "are longer than a given length or non-terminal. Optionally, compute", "< image.shape[0]-1 and y < image.shape[1]-1: # Extract an 8-connected", "node ''' img = image.copy() # Find row and column", "np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:, 2:3].transpose()).tolist()) except: print(\"La géolocalisation", "raise AssertionError() # If the number of non-zero locations equals", "img = image.copy() # Find row and column locations that", "node and direction until the next node, and stores the", "be save ''' canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap =", "= True if nodes_grid[x, y]: end = True direction =", "largest_component: try: _, labels, stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA)", "= np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:, 2:3].transpose()).tolist()) except: print(\"La", "= np.asarray(data['M']) simple_segments_JSON = [] for segment in simple_segments: s", "1) df['address'] = new_addresses df['degree'] = new_degree return df def", "import approximate_polygon from PIL import Image, ImageDraw from utils.utils import", "image_name: str, export_file_path: str, exportPNG: bool = False, exportJSON: bool", "df['address'] = new_addresses df['degree'] = new_degree return df def avoidDiagonalEdges(address:", "segments, containing all the pixels on the way between each", "diagonal.keys(): if d in address: if not(diagonal[d][0] in address) and", "y, image.shape, ) raise AssertionError() # If the number of", "skeletonized image ''' assert len(road_network.shape) == 2, 'ERROR: road_network must", "for (r,c) in zip(rows, cols): if r > 0 and", "of segments, containing all the pixels on the way between", "pas possible de calculer la géolocalisation de son réseau filaire\".format(image_name))", "installer Homebrew:\\n', ' /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer", "path where the skeletonized image should be saved largest_component: if", "list, vectorized: np.ndarray, out_path: str): ''' Save a given set", "or exportSHP): simple_segments, full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length =", "import shapefile as shp from skimage.measure import approximate_polygon from PIL", "in white) path: path where the skeletonized image should be", "6] elif direction == 6: wrong_paths = [1, 5] elif", "'ERROR: road_network must be grayscale image' img = cv2.resize(road_network, (road_network.shape[1]//2,", "image' img = cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized", "if len(direction_set) != 1: end = True break direction =", "nodes coordinates (x, y) degree: degrees of the nodes (2=endpoint,", "the path, where the output bitmap image should be save", "for ind, node in df_nodes.iterrows(): for direct in node['address']: code", "image of the road network out_path: the path, where the", "str): ''' Save a given set of segments as a", "= False way = [(x, y)] # First iteration new_x,", "the nodes of the skeletonized image Output(s): way: list of", "= [] for way in ways: inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose()", "1, 2, 3, -, 5, 6, 7, 8}) image: skeletonized", "image.shape[1]-1: # Extract an 8-connected neighbourhood (col_neigh, row_neigh) = np.meshgrid(np.array([c-1,", "2, 'ERROR: road_network must be grayscale image' img = cv2.resize(road_network,", "in df_nodes.iterrows(): for direct in node['address']: code = str(node['x']) +", "< 254] = 0 road_network[road_network < 255/2] = 0 road_network[road_network", "x_, y_ = x-1, y+1 elif way == 3: x_,", "\\ should be comprised between 0 and 8, and !=", "= skeletonize(road_network, largest_component = True) nodes, degree, addresses = findNodes(vectorized)", "df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree'] !=", "= True return way, direction, nodes_grid[x, y] def findSegments(df_nodes: pd.DataFrame,", "> 100] = 255 vectorized[vectorized <= 100] = 0 if", "= nodes_grid.astype('int') for ind, node in df_nodes.iterrows(): for direct in", "Cast to int to index into image col_neigh, row_neigh =", "ImageMagick:\\n', ' brew install imagemagick') print('Pour installer Potrace: \\n', '", "direction_set[direction_set != 4] addresses.append(direction_set) nodes = np.asarray(nodes) return nodes, degree,", "largest_component = True) nodes, degree, addresses = findNodes(vectorized) if len(degree)", "8] elif direction == 2: wrong_paths = [3, 7] elif", "8] elif direction == 5: wrong_paths = [0, 6] elif", "skeletonized image of the road network min_length: min segment length", "[2, 8] elif direction == 5: wrong_paths = [0, 6]", "int = None): right, diagonal = [1, 3, 5, 7],", "= [1, 3] return wrong_paths direction = start_dir x, y", "str(way[-1][1]) + '_' + str(8-last_direct)) ways.append(way) if return_simple_ways: simple_ways =", "0 except: print(x, y, image.shape, ) raise AssertionError() # If", "in address: new_address.append(r) for d in diagonal.keys(): if d in", "def findSegments(df_nodes: pd.DataFrame, image: np.ndarray, min_length: int = 30, return_simple_ways:", "calculée. Par conséquent, \\ il n'est pas possible de calculer", "= np.asarray(nodes) return nodes, degree, addresses def cleanNodesEdges(df_nodes: pd.DataFrame): df", "start node y-coordinate start_dir: starting direction ({0, 1, 2, 3,", "str(y) + ',' + str(way) + '), way \\ should", "absoluteWay(x: int, y: int, way: int): if way == 0:", "in the road network skeleton image. Input(s): image: skeletonized image", "as shp from skimage.measure import approximate_polygon from PIL import Image,", "network skeleton image. Input(s): image: skeletonized image Output(s): nodes: array", "project_name, 'match' , 'primary', image_name + '.json')) as data: data", "False if len(direction_set) != 1: end = True break direction", "brew install imagemagick') print('Pour installer Potrace: \\n', ' brew install", "way == 6: x_, y_ = x+1, y-1 elif way", "start_dir x, y = start_x, start_y assert image[x, y] !=", "wrong_paths = [3, 7] elif direction == 3: wrong_paths =", "installer ImageMagick:\\n', ' brew install imagemagick') print('Pour installer Potrace: \\n',", "3], 2: [1, 5], 6: [3, 7], 8: [5, 7]}", "vectorized, min_length = 15, return_simple_ways = True) else: full_segments, nodes_grid", "way: list of pixel coordinates on the way direction: last", "1: end = True break direction = direction_set[0] new_x, new_y", "last_ds.append(direction_set) direction_set = direction_set[direction_set != (8-direction)] last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set,", "== 0: wrong_paths = [5, 7] elif direction == 1:", "= True) else: full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length =", "network. Input(s): segments: list of segments, containing all the pixels", "exportJSON: bool = False, exportSVG: bool = False, exportSHP: bool", "node, and stores the pixels on the way. Input(s): start_x:", "return simple_segments, full_segments, nodes_grid def toPNG(segments: list, vectorized: np.ndarray, out_path:", "for i in range(len(simple_ways)): w.line([simple_ways[i]]) w.record('01', i, '', '') w.close()", "',' + str(y) + ',' + str(way) + '), way", "segments as a bitmap image from the road network. Input(s):", "x-1, y+1 elif way == 3: x_, y_ = x,", "nationale de France (BnF) import cv2, thinning, os import numpy", "wired model. Input(s): road_network: black and white image of the", "255/2] = 255 vectorized = skeletonize(road_network, largest_component = True) nodes,", "!= 0, 'ERROR: 2nd point is not white' way.append((new_x, new_y))", "cv2, thinning, os import numpy as np import pandas as", "fonctionne que pour le format JSON actuellement.') else: simple_segments_JSON =", "exportSHP): simple_segments, full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length = 15,", "(labels == main_component).astype('uint8')*255 except: 'Warning: Skeletonization failed to apply largest_component", "30, return_simple_ways: bool = True): ''' Find all the road", "return_simple_ways = True) else: full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length", "export_file_path.replace('png', 'svg') os.system('convert ' + png_path + pnm_path) os.system('potrace '", "start_y: int, start_dir: int, image: np.ndarray, nodes_grid: np.ndarray): ''' Follow", "= [2, 8] elif direction == 5: wrong_paths = [0,", "exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name)) if exportSVG: print(\"\\nAvertissement: Si vous", "type int.') return x_, y_ def noTurnBack(direction: int): wrong_paths =", "y-1 elif way == 5: x_, y_ = x, y+1", "que pour le format JSON actuellement.') else: simple_segments_JSON = simple_segments", "svg_path) return simple_segments, full_segments, nodes_grid def toPNG(segments: list, vectorized: np.ndarray,", "address in df['address'].iteritems(): new_address = avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) + 1)", "Skipping.' cv2.imwrite(path, vectorized) return vectorized def findNodes(image: np.ndarray): ''' Find", "7: x_, y_ = x+1, y elif way == 8:", "False): assert (exportPNG or exportJSON or exportSVG or exportSHP) #", "if not((8-direction) in diagonal[d]): new_address.append(d) else: new_address.append(d) return new_address def", "= start_dir x, y = start_x, start_y assert image[x, y]", "print(x, y, image.shape, ) raise AssertionError() # If the number", "from the road network. Input(s): segments: list of segments, containing", "connectivity=8, stats=cv2.CC_STAT_AREA) stats = stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized =", "nodes: array of nodes coordinates (x, y) degree: degrees of", "the nodes (2=endpoint, 4=crossroads of 3 streets, 5=crossroads of 4", "''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name)) if exportSVG: print(\"\\nAvertissement: Si", "y]: end = True direction = 8-start_dir while not(end): if", "y] def findSegments(df_nodes: pd.DataFrame, image: np.ndarray, min_length: int = 30,", "11, 0) w.field('streetname', 'C', 41, 0) w.field('note', 'C', 32, 0)", "'ERROR: 2nd point is not white' way.append((new_x, new_y)) x, y", "direction == 7: wrong_paths = [0, 2] elif direction ==", "# For Bibliothèque nationale de France (BnF) import cv2, thinning,", "> 0 and c > 0 and r < image.shape[0]-1", "direction_set = direction_set[direction_set != wrong_path] wrong_paths_active = False if len(direction_set)", "+ '_' + str(direct) if not(code in done): way, last_direct,", "component will be kept Output(s): vectorized: skeletonized image ''' assert", "exportPNG: png_path = export_file_path else: png_path = os.path.join('workshop', 'thin.png') pnm_path", "way \\ should be comprised between 0 and 8, and", "return_simple_ways: if True, compute the Douglas-Peucker simple itinerary of each", "index into image col_neigh, row_neigh = col_neigh.astype('int'), row_neigh.astype('int') # Convert", "the road network out_path: the path, where the output bitmap", "shp.Writer(out_path) w.field('DeletionFlag', 'C', 1, 0) w.field('gid', 'N', 11, 0) w.field('streetname',", "assert len(road_network.shape) == 2, 'ERROR: road_network must be grayscale image'", "nodes nodes_grid: image containing all the nodes found in the", "coordinates on the way direction: last direction to reach the", "each couple of nodes nodes_grid: image containing all the nodes", "= 0 if largest_component: try: _, labels, stats, _ =", "str, exportPNG: bool = False, exportJSON: bool = False, exportSVG:", "= thinning.guo_hall_thinning(img) vectorized[vectorized > 100] = 255 vectorized[vectorized <= 100]", "8-connected neighbourhood (row_neigh, col_neigh) = np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1, y,", "-s -o ' + svg_path) return simple_segments, full_segments, nodes_grid def", "white' way.append((new_x, new_y)) x, y = new_x, new_y wrong_paths =", "list, direction: int = None): right, diagonal = [1, 3,", "nodes_grid def thinImage(image: np.ndarray, image_name: str, export_file_path: str, exportPNG: bool", "pixels on the way between each couple of nodes nodes_grid:", "absoluteWay(x, y, direction) way.append((new_x, new_y)) x, y = new_x, new_y", "end = True break direction = direction_set[0] new_x, new_y =", "main_component).astype('uint8')*255 except: 'Warning: Skeletonization failed to apply largest_component = True", "= [5, 7] elif direction == 1: wrong_paths = [6,", "of each segment and return it Output(s): (Optional)(simple_ways: the Douglas-Peucker", "jamais utilisé cette commande, \\ installez d'abord Homebrew, ImageMagick et", "(2=endpoint, 4=crossroads of 3 streets, 5=crossroads of 4 streets, etc.)", "M = np.asarray(data['M']) simple_segments_JSON = [] for segment in simple_segments:", "(BnF) import cv2, thinning, os import numpy as np import", "Image.MAX_IMAGE_PIXELS = 500000000 def skeletonize(road_network: np.ndarray, path: str = \"workshop/vectorized.png\",", "8}) image: skeletonized image of the road network nodes_grid: grid", "exportSHP) # Convert to B&W road_network = image.copy() road_network[road_network <", "via le terminal.\\n\") print('Pour installer Homebrew:\\n', ' /usr/bin/ruby -e \"$(curl", "or (n_neighbours >= 4): nodes.append((r, c)) degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood", "image Output(s): way: list of pixel coordinates on the way", "Input(s): road_network: black and white image of the road network", "itinerary of each segmenty) ways: list of segments, containing all", "2020, BackThen Maps # Coded by <NAME> https://github.com/RPetitpierre # For", "',' + str(way) + '), way \\ should be comprised", "image: np.ndarray, nodes_grid: np.ndarray): ''' Follow the path from one", "new_y if nodes_grid[x, y]: end = True else: end =", "direction_set = np.where(pix_neighbourhood == True)[0] last_ds = [wrong_paths] last_ds.append(direction_set) direction_set", "B&W road_network = image.copy() road_network[road_network < 254] = 0 road_network[road_network", "draw.line(coords, fill = 'black', width=0) bitmap.save(out_path) def toShapefile(simple_ways, out_path): w", "df def avoidDiagonalEdges(address: list, direction: int = None): right, diagonal", "simple itinerary of each segment and return it. Input(s): df_nodes:", "col_neigh = col_neigh.astype('int') row_neigh = row_neigh.astype('int') # Convert into a", "4=crossroads of 3 streets, 5=crossroads of 4 streets, etc.) addresses:", "Input(s): start_x: start node x-coordinate start_y: start node y-coordinate start_dir:", "254] = 0 road_network[road_network < 255/2] = 0 road_network[road_network >=", "road network out_path: the path, where the output bitmap image", "new_addresses, new_degree = [], [] for ind, address in df['address'].iteritems():", "and y < image.shape[1]-1: # Extract an 8-connected neighbourhood (row_neigh,", "index into image col_neigh = col_neigh.astype('int') row_neigh = row_neigh.astype('int') #", "!= 4] addresses.append(direction_set) nodes = np.asarray(nodes) return nodes, degree, addresses", "y and way should be of type int.') return x_,", "be grayscale image' img = cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized =", "np.asarray(data['M']) simple_segments_JSON = [] for segment in simple_segments: s =", "bitmap image should be save ''' canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png',", "streets, etc.) addresses: directions of the crossing roads, with regard", "pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel() != 0 except: print(x, y, image.shape,", "(degree == 2))): done.append(str(way[-1][0]) + '_' + str(way[-1][1]) + '_'", "Image, ImageDraw from utils.utils import * from utils.match import toLatLon", "list of nodes image: skeletonized image of the road network", "if exportPNG: png_path = export_file_path else: png_path = os.path.join('workshop', 'thin.png')", "ways = [], [] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape)", "Thinning/skeletonization of the road network image to a wired model.", "encore été calculée. Par conséquent, \\ il n'est pas possible", "and r < image.shape[0]-1 and c < image.shape[1]-1: # Extract", "neighbourhood (col_neigh, row_neigh) = np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1, r, r+1]))", "code = str(node['x']) + '_' + str(node['y']) + '_' +", "row['degree'] nodes_grid = nodes_grid.astype('int') for ind, node in df_nodes.iterrows(): for", "pandas as pd import shapefile as shp from skimage.measure import", "nodes_grid=nodes_grid) if not((len(way) <= min_length) and ((node['degree'] == 2) or", "simple_segments: s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:, 2:3].transpose()).tolist())", "if r in address: new_address.append(r) for d in diagonal.keys(): if", "if not(code in done): way, last_direct, degree = explorePath(start_x=node['x'], start_y=node['y'],", "exportPNG: toPNG(full_segments, vectorized, export_file_path) elif exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png'))", "= [6, 8] elif direction == 2: wrong_paths = [3,", "elif way == 1: x_, y_ = x-1, y elif", "x+1, y elif way == 8: x_, y_ = x+1,", "0, 'ERROR: start point is not white' end = False", "non-zero (rows, cols) = np.nonzero(img) nodes, degree, addresses = [],", "for non-zero locations pix_neighbourhood = img[row_neigh, col_neigh].ravel() != 0 #", "to B&W road_network = image.copy() road_network[road_network < 254] = 0", "r in right: if r in address: new_address.append(r) for d", "list of pixel coordinates on the way direction: last direction", "the nodes in the road network skeleton image. Input(s): image:", "way should be of type int.') return x_, y_ def", "zip(rows, cols): if r > 0 and c > 0", "= (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap = Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap)", "image: skeletonized image of the road network nodes_grid: grid of", "image_name)) if exportSVG: print(\"\\nAvertissement: Si vous n'avez jamais utilisé cette", "last direction to reach the 2nd node nodes_grid[x, y]: degree", "from utils.match import toLatLon Image.MAX_IMAGE_PIXELS = 500000000 def skeletonize(road_network: np.ndarray,", "of non-zero locations equals 2, add this to our list", "int = 30, return_simple_ways: bool = True): ''' Find all", "else: end = True return way, direction, nodes_grid[x, y] def", "export_file_path else: png_path = os.path.join('workshop', 'thin.png') pnm_path = os.path.join('workshop', 'thin.pnm')", "x_, y_ = x-1, y elif way == 2: x_,", "+ png_path + pnm_path) os.system('potrace ' + pnm_path + '", "toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name)) if exportSVG: print(\"\\nAvertissement: Si vous n'avez", "'N', 11, 0) w.field('streetname', 'C', 41, 0) w.field('note', 'C', 32,", "!= 4] last_ds.append(direction_set) direction_set = direction_set[direction_set != (8-direction)] last_ds.append(direction_set) direction_set", "vectorized, os.path.join('workshop', 'thin.png')) if geoloc: if exportJSON: project_name = getProjectName()", "2, 3, -, 5, 6, 7, 8}) image: skeletonized image", "direction until the next node, and stores the pixels on", "nodes = np.asarray(nodes) return nodes, degree, addresses def cleanNodesEdges(df_nodes: pd.DataFrame):", "= 15, return_simple_ways = True) else: full_segments, nodes_grid = findSegments(df_nodes,", "image.shape[0]-1 and y < image.shape[1]-1: # Extract an 8-connected neighbourhood", "regard to the node ''' img = image.copy() # Find", "cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree'] != 3] if (exportJSON or exportSHP):", "nodes_grid[row['x'], row['y']] = row['degree'] nodes_grid = nodes_grid.astype('int') for ind, node", "in done): way, last_direct, degree = explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img,", "the skeletonized image Output(s): way: list of pixel coordinates on", "labels, stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats = stats[1:]", "= np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1, y, y+1])) # Cast to", "[5, 7] elif direction == 1: wrong_paths = [6, 8]", "'thin.png') pnm_path = os.path.join('workshop', 'thin.pnm') svg_path = export_file_path.replace('png', 'svg') os.system('convert", "If the number of non-zero locations equals 2, add this", "in segments: coords = [] for point in segment: coords.append((point[1],", "image to a wired model. Input(s): road_network: black and white", "+ '_' + str(node['y']) + '_' + str(direct) if not(code", "project_name = getProjectName() try: with open(os.path.join('save', project_name, 'match' , 'primary',", "été calculée. Par conséquent, \\ il n'est pas possible de", "image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways, ways, nodes_grid else: return ways,", "x < image.shape[0]-1 and y < image.shape[1]-1: # Extract an", "should be saved largest_component: if True, only the largest road", "elif direction == 2: wrong_paths = [3, 7] elif direction", "True): ''' Find all the road segments in the network.", "0 road_network[road_network < 255/2] = 0 road_network[road_network >= 255/2] =", "= False) simple_segments = [] if exportPNG: toPNG(full_segments, vectorized, export_file_path)", "for wrong_path in wrong_paths: direction_set = direction_set[direction_set != wrong_path] wrong_paths_active", "addresses = findNodes(vectorized) if len(degree) < 0: return [], [],", "cv2.imwrite(path, vectorized) return vectorized def findNodes(image: np.ndarray): ''' Find the", "way between each couple of nodes nodes_grid: image containing all", "wrong_paths = [] if direction == 0: wrong_paths = [5,", "> 0 and r < image.shape[0]-1 and c < image.shape[1]-1:", "0 and y > 0 and x < image.shape[0]-1 and", "in node['address']: code = str(node['x']) + '_' + str(node['y']) +", "direction_set[direction_set != 4] last_ds.append(direction_set) direction_set = direction_set[direction_set != (8-direction)] last_ds.append(direction_set)", "new_y] != 0, 'ERROR: 2nd point is not white' way.append((new_x,", "2) or (n_neighbours >= 4): nodes.append((r, c)) degree.append(n_neighbours) direction_set =", "[], [] for ind, address in df['address'].iteritems(): new_address = avoidDiagonalEdges(address)", "and y > 0 and x < image.shape[0]-1 and y", "image=img, nodes_grid=nodes_grid) if not((len(way) <= min_length) and ((node['degree'] == 2)", "= [] if exportPNG: toPNG(full_segments, vectorized, export_file_path) elif exportSVG: toPNG(full_segments,", "direction = 8-start_dir while not(end): if x > 0 and", "4] addresses.append(direction_set) nodes = np.asarray(nodes) return nodes, degree, addresses def", "x-1, y-1 elif way == 1: x_, y_ = x-1,", "thinning, os import numpy as np import pandas as pd", "if the segment is terminal return_simple_ways: if True, compute the", "it Output(s): (Optional)(simple_ways: the Douglas-Peucker simple itinerary of each segmenty)", "'C', 1, 0) w.field('gid', 'N', 11, 0) w.field('streetname', 'C', 41,", "import toLatLon Image.MAX_IMAGE_PIXELS = 500000000 def skeletonize(road_network: np.ndarray, path: str", "and ((node['degree'] == 2) or (degree == 2))): done.append(str(way[-1][0]) +", "nodes_grid else: return ways, nodes_grid def thinImage(image: np.ndarray, image_name: str,", "image ''' assert len(road_network.shape) == 2, 'ERROR: road_network must be", "df['address'].iteritems(): new_address = avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) + 1) df['address'] =", "in address): if direction != None: if not((8-direction) in diagonal[d]):", "' /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n', '", "c > 0 and r < image.shape[0]-1 and c <", "int to index into image col_neigh = col_neigh.astype('int') row_neigh =", "[] for segment in simple_segments: s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:,", "the arrival node ''' def absoluteWay(x: int, y: int, way:", "new_x, new_y = absoluteWay(x, y, direction) way.append((new_x, new_y)) x, y", "(col_neigh, row_neigh) = np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1, r, r+1])) #", "image containing all the nodes found in the image and", "os.path.join('workshop', 'thin.png')) if geoloc: if exportJSON: project_name = getProjectName() try:", "== 8: x_, y_ = x+1, y+1 else: raise AttributeError('Parameters", "r in address: new_address.append(r) for d in diagonal.keys(): if d", "1: wrong_paths = [6, 8] elif direction == 2: wrong_paths", "exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name)) if exportSVG:", "15, return_simple_ways = True) else: full_segments, nodes_grid = findSegments(df_nodes, vectorized,", "into image col_neigh = col_neigh.astype('int') row_neigh = row_neigh.astype('int') # Convert", "wrong_paths = [1, 3] return wrong_paths direction = start_dir x,", "# Extract an 8-connected neighbourhood (row_neigh, col_neigh) = np.meshgrid(np.array([x-1, x,", "min_length: int = 30, return_simple_ways: bool = True): ''' Find", "locations that are non-zero (rows, cols) = np.nonzero(img) nodes, degree,", "!= wrong_path] wrong_paths_active = False if len(direction_set) != 1: end", "except: print(\"La géolocalisation de l'image {} n'a pas encore été", "possible de calculer la géolocalisation de son réseau filaire\".format(image_name)) simple_segments_JSON", "vous n'avez jamais utilisé cette commande, \\ installez d'abord Homebrew,", "None): right, diagonal = [1, 3, 5, 7], {0: [1,", "Douglas-Peucker simple itinerary of each segment and return it. Input(s):", "True return way, direction, nodes_grid[x, y] def findSegments(df_nodes: pd.DataFrame, image:", "segment length if the segment is terminal return_simple_ways: if True,", "x_, y_ = x+1, y elif way == 8: x_,", "= False, exportJSON: bool = False, exportSVG: bool = False,", "= avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) + 1) df['address'] = new_addresses df['degree']", "# Cast to int to index into image col_neigh =", "6: x_, y_ = x+1, y-1 elif way == 7:", "direction == 2: wrong_paths = [3, 7] elif direction ==", "Save a given set of segments as a bitmap image", "if way == 0: x_, y_ = x-1, y-1 elif", "'svg') os.system('convert ' + png_path + pnm_path) os.system('potrace ' +", "new_y)) x, y = new_x, new_y wrong_paths = noTurnBack(direction) wrong_paths_active", "'ERROR: start point is not white' end = False way", "crossing roads, with regard to the node ''' img =", "the Douglas-Peucker simple itinerary of each segment and return it", "apply largest_component = True param. Skipping.' cv2.imwrite(path, vectorized) return vectorized", "else: png_path = os.path.join('workshop', 'thin.png') pnm_path = os.path.join('workshop', 'thin.pnm') svg_path", "{} n'a pas encore été calculée. Par conséquent, \\ il", "road network min_length: min segment length if the segment is", "os.system('convert ' + png_path + pnm_path) os.system('potrace ' + pnm_path", "return way, direction, nodes_grid[x, y] def findSegments(df_nodes: pd.DataFrame, image: np.ndarray,", "0 if largest_component: try: _, labels, stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(),", "ways, nodes_grid else: return ways, nodes_grid def thinImage(image: np.ndarray, image_name:", "elif way == 7: x_, y_ = x+1, y elif", "4): nodes.append((r, c)) degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood == True)[0] direction_set", "6, 7, 8}) image: skeletonized image of the road network", "15, return_simple_ways = False) simple_segments = [] if exportPNG: toPNG(full_segments,", "try: pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel() != 0 except: print(x, y,", "utilisé cette commande, \\ installez d'abord Homebrew, ImageMagick et Potrace", "c < image.shape[1]-1: # Extract an 8-connected neighbourhood (col_neigh, row_neigh)", "simple_segments else: print('La géolocalisation du réseau filaire ne fonctionne que", "y) degree: degrees of the nodes (2=endpoint, 4=crossroads of 3", "terminal.\\n\") print('Pour installer Homebrew:\\n', ' /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"')", "node in df_nodes.iterrows(): for direct in node['address']: code = str(node['x'])", "for segment in simple_segments: s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2])", "[] if exportPNG: toPNG(full_segments, vectorized, export_file_path) elif exportSVG: toPNG(full_segments, vectorized,", "= False): assert (exportPNG or exportJSON or exportSVG or exportSHP)", "image.shape, ) raise AssertionError() # If the number of non-zero", "bitmap = Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap) for segment in segments:", "pnm_path + ' -s -o ' + svg_path) return simple_segments,", "[], [] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape) for ind,", "of nodes nodes_grid: image containing all the nodes found in", "= start_x, start_y assert image[x, y] != 0, 'ERROR: start", "c)) degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood == True)[0] direction_set = direction_set[direction_set", "[0, 6] elif direction == 6: wrong_paths = [1, 5]", "df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape) for ind, row in df_nodes[['x', 'y',", "as data: data = json.load(data) M = np.asarray(data['M']) simple_segments_JSON =", "vectorized: skeletonized image of the road network out_path: the path,", "= x+1, y elif way == 8: x_, y_ =", "return_simple_ways: simple_ways = [] for way in ways: inv_way =", "open(os.path.join('save', project_name, 'match' , 'primary', image_name + '.json')) as data:", "way, last_direct, degree = explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid) if", "or exportJSON or exportSVG or exportSHP) # Convert to B&W", "between 0 and 8, and != 4. x, y and", "str(node['x']) + '_' + str(node['y']) + '_' + str(direct) if", "== 7: x_, y_ = x+1, y elif way ==", "if nodes_grid[x, y]: end = True direction = 8-start_dir while", "wrong_paths = [2, 8] elif direction == 5: wrong_paths =", "''' Follow the path from one given start node and", "!= 0 # If the number of non-zero locations equals", "on the way direction: last direction to reach the 2nd", "(n_neighbours >= 4): nodes.append((r, c)) degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood ==", "locations equals 2, add this to our list of coordinates", "containing all the pixels on the way between each couple", "direction)) last_ds.append(direction_set) if wrong_paths_active: for wrong_path in wrong_paths: direction_set =", "in the network. Keep the ones that are longer than", "png_path = export_file_path else: png_path = os.path.join('workshop', 'thin.png') pnm_path =", "x, y-1 elif way == 5: x_, y_ = x,", "True) else: full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length = 15,", "way. Input(s): start_x: start node x-coordinate start_y: start node y-coordinate", "ways: inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways, ways,", "bool = False): assert (exportPNG or exportJSON or exportSVG or", "avoidDiagonalEdges(address: list, direction: int = None): right, diagonal = [1,", "'y': nodes[:,1], 'degree': degree, 'address': addresses }) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True)", "save ''' canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap = Image.open('workshop/canvas.png')", "32, 0) for i in range(len(simple_ways)): w.line([simple_ways[i]]) w.record('01', i, '',", "if largest_component: try: _, labels, stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8,", ", 'primary', image_name + '.json')) as data: data = json.load(data)", "exportPNG: bool = False, exportJSON: bool = False, exportSVG: bool", "numpy as np import pandas as pd import shapefile as", "degree, addresses def cleanNodesEdges(df_nodes: pd.DataFrame): df = df_nodes.copy() new_addresses, new_degree", "stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats = stats[1:] main_component", "given length or non-terminal. Optionally, compute the Douglas-Peucker simple itinerary", "x_, y_ def noTurnBack(direction: int): wrong_paths = [] if direction", "= x-1, y elif way == 2: x_, y_ =", "direction != None: if not((8-direction) in diagonal[d]): new_address.append(d) else: new_address.append(d)", "'C', 41, 0) w.field('note', 'C', 32, 0) for i in", "neighbourhood (row_neigh, col_neigh) = np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1, y, y+1]))", "= simple_segments else: print('La géolocalisation du réseau filaire ne fonctionne", "elif way == 2: x_, y_ = x-1, y+1 elif", "or non-terminal. Optionally, compute the Douglas-Peucker simple itinerary of each", "nodes_grid = findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways = False)", "the segment is terminal return_simple_ways: if True, compute the Douglas-Peucker", "direction: last direction to reach the 2nd node nodes_grid[x, y]:", "brew install potrace\\n') if exportPNG: png_path = export_file_path else: png_path", "number of non-zero locations equals 2, add this to our", "coordinates (x, y) degree: degrees of the nodes (2=endpoint, 4=crossroads", "= [] for point in segment: coords.append((point[1], point[0])) draw.line(coords, fill", "direction_set[0] new_x, new_y = absoluteWay(x, y, direction) way.append((new_x, new_y)) x,", "== 2))): done.append(str(way[-1][0]) + '_' + str(way[-1][1]) + '_' +", "exportJSON: with open(export_file_path.replace('png', 'json'), 'w') as outfile: json.dump(simple_segments_JSON, outfile) if", "3, 5, 7], {0: [1, 3], 2: [1, 5], 6:", "nodes_grid = np.zeros(image.shape) for ind, row in df_nodes[['x', 'y', 'degree']].iterrows():", "= (labels == main_component).astype('uint8')*255 except: 'Warning: Skeletonization failed to apply", "way == 8: x_, y_ = x+1, y+1 else: raise", "= np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if wrong_paths_active: for wrong_path in wrong_paths:", "direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if wrong_paths_active: for wrong_path in", "8: x_, y_ = x+1, y+1 else: raise AttributeError('Parameters invalid:", "of pixel coordinates on the way direction: last direction to", "cv2.imwrite('workshop/canvas.png', canvas); bitmap = Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap) for segment", "y_ = x-1, y elif way == 2: x_, y_", "vectorized: skeletonized image ''' assert len(road_network.shape) == 2, 'ERROR: road_network", "0: x_, y_ = x-1, y-1 elif way == 1:", "done, ways = [], [] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid =", "nodes, degree, addresses = findNodes(vectorized) if len(degree) < 0: return", "and return it. Input(s): df_nodes: list of nodes image: skeletonized", "segmenty) ways: list of segments, containing all the pixels on", "to index into image col_neigh, row_neigh = col_neigh.astype('int'), row_neigh.astype('int') #", "filaire ne fonctionne que pour le format JSON actuellement.') else:", "(exportPNG or exportJSON or exportSVG or exportSHP) # Convert to", "degree.append(n_neighbours) direction_set = np.where(pix_neighbourhood == True)[0] direction_set = direction_set[direction_set !=", "image should be save ''' canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas);", "for segment in segments: coords = [] for point in", ">= 255/2] = 255 vectorized = skeletonize(road_network, largest_component = True)", "[], np.zeros((image.shape[1], image.shape[0])) df_nodes = pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1], 'degree':", "break direction = direction_set[0] new_x, new_y = absoluteWay(x, y, direction)", "img[row_neigh, col_neigh].ravel() != 0 # If the number of non-zero", "= x+1, y-1 elif way == 7: x_, y_ =", "== True)[0] direction_set = direction_set[direction_set != 4] addresses.append(direction_set) nodes =", "pnm_path) os.system('potrace ' + pnm_path + ' -s -o '", "of each segmenty) ways: list of segments, containing all the", "x, y+1 elif way == 6: x_, y_ = x+1,", "containing all the nodes found in the image and their", "and not(diagonal[d][1] in address): if direction != None: if not((8-direction)", "new_address.append(r) for d in diagonal.keys(): if d in address: if", "3] if (exportJSON or exportSHP): simple_segments, full_segments, nodes_grid = findSegments(df_nodes,", "node ''' def absoluteWay(x: int, y: int, way: int): if", "road network. Input(s): segments: list of segments, containing all the", "else: raise AttributeError('Parameters invalid: (' + str(x) + ',' +", "wrong_paths = noTurnBack(direction) wrong_paths_active = True if nodes_grid[x, y]: end", "if (n_neighbours == 2) or (n_neighbours >= 4): nodes.append((r, c))", "= image.copy() done, ways = [], [] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True)", "[0, 2] elif direction == 8: wrong_paths = [1, 3]", "y elif way == 2: x_, y_ = x-1, y+1", "findNodes(image: np.ndarray): ''' Find the nodes in the road network", "= np.where(pix_neighbourhood == True)[0] last_ds = [wrong_paths] last_ds.append(direction_set) direction_set =", "vectorized, export_file_path) elif exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png')) if geoloc:", "[] for r in right: if r in address: new_address.append(r)", "direction == 0: wrong_paths = [5, 7] elif direction ==", "= True) nodes, degree, addresses = findNodes(vectorized) if len(degree) <", "to int to index into image col_neigh = col_neigh.astype('int') row_neigh", "réseau filaire ne fonctionne que pour le format JSON actuellement.')", "as a bitmap image from the road network. Input(s): segments:", "y: int, way: int): if way == 0: x_, y_", "to a wired model. Input(s): road_network: black and white image", "the way. Input(s): start_x: start node x-coordinate start_y: start node", "assert image[new_x, new_y] != 0, 'ERROR: 2nd point is not", "= np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways, ways, nodes_grid else:", "col_neigh].ravel() != 0 # If the number of non-zero locations", "itinerary of each segment and return it Output(s): (Optional)(simple_ways: the", "= simple_segments if exportJSON: with open(export_file_path.replace('png', 'json'), 'w') as outfile:", "np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if wrong_paths_active: for wrong_path in wrong_paths: direction_set", "Potrace via le terminal.\\n\") print('Pour installer Homebrew:\\n', ' /usr/bin/ruby -e", "for r in right: if r in address: new_address.append(r) for", "Optionally, compute the Douglas-Peucker simple itinerary of each segment and", "1: x_, y_ = x-1, y elif way == 2:", "add this to our list of coordinates n_neighbours = np.sum(pix_neighbourhood)", "== 5: wrong_paths = [0, 6] elif direction == 6:", "simple_segments_JSON = simple_segments if exportJSON: with open(export_file_path.replace('png', 'json'), 'w') as", "all the road segments in the network. Keep the ones", "if exportPNG: toPNG(full_segments, vectorized, export_file_path) elif exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop',", "Extract an 8-connected neighbourhood (col_neigh, row_neigh) = np.meshgrid(np.array([c-1, c, c+1]),", "should be comprised between 0 and 8, and != 4.", "= np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood == True)[0] last_ds = [wrong_paths]", "new_y = absoluteWay(x, y, direction) way.append((new_x, new_y)) x, y =", "len(road_network.shape) == 2, 'ERROR: road_network must be grayscale image' img", "grayscale image' img = cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img)", "if exportSVG: print(\"\\nAvertissement: Si vous n'avez jamais utilisé cette commande,", "addresses = [], [], [] for (r,c) in zip(rows, cols):", ":2]) + M[:, 2:3].transpose()).tolist()) except: print(\"La géolocalisation de l'image {}", "min_length = 15, return_simple_ways = True) else: full_segments, nodes_grid =", "y_ = x, y+1 elif way == 6: x_, y_", "getProjectName() try: with open(os.path.join('save', project_name, 'match' , 'primary', image_name +", "+ '_' + str(way[-1][1]) + '_' + str(8-last_direct)) ways.append(way) if", "exportSVG or exportSHP) # Convert to B&W road_network = image.copy()", "Output(s): nodes: array of nodes coordinates (x, y) degree: degrees", "pixels on the way between each couple of nodes vectorized:", "Potrace: \\n', ' brew install potrace\\n') if exportPNG: png_path =", "pd.DataFrame, image: np.ndarray, min_length: int = 30, return_simple_ways: bool =", "if nodes_grid[x, y]: end = True else: end = True", "41, 0) w.field('note', 'C', 32, 0) for i in range(len(simple_ways)):", "[] if direction == 0: wrong_paths = [5, 7] elif", "nodes vectorized: skeletonized image of the road network out_path: the", "str(8-last_direct)) ways.append(way) if return_simple_ways: simple_ways = [] for way in", "(r,c) in zip(rows, cols): if r > 0 and c", "ImageMagick et Potrace via le terminal.\\n\") print('Pour installer Homebrew:\\n', '", "np.ndarray, min_length: int = 30, return_simple_ways: bool = True): '''", "Output(s): way: list of pixel coordinates on the way direction:", "int, start_y: int, start_dir: int, image: np.ndarray, nodes_grid: np.ndarray): '''", "== 6: x_, y_ = x+1, y-1 elif way ==", "y, direction) assert image[new_x, new_y] != 0, 'ERROR: 2nd point", "last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if wrong_paths_active: for wrong_path", "Output(s): (Optional)(simple_ways: the Douglas-Peucker simple itinerary of each segmenty) ways:", "[3, 7] elif direction == 3: wrong_paths = [2, 8]", "and x < image.shape[0]-1 and y < image.shape[1]-1: # Extract", "direction_set = direction_set[direction_set != (8-direction)] last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction))", "else: new_address.append(d) return new_address def explorePath(start_x: int, start_y: int, start_dir:", "simple itinerary of each segmenty) ways: list of segments, containing", "road segments in the network. Keep the ones that are", "Input(s): image: skeletonized image Output(s): nodes: array of nodes coordinates", "should be save ''' canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap", "conséquent, \\ il n'est pas possible de calculer la géolocalisation", "open(export_file_path.replace('png', 'json'), 'w') as outfile: json.dump(simple_segments_JSON, outfile) if exportSHP: os.makedirs(export_file_path.replace('.png',", "equals 2, add this to our list of coordinates n_neighbours", "start point is not white' end = False way =", "# Find row and column locations that are non-zero (rows,", "True, compute the Douglas-Peucker simple itinerary of each segment and", "road_network[road_network < 255/2] = 0 road_network[road_network >= 255/2] = 255", "Homebrew:\\n', ' /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n',", "start node and direction until the next node, and stores", "direction_set = direction_set[direction_set != 4] addresses.append(direction_set) nodes = np.asarray(nodes) return", "2))): done.append(str(way[-1][0]) + '_' + str(way[-1][1]) + '_' + str(8-last_direct))", "-e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n', ' brew install", "# If the number of non-zero locations equals 2, add", "new_address.append(d) return new_address def explorePath(start_x: int, start_y: int, start_dir: int,", "= True direction = 8-start_dir while not(end): if x >", "return new_address def explorePath(start_x: int, start_y: int, start_dir: int, image:", "for way in ways: inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist())", "w = shp.Writer(out_path) w.field('DeletionFlag', 'C', 1, 0) w.field('gid', 'N', 11,", "= new_addresses df['degree'] = new_degree return df def avoidDiagonalEdges(address: list,", "''' def absoluteWay(x: int, y: int, way: int): if way", "\\ installez d'abord Homebrew, ImageMagick et Potrace via le terminal.\\n\")", "= False, exportSHP: bool = False, geoloc: bool = False):", "Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap) for segment in segments: coords =", "failed to apply largest_component = True param. Skipping.' cv2.imwrite(path, vectorized)", "0 and 8, and != 4. x, y and way", "or (degree == 2))): done.append(str(way[-1][0]) + '_' + str(way[-1][1]) +", "\"workshop/vectorized.png\", largest_component: bool = False): ''' Thinning/skeletonization of the road", "0 and c > 0 and r < image.shape[0]-1 and", "network image to a wired model. Input(s): road_network: black and", "is not white' way.append((new_x, new_y)) x, y = new_x, new_y", "the ones that are longer than a given length or", "0 and r < image.shape[0]-1 and c < image.shape[1]-1: #", "AttributeError('Parameters invalid: (' + str(x) + ',' + str(y) +", "7]} new_address = [] for r in right: if r", "= [] for segment in simple_segments: s = np.asarray([2*np.asarray(segment)[:,0], image.shape[0]-(2*np.asarray(segment)[:,1])]).T", "addresses }) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes) df_nodes =", "param. Skipping.' cv2.imwrite(path, vectorized) return vectorized def findNodes(image: np.ndarray): '''", "check for non-zero locations try: pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel() !=", "Par conséquent, \\ il n'est pas possible de calculer la", "True, only the largest road network component will be kept", "with open(os.path.join('save', project_name, 'match' , 'primary', image_name + '.json')) as", "def absoluteWay(x: int, y: int, way: int): if way ==", "0) w.field('gid', 'N', 11, 0) w.field('streetname', 'C', 41, 0) w.field('note',", "image[x, y] != 0, 'ERROR: start point is not white'", "import numpy as np import pandas as pd import shapefile", "is not white' end = False way = [(x, y)]", "stats=cv2.CC_STAT_AREA) stats = stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels", "non-zero locations pix_neighbourhood = img[row_neigh, col_neigh].ravel() != 0 # If", "row['y']] = row['degree'] nodes_grid = nodes_grid.astype('int') for ind, node in", "x-1, y elif way == 2: x_, y_ = x-1,", "Coded by <NAME> https://github.com/RPetitpierre # For Bibliothèque nationale de France", "data = json.load(data) M = np.asarray(data['M']) simple_segments_JSON = [] for", "arrival node ''' def absoluteWay(x: int, y: int, way: int):", "x+1, y+1 else: raise AttributeError('Parameters invalid: (' + str(x) +", "end = True direction = 8-start_dir while not(end): if x", "shapefile as shp from skimage.measure import approximate_polygon from PIL import", "pour le format JSON actuellement.') else: simple_segments_JSON = simple_segments if", "0 # If the number of non-zero locations equals 2,", "road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized > 100] = 255 vectorized[vectorized", "df_nodes = pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1], 'degree': degree, 'address': addresses", "in segment: coords.append((point[1], point[0])) draw.line(coords, fill = 'black', width=0) bitmap.save(out_path)", "wrong_paths_active: for wrong_path in wrong_paths: direction_set = direction_set[direction_set != wrong_path]", "raise AttributeError('Parameters invalid: (' + str(x) + ',' + str(y)", "Extract an 8-connected neighbourhood (row_neigh, col_neigh) = np.meshgrid(np.array([x-1, x, x+1]),", "'address': addresses }) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes) df_nodes", "image: skeletonized image Output(s): nodes: array of nodes coordinates (x,", "point in segment: coords.append((point[1], point[0])) draw.line(coords, fill = 'black', width=0)", "all the nodes found in the image and their degree", "x, y and way should be of type int.') return", "not(code in done): way, last_direct, degree = explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct,", "cette commande, \\ installez d'abord Homebrew, ImageMagick et Potrace via", "> 0 and x < image.shape[0]-1 and y < image.shape[1]-1:", "+ str(x) + ',' + str(y) + ',' + str(way)", "the road network. Input(s): segments: list of segments, containing all", "grid of the nodes of the skeletonized image Output(s): way:", "on the way between each couple of nodes vectorized: skeletonized", "network. Keep the ones that are longer than a given", "vectorized def findNodes(image: np.ndarray): ''' Find the nodes in the", "col_neigh) = np.meshgrid(np.array([x-1, x, x+1]), np.array([y-1, y, y+1])) # Cast", "road network nodes_grid: grid of the nodes of the skeletonized", "du réseau filaire ne fonctionne que pour le format JSON", "= cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized > 100]", "True param. Skipping.' cv2.imwrite(path, vectorized) return vectorized def findNodes(image: np.ndarray):", "image.shape[0])) df_nodes = pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1], 'degree': degree, 'address':", "y)] # First iteration new_x, new_y = absoluteWay(x, y, direction)", "the pixels on the way between each couple of nodes", "return [], [], np.zeros((image.shape[1], image.shape[0])) df_nodes = pd.DataFrame({'x': nodes[:,0], 'y':", "[] for (r,c) in zip(rows, cols): if r > 0", "4. x, y and way should be of type int.')", "os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name)) if exportSVG: print(\"\\nAvertissement:", "'thin.png')) if geoloc: if exportJSON: project_name = getProjectName() try: with", "length if the segment is terminal return_simple_ways: if True, compute", "or exportSHP) # Convert to B&W road_network = image.copy() road_network[road_network", "segment is terminal return_simple_ways: if True, compute the Douglas-Peucker simple", "of nodes image: skeletonized image of the road network min_length:", "the road network min_length: min segment length if the segment", "nodes image: skeletonized image of the road network min_length: min", "False, exportSHP: bool = False, geoloc: bool = False): assert", "will be kept Output(s): vectorized: skeletonized image ''' assert len(road_network.shape)", "if d in address: if not(diagonal[d][0] in address) and not(diagonal[d][1]", "True else: end = True return way, direction, nodes_grid[x, y]", "min_length) and ((node['degree'] == 2) or (degree == 2))): done.append(str(way[-1][0])", "str(node['y']) + '_' + str(direct) if not(code in done): way,", "[1, 5], 6: [3, 7], 8: [5, 7]} new_address =", "min segment length if the segment is terminal return_simple_ways: if", "not white' way.append((new_x, new_y)) x, y = new_x, new_y wrong_paths", "imagemagick') print('Pour installer Potrace: \\n', ' brew install potrace\\n') if", "for d in diagonal.keys(): if d in address: if not(diagonal[d][0]", "(n_neighbours == 2) or (n_neighbours >= 4): nodes.append((r, c)) degree.append(n_neighbours)", "= df_nodes.copy() new_addresses, new_degree = [], [] for ind, address", "# Convert into a single 1D array and check for", "canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap = Image.open('workshop/canvas.png') draw =", "Convert to B&W road_network = image.copy() road_network[road_network < 254] =", "our list of coordinates n_neighbours = np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood", "list of coordinates n_neighbours = np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood ==", "segment and return it Output(s): (Optional)(simple_ways: the Douglas-Peucker simple itinerary", "and return it Output(s): (Optional)(simple_ways: the Douglas-Peucker simple itinerary of", "Skeletonization failed to apply largest_component = True param. Skipping.' cv2.imwrite(path,", "image.copy() done, ways = [], [] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid", "new_x, new_y wrong_paths = noTurnBack(direction) wrong_paths_active = True if nodes_grid[x,", "for point in segment: coords.append((point[1], point[0])) draw.line(coords, fill = 'black',", "except: 'Warning: Skeletonization failed to apply largest_component = True param.", "last_ds.append(direction_set) direction_set = direction_set[direction_set != 4] last_ds.append(direction_set) direction_set = direction_set[direction_set", "nodes[:,0], 'y': nodes[:,1], 'degree': degree, 'address': addresses }) df_nodes =", "y]: end = True else: end = True return way,", "couple of nodes nodes_grid: image containing all the nodes found", "couple of nodes vectorized: skeletonized image of the road network", "simple_segments, full_segments, nodes_grid def toPNG(segments: list, vectorized: np.ndarray, out_path: str):", "segment: coords.append((point[1], point[0])) draw.line(coords, fill = 'black', width=0) bitmap.save(out_path) def", "start_dir=direct, image=img, nodes_grid=nodes_grid) if not((len(way) <= min_length) and ((node['degree'] ==", "'degree': degree, 'address': addresses }) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes =", "== 3: wrong_paths = [2, 8] elif direction == 5:", "= getProjectName() try: with open(os.path.join('save', project_name, 'match' , 'primary', image_name", "'degree']].iterrows(): nodes_grid[row['x'], row['y']] = row['degree'] nodes_grid = nodes_grid.astype('int') for ind,", "image col_neigh = col_neigh.astype('int') row_neigh = row_neigh.astype('int') # Convert into", "255/2] = 0 road_network[road_network >= 255/2] = 255 vectorized =", "of coordinates n_neighbours = np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood == True)[0]", "''' Find all the road segments in the network. Keep", "JSON actuellement.') else: simple_segments_JSON = simple_segments if exportJSON: with open(export_file_path.replace('png',", "def explorePath(start_x: int, start_y: int, start_dir: int, image: np.ndarray, nodes_grid:", "(road_network.shape[1]//2, road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized > 100] = 255", "white) path: path where the skeletonized image should be saved", "address): if direction != None: if not((8-direction) in diagonal[d]): new_address.append(d)", "= x+1, y+1 else: raise AttributeError('Parameters invalid: (' + str(x)", "road_network[road_network >= 255/2] = 255 vectorized = skeletonize(road_network, largest_component =", "on the way between each couple of nodes nodes_grid: image", "network (streets in white) path: path where the skeletonized image", "the pixels on the way. Input(s): start_x: start node x-coordinate", "it. Input(s): df_nodes: list of nodes image: skeletonized image of", "the Douglas-Peucker simple itinerary of each segmenty) ways: list of", "+ str(way[-1][1]) + '_' + str(8-last_direct)) ways.append(way) if return_simple_ways: simple_ways", "[] for ind, address in df['address'].iteritems(): new_address = avoidDiagonalEdges(address) new_addresses.append(new_address)", "= False, geoloc: bool = False): assert (exportPNG or exportJSON", "length or non-terminal. Optionally, compute the Douglas-Peucker simple itinerary of", "point[0])) draw.line(coords, fill = 'black', width=0) bitmap.save(out_path) def toShapefile(simple_ways, out_path):", "5], 6: [3, 7], 8: [5, 7]} new_address = []", "try: _, labels, stats, _ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats", "elif exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png')) if geoloc: if exportJSON:", "pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1], 'degree': degree, 'address': addresses }) df_nodes", "from one given start node and direction until the next", "wrong_path] wrong_paths_active = False if len(direction_set) != 1: end =", "(' + str(x) + ',' + str(y) + ',' +", "compute the Douglas-Peucker simple itinerary of each segment and return", "right, diagonal = [1, 3, 5, 7], {0: [1, 3],", "= shp.Writer(out_path) w.field('DeletionFlag', 'C', 1, 0) w.field('gid', 'N', 11, 0)", "print('Pour installer ImageMagick:\\n', ' brew install imagemagick') print('Pour installer Potrace:", "for ind, row in df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']] =", "the road network skeleton image. Input(s): image: skeletonized image Output(s):", "= 15, return_simple_ways = False) simple_segments = [] if exportPNG:", "node nodes_grid[x, y]: degree of the arrival node ''' def", "= 255 vectorized = skeletonize(road_network, largest_component = True) nodes, degree,", "'_' + str(8-last_direct)) ways.append(way) if return_simple_ways: simple_ways = [] for", "path: path where the skeletonized image should be saved largest_component:", "image should be saved largest_component: if True, only the largest", "and direction until the next node, and stores the pixels", "elif way == 5: x_, y_ = x, y+1 elif", "vectorized[vectorized > 100] = 255 vectorized[vectorized <= 100] = 0", "wrong_paths_active = True if nodes_grid[x, y]: end = True direction", "True break direction = direction_set[0] new_x, new_y = absoluteWay(x, y,", "full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways =", "x_, y_ = x-1, y-1 elif way == 1: x_,", "5, 6, 7, 8}) image: skeletonized image of the road", "2: wrong_paths = [3, 7] elif direction == 3: wrong_paths", "= x, y-1 elif way == 5: x_, y_ =", "direction = direction_set[0] new_x, new_y = absoluteWay(x, y, direction) way.append((new_x,", "!= None: if not((8-direction) in diagonal[d]): new_address.append(d) else: new_address.append(d) return", "< 0: return [], [], np.zeros((image.shape[1], image.shape[0])) df_nodes = pd.DataFrame({'x':", "def cleanNodesEdges(df_nodes: pd.DataFrame): df = df_nodes.copy() new_addresses, new_degree = [],", "+ ',' + str(y) + ',' + str(way) + '),", "son réseau filaire\".format(image_name)) simple_segments_JSON = simple_segments else: print('La géolocalisation du", "way.append((new_x, new_y)) x, y = new_x, new_y wrong_paths = noTurnBack(direction)", "that are non-zero (rows, cols) = np.nonzero(img) nodes, degree, addresses", "skeletonized image Output(s): nodes: array of nodes coordinates (x, y)", "os.path.join('workshop', 'thin.pnm') svg_path = export_file_path.replace('png', 'svg') os.system('convert ' + png_path", "terminal return_simple_ways: if True, compute the Douglas-Peucker simple itinerary of", "True direction = 8-start_dir while not(end): if x > 0", "df_nodes = cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree'] != 3] if (exportJSON", "'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']] = row['degree'] nodes_grid = nodes_grid.astype('int') for", "def noTurnBack(direction: int): wrong_paths = [] if direction == 0:", "if direction != None: if not((8-direction) in diagonal[d]): new_address.append(d) else:", "y, direction) way.append((new_x, new_y)) x, y = new_x, new_y if", "that are longer than a given length or non-terminal. Optionally,", "+ svg_path) return simple_segments, full_segments, nodes_grid def toPNG(segments: list, vectorized:", "1D array and check for non-zero locations pix_neighbourhood = img[row_neigh,", "Input(s): df_nodes: list of nodes image: skeletonized image of the", "image and their degree ''' img = image.copy() done, ways", "col_neigh.astype('int'), row_neigh.astype('int') # Convert into a single 1D array and", "[5, 7]} new_address = [] for r in right: if", "image col_neigh, row_neigh = col_neigh.astype('int'), row_neigh.astype('int') # Convert into a", "each segmenty) ways: list of segments, containing all the pixels", "exportJSON: project_name = getProjectName() try: with open(os.path.join('save', project_name, 'match' ,", "x_, y_ = x+1, y+1 else: raise AttributeError('Parameters invalid: ('", "df_nodes.iterrows(): for direct in node['address']: code = str(node['x']) + '_'", "simple_ways, ways, nodes_grid else: return ways, nodes_grid def thinImage(image: np.ndarray,", "outfile: json.dump(simple_segments_JSON, outfile) if exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png',", "simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:, 2:3].transpose()).tolist()) except: print(\"La géolocalisation de l'image", "pnm_path = os.path.join('workshop', 'thin.pnm') svg_path = export_file_path.replace('png', 'svg') os.system('convert '", "of the arrival node ''' def absoluteWay(x: int, y: int,", "def skeletonize(road_network: np.ndarray, path: str = \"workshop/vectorized.png\", largest_component: bool =", "y+1 else: raise AttributeError('Parameters invalid: (' + str(x) + ','", "installez d'abord Homebrew, ImageMagick et Potrace via le terminal.\\n\") print('Pour", "of 4 streets, etc.) addresses: directions of the crossing roads,", "l'image {} n'a pas encore été calculée. Par conséquent, \\", "+ str(way) + '), way \\ should be comprised between", "= row['degree'] nodes_grid = nodes_grid.astype('int') for ind, node in df_nodes.iterrows():", "directions of the crossing roads, with regard to the node", "(x, y) degree: degrees of the nodes (2=endpoint, 4=crossroads of", "y-coordinate start_dir: starting direction ({0, 1, 2, 3, -, 5,", "nodes_grid: np.ndarray): ''' Follow the path from one given start", "start_y: start node y-coordinate start_dir: starting direction ({0, 1, 2,", "row_neigh = row_neigh.astype('int') # Convert into a single 1D array", "wrong_paths = [0, 6] elif direction == 6: wrong_paths =", "PIL import Image, ImageDraw from utils.utils import * from utils.match", "x_, y_ = x+1, y-1 elif way == 7: x_,", "are non-zero (rows, cols) = np.nonzero(img) nodes, degree, addresses =", "return df def avoidDiagonalEdges(address: list, direction: int = None): right,", "7: wrong_paths = [0, 2] elif direction == 8: wrong_paths", "int, image: np.ndarray, nodes_grid: np.ndarray): ''' Follow the path from", "int, y: int, way: int): if way == 0: x_,", "ne fonctionne que pour le format JSON actuellement.') else: simple_segments_JSON", "0: wrong_paths = [5, 7] elif direction == 1: wrong_paths", "n_neighbours = np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood == True)[0] last_ds =", "' + png_path + pnm_path) os.system('potrace ' + pnm_path +", "vectorized = (labels == main_component).astype('uint8')*255 except: 'Warning: Skeletonization failed to", "image[row_neigh, col_neigh].transpose().ravel() != 0 except: print(x, y, image.shape, ) raise", "shp from skimage.measure import approximate_polygon from PIL import Image, ImageDraw", "géolocalisation de son réseau filaire\".format(image_name)) simple_segments_JSON = simple_segments else: print('La", "= 0 road_network[road_network < 255/2] = 0 road_network[road_network >= 255/2]", "< image.shape[0]-1 and c < image.shape[1]-1: # Extract an 8-connected", "degree, 'address': addresses }) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes)", "new_address = [] for r in right: if r in", "y = start_x, start_y assert image[x, y] != 0, 'ERROR:", "= col_neigh.astype('int'), row_neigh.astype('int') # Convert into a single 1D array", "wrong_paths_active = False if len(direction_set) != 1: end = True", "np.zeros((image.shape[1], image.shape[0])) df_nodes = pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1], 'degree': degree,", "road_network = image.copy() road_network[road_network < 254] = 0 road_network[road_network <", "vectorized: np.ndarray, out_path: str): ''' Save a given set of", "d in diagonal.keys(): if d in address: if not(diagonal[d][0] in", "addresses def cleanNodesEdges(df_nodes: pd.DataFrame): df = df_nodes.copy() new_addresses, new_degree =", "ImageDraw.Draw(bitmap) for segment in segments: coords = [] for point", "wrong_paths = [5, 7] elif direction == 1: wrong_paths =", "on the way. Input(s): start_x: start node x-coordinate start_y: start", "y-1 elif way == 1: x_, y_ = x-1, y", "== 2: wrong_paths = [3, 7] elif direction == 3:", "each couple of nodes vectorized: skeletonized image of the road", "return simple_ways, ways, nodes_grid else: return ways, nodes_grid def thinImage(image:", "= os.path.join('workshop', 'thin.pnm') svg_path = export_file_path.replace('png', 'svg') os.system('convert ' +", "'thin.pnm') svg_path = export_file_path.replace('png', 'svg') os.system('convert ' + png_path +", "reach the 2nd node nodes_grid[x, y]: degree of the arrival", "to int to index into image col_neigh, row_neigh = col_neigh.astype('int'),", "int.') return x_, y_ def noTurnBack(direction: int): wrong_paths = []", "y+1 elif way == 3: x_, y_ = x, y-1", "x+1, y-1 elif way == 7: x_, y_ = x+1,", "and 8, and != 4. x, y and way should", "= False if len(direction_set) != 1: end = True break", "[(x, y)] # First iteration new_x, new_y = absoluteWay(x, y,", "le format JSON actuellement.') else: simple_segments_JSON = simple_segments if exportJSON:", "= cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree'] != 3] if (exportJSON or", "point is not white' way.append((new_x, new_y)) x, y = new_x,", "= [0, 2] elif direction == 8: wrong_paths = [1,", "ImageDraw from utils.utils import * from utils.match import toLatLon Image.MAX_IMAGE_PIXELS", "vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized > 100] = 255 vectorized[vectorized <=", "int to index into image col_neigh, row_neigh = col_neigh.astype('int'), row_neigh.astype('int')", "geoloc: bool = False): assert (exportPNG or exportJSON or exportSVG", "skeletonized image of the road network out_path: the path, where", "roads, with regard to the node ''' img = image.copy()", "< image.shape[1]-1: # Extract an 8-connected neighbourhood (row_neigh, col_neigh) =", "the largest road network component will be kept Output(s): vectorized:", "each segment and return it Output(s): (Optional)(simple_ways: the Douglas-Peucker simple", "potrace\\n') if exportPNG: png_path = export_file_path else: png_path = os.path.join('workshop',", "full_segments, nodes_grid def toPNG(segments: list, vectorized: np.ndarray, out_path: str): '''", "simple_segments = [] if exportPNG: toPNG(full_segments, vectorized, export_file_path) elif exportSVG:", "= df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree'] != 3]", "if (exportJSON or exportSHP): simple_segments, full_segments, nodes_grid = findSegments(df_nodes, vectorized,", "toPNG(segments: list, vectorized: np.ndarray, out_path: str): ''' Save a given", "bool = True): ''' Find all the road segments in", "[1, 5] elif direction == 7: wrong_paths = [0, 2]", "de calculer la géolocalisation de son réseau filaire\".format(image_name)) simple_segments_JSON =", "n'est pas possible de calculer la géolocalisation de son réseau", "new_y wrong_paths = noTurnBack(direction) wrong_paths_active = True if nodes_grid[x, y]:", "False way = [(x, y)] # First iteration new_x, new_y", "y_ = x, y-1 elif way == 5: x_, y_", "the way between each couple of nodes nodes_grid: image containing", "y_ def noTurnBack(direction: int): wrong_paths = [] if direction ==", "and their degree ''' img = image.copy() done, ways =", "x, y = start_x, start_y assert image[x, y] != 0,", "''' img = image.copy() done, ways = [], [] df_nodes", "an 8-connected neighbourhood (col_neigh, row_neigh) = np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1,", "n'a pas encore été calculée. Par conséquent, \\ il n'est", "4 streets, etc.) addresses: directions of the crossing roads, with", "segment in segments: coords = [] for point in segment:", "into a single 1D array and check for non-zero locations", "and check for non-zero locations try: pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel()", "True) nodes, degree, addresses = findNodes(vectorized) if len(degree) < 0:", "elif way == 3: x_, y_ = x, y-1 elif", "df_nodes: list of nodes image: skeletonized image of the road", "road network component will be kept Output(s): vectorized: skeletonized image", "of the nodes of the skeletonized image Output(s): way: list", "skeletonized image should be saved largest_component: if True, only the", "invalid: (' + str(x) + ',' + str(y) + ','", "and way should be of type int.') return x_, y_", "nodes of the skeletonized image Output(s): way: list of pixel", "False): ''' Thinning/skeletonization of the road network image to a", "= np.nonzero(img) nodes, degree, addresses = [], [], [] for", "explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid) if not((len(way) <= min_length) and", "x > 0 and y > 0 and x <", "1, 0) w.field('gid', 'N', 11, 0) w.field('streetname', 'C', 41, 0)", "x, x+1]), np.array([y-1, y, y+1])) # Cast to int to", "'_' + str(way[-1][1]) + '_' + str(8-last_direct)) ways.append(way) if return_simple_ways:", "img = cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized >", "== 8: wrong_paths = [1, 3] return wrong_paths direction =", "wrong_paths: direction_set = direction_set[direction_set != wrong_path] wrong_paths_active = False if", "y+1 elif way == 6: x_, y_ = x+1, y-1", "+ '_' + str(8-last_direct)) ways.append(way) if return_simple_ways: simple_ways = []", "wrong_paths = [0, 2] elif direction == 8: wrong_paths =", "'), way \\ should be comprised between 0 and 8,", "y-1 elif way == 7: x_, y_ = x+1, y", "= str(node['x']) + '_' + str(node['y']) + '_' + str(direct)", "direction_set[direction_set != (8-direction)] last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if", "segments: list of segments, containing all the pixels on the", "in diagonal.keys(): if d in address: if not(diagonal[d][0] in address)", "except: print(x, y, image.shape, ) raise AssertionError() # If the", "one given start node and direction until the next node,", "2, add this to our list of coordinates n_neighbours =", "findSegments(df_nodes: pd.DataFrame, image: np.ndarray, min_length: int = 30, return_simple_ways: bool", "y_ = x+1, y elif way == 8: x_, y_", "direction == 5: wrong_paths = [0, 6] elif direction ==", "5: x_, y_ = x, y+1 elif way == 6:", "direction, nodes_grid[x, y] def findSegments(df_nodes: pd.DataFrame, image: np.ndarray, min_length: int", "address: new_address.append(r) for d in diagonal.keys(): if d in address:", "-, 5, 6, 7, 8}) image: skeletonized image of the", "(8-direction)] last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if wrong_paths_active: for", "in wrong_paths: direction_set = direction_set[direction_set != wrong_path] wrong_paths_active = False", "cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2)) vectorized = thinning.guo_hall_thinning(img) vectorized[vectorized > 100] =", "skeletonize(road_network, largest_component = True) nodes, degree, addresses = findNodes(vectorized) if", "cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats = stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized", "5: wrong_paths = [0, 6] elif direction == 6: wrong_paths", "wrong_path in wrong_paths: direction_set = direction_set[direction_set != wrong_path] wrong_paths_active =", "os import numpy as np import pandas as pd import", "degree, addresses = [], [], [] for (r,c) in zip(rows,", "Follow the path from one given start node and direction", "outfile) if exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''), image_name))", "!= 0, 'ERROR: start point is not white' end =", "np.array([r-1, r, r+1])) # Cast to int to index into", "print('Pour installer Homebrew:\\n', ' /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour", "end = False way = [(x, y)] # First iteration", "def thinImage(image: np.ndarray, image_name: str, export_file_path: str, exportPNG: bool =", "each segment and return it. Input(s): df_nodes: list of nodes", "For Bibliothèque nationale de France (BnF) import cv2, thinning, os", "= image.copy() # Find row and column locations that are", "elif way == 8: x_, y_ = x+1, y+1 else:", "= 8-start_dir while not(end): if x > 0 and y", "new_addresses.append(new_address) new_degree.append(len(new_address) + 1) df['address'] = new_addresses df['degree'] = new_degree", "Find the nodes in the road network skeleton image. Input(s):", "de France (BnF) import cv2, thinning, os import numpy as", "pas encore été calculée. Par conséquent, \\ il n'est pas", "''), image_name)) if exportSVG: print(\"\\nAvertissement: Si vous n'avez jamais utilisé", "[] for way in ways: inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way),", "= direction_set[direction_set != 4] addresses.append(direction_set) nodes = np.asarray(nodes) return nodes,", "< 255/2] = 0 road_network[road_network >= 255/2] = 255 vectorized", "the skeletonized image should be saved largest_component: if True, only", "3] return wrong_paths direction = start_dir x, y = start_x,", "[1, 3, 5, 7], {0: [1, 3], 2: [1, 5],", "start node x-coordinate start_y: start node y-coordinate start_dir: starting direction", "the output bitmap image should be save ''' canvas =", "or exportSVG or exportSHP) # Convert to B&W road_network =", "'_' + str(direct) if not(code in done): way, last_direct, degree", "}) df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree']", "y elif way == 8: x_, y_ = x+1, y+1", "not(diagonal[d][1] in address): if direction != None: if not((8-direction) in", "way between each couple of nodes vectorized: skeletonized image of", "the road network (streets in white) path: path where the", "not((8-direction) in diagonal[d]): new_address.append(d) else: new_address.append(d) return new_address def explorePath(start_x:", "y = new_x, new_y if nodes_grid[x, y]: end = True", "= True break direction = direction_set[0] new_x, new_y = absoluteWay(x,", "in right: if r in address: new_address.append(r) for d in", "address: if not(diagonal[d][0] in address) and not(diagonal[d][1] in address): if", "= findNodes(vectorized) if len(degree) < 0: return [], [], np.zeros((image.shape[1],", "(np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels == main_component).astype('uint8')*255 except: 'Warning: Skeletonization failed", "of the road network min_length: min segment length if the", "import Image, ImageDraw from utils.utils import * from utils.match import", "kept Output(s): vectorized: skeletonized image ''' assert len(road_network.shape) == 2,", "addresses: directions of the crossing roads, with regard to the", "= export_file_path else: png_path = os.path.join('workshop', 'thin.png') pnm_path = os.path.join('workshop',", "(exportJSON or exportSHP): simple_segments, full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length", "row_neigh.astype('int') # Convert into a single 1D array and check", "new_degree return df def avoidDiagonalEdges(address: list, direction: int = None):", "min_length = 15, return_simple_ways = False) simple_segments = [] if", "= new_x, new_y wrong_paths = noTurnBack(direction) wrong_paths_active = True if", "np.sum(pix_neighbourhood) if (n_neighbours == 2) or (n_neighbours >= 4): nodes.append((r,", "0: return [], [], np.zeros((image.shape[1], image.shape[0])) df_nodes = pd.DataFrame({'x': nodes[:,0],", "False, exportJSON: bool = False, exportSVG: bool = False, exportSHP:", "to reach the 2nd node nodes_grid[x, y]: degree of the", "assert image[x, y] != 0, 'ERROR: start point is not", "3, -, 5, 6, 7, 8}) image: skeletonized image of", "way direction: last direction to reach the 2nd node nodes_grid[x,", "col_neigh].transpose().ravel() != 0 except: print(x, y, image.shape, ) raise AssertionError()", "+ '.json')) as data: data = json.load(data) M = np.asarray(data['M'])", "0, 'ERROR: 2nd point is not white' way.append((new_x, new_y)) x,", "y_ = x+1, y-1 elif way == 7: x_, y_", "direct in node['address']: code = str(node['x']) + '_' + str(node['y'])", "la géolocalisation de son réseau filaire\".format(image_name)) simple_segments_JSON = simple_segments else:", "AssertionError() # If the number of non-zero locations equals 2,", "in df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']] = row['degree'] nodes_grid =", "column locations that are non-zero (rows, cols) = np.nonzero(img) nodes,", "ways, nodes_grid def thinImage(image: np.ndarray, image_name: str, export_file_path: str, exportPNG:", "np.ndarray): ''' Find the nodes in the road network skeleton", "y > 0 and x < image.shape[0]-1 and y <", "row and column locations that are non-zero (rows, cols) =", "of nodes coordinates (x, y) degree: degrees of the nodes", "installer Potrace: \\n', ' brew install potrace\\n') if exportPNG: png_path", "= [] for r in right: if r in address:", "\"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n', ' brew install imagemagick')", "way == 1: x_, y_ = x-1, y elif way", "(Optional)(simple_ways: the Douglas-Peucker simple itinerary of each segmenty) ways: list", "(streets in white) path: path where the skeletonized image should", "longer than a given length or non-terminal. Optionally, compute the", "if exportJSON: project_name = getProjectName() try: with open(os.path.join('save', project_name, 'match'", "way.append((new_x, new_y)) x, y = new_x, new_y if nodes_grid[x, y]:", "in df['address'].iteritems(): new_address = avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) + 1) df['address']", "nodes, degree, addresses = [], [], [] for (r,c) in", "<= min_length) and ((node['degree'] == 2) or (degree == 2))):", "Keep the ones that are longer than a given length", "8: wrong_paths = [1, 3] return wrong_paths direction = start_dir", "pixels on the way. Input(s): start_x: start node x-coordinate start_y:", "streets, 5=crossroads of 4 streets, etc.) addresses: directions of the", "the image and their degree ''' img = image.copy() done,", "nodes, degree, addresses def cleanNodesEdges(df_nodes: pd.DataFrame): df = df_nodes.copy() new_addresses,", "import cv2, thinning, os import numpy as np import pandas", "direction_set = np.where(pix_neighbourhood == True)[0] direction_set = direction_set[direction_set != 4]", "where the skeletonized image should be saved largest_component: if True,", "-fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n', ' brew install imagemagick') print('Pour", "largest_component: if True, only the largest road network component will", "found in the image and their degree ''' img =", "road network image to a wired model. Input(s): road_network: black", "image.shape[0]-(2*np.asarray(segment)[:,1])]).T simple_segments_JSON.append(toLatLon((s@M[:, :2]) + M[:, 2:3].transpose()).tolist()) except: print(\"La géolocalisation de", "white' end = False way = [(x, y)] # First", "_ = cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats = stats[1:] main_component =", "= [], [], [] for (r,c) in zip(rows, cols): if", "simple_segments, full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways", "0 and x < image.shape[0]-1 and y < image.shape[1]-1: #", "3: wrong_paths = [2, 8] elif direction == 5: wrong_paths", "network min_length: min segment length if the segment is terminal", "# Cast to int to index into image col_neigh, row_neigh", "install imagemagick') print('Pour installer Potrace: \\n', ' brew install potrace\\n')", "out_path): w = shp.Writer(out_path) w.field('DeletionFlag', 'C', 1, 0) w.field('gid', 'N',", "= [3, 7] elif direction == 3: wrong_paths = [2,", "between each couple of nodes nodes_grid: image containing all the", "utils.utils import * from utils.match import toLatLon Image.MAX_IMAGE_PIXELS = 500000000", "y] != 0, 'ERROR: start point is not white' end", "inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways, ways, nodes_grid", "# Extract an 8-connected neighbourhood (col_neigh, row_neigh) = np.meshgrid(np.array([c-1, c,", "d in address: if not(diagonal[d][0] in address) and not(diagonal[d][1] in", "if geoloc: if exportJSON: project_name = getProjectName() try: with open(os.path.join('save',", "a given length or non-terminal. Optionally, compute the Douglas-Peucker simple", "np.ndarray, path: str = \"workshop/vectorized.png\", largest_component: bool = False): '''", "point is not white' end = False way = [(x,", "True)[0] last_ds = [wrong_paths] last_ds.append(direction_set) direction_set = direction_set[direction_set != 4]", "skimage.measure import approximate_polygon from PIL import Image, ImageDraw from utils.utils", "== True)[0] last_ds = [wrong_paths] last_ds.append(direction_set) direction_set = direction_set[direction_set !=", "= row_neigh.astype('int') # Convert into a single 1D array and", "= True): ''' Find all the road segments in the", "= direction_set[direction_set != wrong_path] wrong_paths_active = False if len(direction_set) !=", "bool = False, exportSVG: bool = False, exportSHP: bool =", "7, 8}) image: skeletonized image of the road network nodes_grid:", "np.sum(pix_neighbourhood) direction_set = np.where(pix_neighbourhood == True)[0] last_ds = [wrong_paths] last_ds.append(direction_set)", "bool = False, exportSHP: bool = False, geoloc: bool =", "the road network image to a wired model. Input(s): road_network:", "cols): if r > 0 and c > 0 and", "5] elif direction == 7: wrong_paths = [0, 2] elif", "y, y+1])) # Cast to int to index into image", "# Convert to B&W road_network = image.copy() road_network[road_network < 254]", "right: if r in address: new_address.append(r) for d in diagonal.keys():", "in ways: inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways,", "0) w.field('note', 'C', 32, 0) for i in range(len(simple_ways)): w.line([simple_ways[i]])", "< image.shape[1]-1: # Extract an 8-connected neighbourhood (col_neigh, row_neigh) =", ") raise AssertionError() # If the number of non-zero locations", "array and check for non-zero locations pix_neighbourhood = img[row_neigh, col_neigh].ravel()", "network nodes_grid: grid of the nodes of the skeletonized image", "to apply largest_component = True param. Skipping.' cv2.imwrite(path, vectorized) return", "image.shape[1]-1: # Extract an 8-connected neighbourhood (row_neigh, col_neigh) = np.meshgrid(np.array([x-1,", "install potrace\\n') if exportPNG: png_path = export_file_path else: png_path =", "def findNodes(image: np.ndarray): ''' Find the nodes in the road", "not(end): if x > 0 and y > 0 and", "= [], [] df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape) for", "100] = 255 vectorized[vectorized <= 100] = 0 if largest_component:", "the nodes found in the image and their degree '''", "of coordinates n_neighbours = np.sum(pix_neighbourhood) if (n_neighbours == 2) or", "str, export_file_path: str, exportPNG: bool = False, exportJSON: bool =", "wrong_paths = [1, 5] elif direction == 7: wrong_paths =", "2: [1, 5], 6: [3, 7], 8: [5, 7]} new_address", "tolerance=1.6).tolist()) return simple_ways, ways, nodes_grid else: return ways, nodes_grid def", "with open(export_file_path.replace('png', 'json'), 'w') as outfile: json.dump(simple_segments_JSON, outfile) if exportSHP:", "[], [] for (r,c) in zip(rows, cols): if r >", "y_ = x-1, y-1 elif way == 1: x_, y_", "skeletonized image of the road network nodes_grid: grid of the", "np.ndarray, nodes_grid: np.ndarray): ''' Follow the path from one given", "into image col_neigh, row_neigh = col_neigh.astype('int'), row_neigh.astype('int') # Convert into", "# 2020, BackThen Maps # Coded by <NAME> https://github.com/RPetitpierre #", "from skimage.measure import approximate_polygon from PIL import Image, ImageDraw from", "direction == 8: wrong_paths = [1, 3] return wrong_paths direction", "n'avez jamais utilisé cette commande, \\ installez d'abord Homebrew, ImageMagick", "'w') as outfile: json.dump(simple_segments_JSON, outfile) if exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True)", "8, and != 4. x, y and way should be", "df_nodes = df_nodes.sort_values(by='degree').reset_index(drop=True) nodes_grid = np.zeros(image.shape) for ind, row in", "ind, address in df['address'].iteritems(): new_address = avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address) +", "image[new_x, new_y] != 0, 'ERROR: 2nd point is not white'", "nodes_grid = findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways = True)", "= json.load(data) M = np.asarray(data['M']) simple_segments_JSON = [] for segment", "of the road network (streets in white) path: path where", "if True, compute the Douglas-Peucker simple itinerary of each segment", "last_direct, degree = explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid) if not((len(way)", "else: return ways, nodes_grid def thinImage(image: np.ndarray, image_name: str, export_file_path:", "exportJSON or exportSVG or exportSHP) # Convert to B&W road_network", "= [] if direction == 0: wrong_paths = [5, 7]", "return wrong_paths direction = start_dir x, y = start_x, start_y", "path from one given start node and direction until the", "the road network nodes_grid: grid of the nodes of the", "Bibliothèque nationale de France (BnF) import cv2, thinning, os import", "print('La géolocalisation du réseau filaire ne fonctionne que pour le", "7], 8: [5, 7]} new_address = [] for r in", "+ str(node['y']) + '_' + str(direct) if not(code in done):", "len(direction_set) != 1: end = True break direction = direction_set[0]", "a wired model. Input(s): road_network: black and white image of", "elif direction == 7: wrong_paths = [0, 2] elif direction", "their degree ''' img = image.copy() done, ways = [],", "nodes_grid: grid of the nodes of the skeletonized image Output(s):", "'json'), 'w') as outfile: json.dump(simple_segments_JSON, outfile) if exportSHP: os.makedirs(export_file_path.replace('.png', ''),", "int, way: int): if way == 0: x_, y_ =", "the Douglas-Peucker simple itinerary of each segment and return it.", "'.json')) as data: data = json.load(data) M = np.asarray(data['M']) simple_segments_JSON", "' brew install potrace\\n') if exportPNG: png_path = export_file_path else:", "new_y)) x, y = new_x, new_y if nodes_grid[x, y]: end", "[], [], [] for (r,c) in zip(rows, cols): if r", "format JSON actuellement.') else: simple_segments_JSON = simple_segments if exportJSON: with", "print('Pour installer Potrace: \\n', ' brew install potrace\\n') if exportPNG:", "[], [], np.zeros((image.shape[1], image.shape[0])) df_nodes = pd.DataFrame({'x': nodes[:,0], 'y': nodes[:,1],", "draw = ImageDraw.Draw(bitmap) for segment in segments: coords = []", "Maps # Coded by <NAME> https://github.com/RPetitpierre # For Bibliothèque nationale", "start_x, start_y assert image[x, y] != 0, 'ERROR: start point", "single 1D array and check for non-zero locations pix_neighbourhood =", "direction: int = None): right, diagonal = [1, 3, 5,", "= True param. Skipping.' cv2.imwrite(path, vectorized) return vectorized def findNodes(image:", "!= 0 except: print(x, y, image.shape, ) raise AssertionError() #", "n_neighbours = np.sum(pix_neighbourhood) if (n_neighbours == 2) or (n_neighbours >=", "if x > 0 and y > 0 and x", "'C', 32, 0) for i in range(len(simple_ways)): w.line([simple_ways[i]]) w.record('01', i,", "= findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways = False) simple_segments", "= [1, 5] elif direction == 7: wrong_paths = [0,", "start_x: start node x-coordinate start_y: start node y-coordinate start_dir: starting", "print(\"\\nAvertissement: Si vous n'avez jamais utilisé cette commande, \\ installez", "svg_path = export_file_path.replace('png', 'svg') os.system('convert ' + png_path + pnm_path)", "way == 2: x_, y_ = x-1, y+1 elif way", "new_x, new_y = absoluteWay(x, y, direction) assert image[new_x, new_y] !=", "be of type int.') return x_, y_ def noTurnBack(direction: int):", "elif direction == 1: wrong_paths = [6, 8] elif direction", "model. Input(s): road_network: black and white image of the road", "calculer la géolocalisation de son réseau filaire\".format(image_name)) simple_segments_JSON = simple_segments", "segment and return it. Input(s): df_nodes: list of nodes image:", "np.asarray(nodes) return nodes, degree, addresses def cleanNodesEdges(df_nodes: pd.DataFrame): df =", "x-coordinate start_y: start node y-coordinate start_dir: starting direction ({0, 1,", "First iteration new_x, new_y = absoluteWay(x, y, direction) assert image[new_x,", "= img[row_neigh, col_neigh].ravel() != 0 # If the number of", "pixel coordinates on the way direction: last direction to reach", "diagonal = [1, 3, 5, 7], {0: [1, 3], 2:", "coords.append((point[1], point[0])) draw.line(coords, fill = 'black', width=0) bitmap.save(out_path) def toShapefile(simple_ways,", "of 3 streets, 5=crossroads of 4 streets, etc.) addresses: directions", "x, y = new_x, new_y if nodes_grid[x, y]: end =", "[3, 7], 8: [5, 7]} new_address = [] for r", "3 streets, 5=crossroads of 4 streets, etc.) addresses: directions of", "way == 0: x_, y_ = x-1, y-1 elif way", "road_network[road_network < 254] = 0 road_network[road_network < 255/2] = 0", "by <NAME> https://github.com/RPetitpierre # For Bibliothèque nationale de France (BnF)", "df_nodes.sort_values(by='degree').reset_index(drop=True) df_nodes = cleanNodesEdges(df_nodes) df_nodes = df_nodes[df_nodes['degree'] != 3] if", "start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid) if not((len(way) <= min_length) and ((node['degree']", "findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways = False) simple_segments =", "'match' , 'primary', image_name + '.json')) as data: data =", "<NAME> https://github.com/RPetitpierre # For Bibliothèque nationale de France (BnF) import", "ind, node in df_nodes.iterrows(): for direct in node['address']: code =", "bool = False, exportJSON: bool = False, exportSVG: bool =", "[wrong_paths] last_ds.append(direction_set) direction_set = direction_set[direction_set != 4] last_ds.append(direction_set) direction_set =", "stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels == main_component).astype('uint8')*255 except:", "segments in the network. Keep the ones that are longer", "!= (8-direction)] last_ds.append(direction_set) direction_set = np.asarray(avoidDiagonalEdges(direction_set, direction)) last_ds.append(direction_set) if wrong_paths_active:", "'_' + str(node['y']) + '_' + str(direct) if not(code in", "if not((len(way) <= min_length) and ((node['degree'] == 2) or (degree", "False) simple_segments = [] if exportPNG: toPNG(full_segments, vectorized, export_file_path) elif", "def avoidDiagonalEdges(address: list, direction: int = None): right, diagonal =", "[] for point in segment: coords.append((point[1], point[0])) draw.line(coords, fill =", "of the road network image to a wired model. Input(s):", "pix_neighbourhood = img[row_neigh, col_neigh].ravel() != 0 # If the number", "and column locations that are non-zero (rows, cols) = np.nonzero(img)", "+ ' -s -o ' + svg_path) return simple_segments, full_segments,", "toPNG(full_segments, vectorized, export_file_path) elif exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png')) if", "len(degree) < 0: return [], [], np.zeros((image.shape[1], image.shape[0])) df_nodes =", "= [1, 3, 5, 7], {0: [1, 3], 2: [1,", "way in ways: inv_way = np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return", "direction) way.append((new_x, new_y)) x, y = new_x, new_y if nodes_grid[x,", "y < image.shape[1]-1: # Extract an 8-connected neighbourhood (row_neigh, col_neigh)", "if r > 0 and c > 0 and r", "y = new_x, new_y wrong_paths = noTurnBack(direction) wrong_paths_active = True", "nodes_grid = nodes_grid.astype('int') for ind, node in df_nodes.iterrows(): for direct", "' + pnm_path + ' -s -o ' + svg_path)", "toLatLon Image.MAX_IMAGE_PIXELS = 500000000 def skeletonize(road_network: np.ndarray, path: str =", "absoluteWay(x, y, direction) assert image[new_x, new_y] != 0, 'ERROR: 2nd", "(rows, cols) = np.nonzero(img) nodes, degree, addresses = [], [],", "= explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid) if not((len(way) <= min_length)", "way == 5: x_, y_ = x, y+1 elif way", "start_dir: starting direction ({0, 1, 2, 3, -, 5, 6,", "wrong_paths = [6, 8] elif direction == 2: wrong_paths =", "np.asarray([np.asarray(way)[:,1], image.shape[0]-np.asarray(way)[:,0]]).transpose() simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways, ways, nodes_grid else: return", "toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png')) if geoloc: if exportJSON: project_name =", "df_nodes.copy() new_addresses, new_degree = [], [] for ind, address in", "with regard to the node ''' img = image.copy() #", "be kept Output(s): vectorized: skeletonized image ''' assert len(road_network.shape) ==", "= [0, 6] elif direction == 6: wrong_paths = [1,", "for non-zero locations try: pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel() != 0", "w.field('gid', 'N', 11, 0) w.field('streetname', 'C', 41, 0) w.field('note', 'C',", "np.where(pix_neighbourhood == True)[0] last_ds = [wrong_paths] last_ds.append(direction_set) direction_set = direction_set[direction_set", "non-zero locations try: pix_neighbourhood = image[row_neigh, col_neigh].transpose().ravel() != 0 except:", "json.dump(simple_segments_JSON, outfile) if exportSHP: os.makedirs(export_file_path.replace('.png', ''), exist_ok=True) toShapefile(simple_segments, os.path.join(export_file_path.replace('.png', ''),", "np.where(pix_neighbourhood == True)[0] direction_set = direction_set[direction_set != 4] addresses.append(direction_set) nodes", "= 30, return_simple_ways: bool = True): ''' Find all the", "array and check for non-zero locations try: pix_neighbourhood = image[row_neigh,", "= 500000000 def skeletonize(road_network: np.ndarray, path: str = \"workshop/vectorized.png\", largest_component:", "5, 7], {0: [1, 3], 2: [1, 5], 6: [3,", "to the node ''' img = image.copy() # Find row", "the network. Keep the ones that are longer than a", "direction = start_dir x, y = start_x, start_y assert image[x,", "exportSVG: bool = False, exportSHP: bool = False, geoloc: bool", "!= 4. x, y and way should be of type", "df_nodes = df_nodes[df_nodes['degree'] != 3] if (exportJSON or exportSHP): simple_segments,", "x_, y_ = x, y+1 elif way == 6: x_,", "non-terminal. Optionally, compute the Douglas-Peucker simple itinerary of each segment", "main_component = (np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels == main_component).astype('uint8')*255 except: 'Warning:", "the crossing roads, with regard to the node ''' img", "of segments as a bitmap image from the road network.", "500000000 def skeletonize(road_network: np.ndarray, path: str = \"workshop/vectorized.png\", largest_component: bool", "== 1: wrong_paths = [6, 8] elif direction == 2:", "image.shape[0]-1 and c < image.shape[1]-1: # Extract an 8-connected neighbourhood", "the 2nd node nodes_grid[x, y]: degree of the arrival node", "if direction == 0: wrong_paths = [5, 7] elif direction", "* from utils.match import toLatLon Image.MAX_IMAGE_PIXELS = 500000000 def skeletonize(road_network:", "= False, exportSVG: bool = False, exportSHP: bool = False,", "elif direction == 5: wrong_paths = [0, 6] elif direction", "/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"') print('Pour installer ImageMagick:\\n', ' brew", "w.field('DeletionFlag', 'C', 1, 0) w.field('gid', 'N', 11, 0) w.field('streetname', 'C',", "elif direction == 3: wrong_paths = [2, 8] elif direction", "way == 3: x_, y_ = x, y-1 elif way", "le terminal.\\n\") print('Pour installer Homebrew:\\n', ' /usr/bin/ruby -e \"$(curl -fsSL", "= col_neigh.astype('int') row_neigh = row_neigh.astype('int') # Convert into a single", "== 2: x_, y_ = x-1, y+1 elif way ==", "réseau filaire\".format(image_name)) simple_segments_JSON = simple_segments else: print('La géolocalisation du réseau", "and c < image.shape[1]-1: # Extract an 8-connected neighbourhood (col_neigh,", "export_file_path) elif exportSVG: toPNG(full_segments, vectorized, os.path.join('workshop', 'thin.png')) if geoloc: if", "= x-1, y-1 elif way == 1: x_, y_ =", "vectorized = skeletonize(road_network, largest_component = True) nodes, degree, addresses =", "width=0) bitmap.save(out_path) def toShapefile(simple_ways, out_path): w = shp.Writer(out_path) w.field('DeletionFlag', 'C',", "where the output bitmap image should be save ''' canvas", "= new_x, new_y if nodes_grid[x, y]: end = True else:", "new_y = absoluteWay(x, y, direction) assert image[new_x, new_y] != 0,", "new_address.append(d) else: new_address.append(d) return new_address def explorePath(start_x: int, start_y: int,", "np import pandas as pd import shapefile as shp from", "return nodes, degree, addresses def cleanNodesEdges(df_nodes: pd.DataFrame): df = df_nodes.copy()", "new_degree = [], [] for ind, address in df['address'].iteritems(): new_address", "data: data = json.load(data) M = np.asarray(data['M']) simple_segments_JSON = []", "single 1D array and check for non-zero locations try: pix_neighbourhood", "locations pix_neighbourhood = img[row_neigh, col_neigh].ravel() != 0 # If the", "= df_nodes[df_nodes['degree'] != 3] if (exportJSON or exportSHP): simple_segments, full_segments,", "''' assert len(road_network.shape) == 2, 'ERROR: road_network must be grayscale", "r, r+1])) # Cast to int to index into image", "0 road_network[road_network >= 255/2] = 255 vectorized = skeletonize(road_network, largest_component", "col_neigh.astype('int') row_neigh = row_neigh.astype('int') # Convert into a single 1D", "return x_, y_ def noTurnBack(direction: int): wrong_paths = [] if", "https://github.com/RPetitpierre # For Bibliothèque nationale de France (BnF) import cv2,", "degree = explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid) if not((len(way) <=", "+ str(direct) if not(code in done): way, last_direct, degree =", "Douglas-Peucker simple itinerary of each segmenty) ways: list of segments,", "> 0 and y > 0 and x < image.shape[0]-1", "noTurnBack(direction) wrong_paths_active = True if nodes_grid[x, y]: end = True", "+ M[:, 2:3].transpose()).tolist()) except: print(\"La géolocalisation de l'image {} n'a", "commande, \\ installez d'abord Homebrew, ImageMagick et Potrace via le", "largest road network component will be kept Output(s): vectorized: skeletonized", "== 7: wrong_paths = [0, 2] elif direction == 8:", "img = image.copy() done, ways = [], [] df_nodes =", "= [wrong_paths] last_ds.append(direction_set) direction_set = direction_set[direction_set != 4] last_ds.append(direction_set) direction_set", "2] elif direction == 8: wrong_paths = [1, 3] return", "stores the pixels on the way. Input(s): start_x: start node", "image_name + '.json')) as data: data = json.load(data) M =", "Homebrew, ImageMagick et Potrace via le terminal.\\n\") print('Pour installer Homebrew:\\n',", "start_y assert image[x, y] != 0, 'ERROR: start point is", "r+1])) # Cast to int to index into image col_neigh", "= cv2.connectedComponentsWithStats(vectorized.copy(), connectivity=8, stats=cv2.CC_STAT_AREA) stats = stats[1:] main_component = (np.argmax(stats[:,4])+1).astype('int32')", "6: wrong_paths = [1, 5] elif direction == 7: wrong_paths", "row in df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'], row['y']] = row['degree'] nodes_grid", "findNodes(vectorized) if len(degree) < 0: return [], [], np.zeros((image.shape[1], image.shape[0]))", "coordinates n_neighbours = np.sum(pix_neighbourhood) if (n_neighbours == 2) or (n_neighbours", "our list of coordinates n_neighbours = np.sum(pix_neighbourhood) if (n_neighbours ==", "return_simple_ways: bool = True): ''' Find all the road segments", "= new_degree return df def avoidDiagonalEdges(address: list, direction: int =", "cols) = np.nonzero(img) nodes, degree, addresses = [], [], []", "image Output(s): nodes: array of nodes coordinates (x, y) degree:", "png_path + pnm_path) os.system('potrace ' + pnm_path + ' -s", "skeletonized image Output(s): way: list of pixel coordinates on the", "simple_ways.append(approximate_polygon(np.asarray(inv_way), tolerance=1.6).tolist()) return simple_ways, ways, nodes_grid else: return ways, nodes_grid", "approximate_polygon from PIL import Image, ImageDraw from utils.utils import *", "network out_path: the path, where the output bitmap image should", "black and white image of the road network (streets in", "-o ' + svg_path) return simple_segments, full_segments, nodes_grid def toPNG(segments:", "np.meshgrid(np.array([c-1, c, c+1]), np.array([r-1, r, r+1])) # Cast to int", "'primary', image_name + '.json')) as data: data = json.load(data) M", "== 2, 'ERROR: road_network must be grayscale image' img =", "the node ''' img = image.copy() # Find row and", "elif direction == 6: wrong_paths = [1, 5] elif direction", "simple_segments_JSON = [] for segment in simple_segments: s = np.asarray([2*np.asarray(segment)[:,0],", "!= 3] if (exportJSON or exportSHP): simple_segments, full_segments, nodes_grid =", "set of segments as a bitmap image from the road", "utils.match import toLatLon Image.MAX_IMAGE_PIXELS = 500000000 def skeletonize(road_network: np.ndarray, path:", "until the next node, and stores the pixels on the", "canvas); bitmap = Image.open('workshop/canvas.png') draw = ImageDraw.Draw(bitmap) for segment in", "= \"workshop/vectorized.png\", largest_component: bool = False): ''' Thinning/skeletonization of the", "be comprised between 0 and 8, and != 4. x,", "last_ds = [wrong_paths] last_ds.append(direction_set) direction_set = direction_set[direction_set != 4] last_ds.append(direction_set)", "out_path: str): ''' Save a given set of segments as", "''' canvas = (np.ones(vectorized.shape)*255).astype('uint8') cv2.imwrite('workshop/canvas.png', canvas); bitmap = Image.open('workshop/canvas.png') draw", "2nd point is not white' way.append((new_x, new_y)) x, y =", "done): way, last_direct, degree = explorePath(start_x=node['x'], start_y=node['y'], start_dir=direct, image=img, nodes_grid=nodes_grid)", "starting direction ({0, 1, 2, 3, -, 5, 6, 7,", "road_network must be grayscale image' img = cv2.resize(road_network, (road_network.shape[1]//2, road_network.shape[0]//2))", "2nd node nodes_grid[x, y]: degree of the arrival node '''", "etc.) addresses: directions of the crossing roads, with regard to", "print(\"La géolocalisation de l'image {} n'a pas encore été calculée.", "not(diagonal[d][0] in address) and not(diagonal[d][1] in address): if direction !=", "node['address']: code = str(node['x']) + '_' + str(node['y']) + '_'", "4] last_ds.append(direction_set) direction_set = direction_set[direction_set != (8-direction)] last_ds.append(direction_set) direction_set =", "cleanNodesEdges(df_nodes: pd.DataFrame): df = df_nodes.copy() new_addresses, new_degree = [], []", "else: full_segments, nodes_grid = findSegments(df_nodes, vectorized, min_length = 15, return_simple_ways", "False, geoloc: bool = False): assert (exportPNG or exportJSON or", "end = True return way, direction, nodes_grid[x, y] def findSegments(df_nodes:", "json.load(data) M = np.asarray(data['M']) simple_segments_JSON = [] for segment in", "2:3].transpose()).tolist()) except: print(\"La géolocalisation de l'image {} n'a pas encore", "x, y = new_x, new_y wrong_paths = noTurnBack(direction) wrong_paths_active =", "int): wrong_paths = [] if direction == 0: wrong_paths =", "x+1]), np.array([y-1, y, y+1])) # Cast to int to index", "nodes_grid def toPNG(segments: list, vectorized: np.ndarray, out_path: str): ''' Save", "start_dir: int, image: np.ndarray, nodes_grid: np.ndarray): ''' Follow the path", "y_ = x+1, y+1 else: raise AttributeError('Parameters invalid: (' +", "Cast to int to index into image col_neigh = col_neigh.astype('int')", "True)[0] direction_set = direction_set[direction_set != 4] addresses.append(direction_set) nodes = np.asarray(nodes)", "= ImageDraw.Draw(bitmap) for segment in segments: coords = [] for", "géolocalisation de l'image {} n'a pas encore été calculée. Par", "= (np.argmax(stats[:,4])+1).astype('int32') vectorized = (labels == main_component).astype('uint8')*255 except: 'Warning: Skeletonization", "5=crossroads of 4 streets, etc.) addresses: directions of the crossing", "df['degree'] = new_degree return df def avoidDiagonalEdges(address: list, direction: int", "= np.zeros(image.shape) for ind, row in df_nodes[['x', 'y', 'degree']].iterrows(): nodes_grid[row['x'],", "simple_segments if exportJSON: with open(export_file_path.replace('png', 'json'), 'w') as outfile: json.dump(simple_segments_JSON,", "thinImage(image: np.ndarray, image_name: str, export_file_path: str, exportPNG: bool = False,", "\\ il n'est pas possible de calculer la géolocalisation de", "for ind, address in df['address'].iteritems(): new_address = avoidDiagonalEdges(address) new_addresses.append(new_address) new_degree.append(len(new_address)", "= direction_set[0] new_x, new_y = absoluteWay(x, y, direction) way.append((new_x, new_y))", "the number of non-zero locations equals 2, add this to", "filaire\".format(image_name)) simple_segments_JSON = simple_segments else: print('La géolocalisation du réseau filaire", "than a given length or non-terminal. Optionally, compute the Douglas-Peucker", "to our list of coordinates n_neighbours = np.sum(pix_neighbourhood) if (n_neighbours", "a single 1D array and check for non-zero locations pix_neighbourhood", "explorePath(start_x: int, start_y: int, start_dir: int, image: np.ndarray, nodes_grid: np.ndarray):" ]
[ "import TestCase from unittest.mock import patch from easy2fa import cli", "unittest import TestCase from unittest.mock import patch from easy2fa import", "mock_input.return_value = '' self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt',", "'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input') @patch('builtins.print') def test_assertions(self, mock_print, mock_input):", "import cli class TestCheckInput(TestCase): @patch('builtins.input') def test_default(self, mock_input): mock_input.return_value =", "= '' self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt', default='one'),", "['yes', 'no']: return 'use yes or no' mock_input.side_effect = ['input',", "default='one'), 'two') @patch('builtins.input') @patch('builtins.print') def test_assertions(self, mock_print, mock_input): def assertion(value):", "TestCheckInput(TestCase): @patch('builtins.input') def test_default(self, mock_input): mock_input.return_value = '' self.assertEquals(cli.check_input('prompt', default='one'),", "'two') @patch('builtins.input') @patch('builtins.print') def test_assertions(self, mock_print, mock_input): def assertion(value): if", "import patch from easy2fa import cli class TestCheckInput(TestCase): @patch('builtins.input') def", "'' self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two')", "default='one'), 'one') mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input') @patch('builtins.print')", "self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input')", "self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input') @patch('builtins.print') def test_assertions(self, mock_print, mock_input): def", "mock_print, mock_input): def assertion(value): if value not in ['yes', 'no']:", "return 'use yes or no' mock_input.side_effect = ['input', '', 'no']", "mock_input.side_effect = ['input', '', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no') mock_print.assert_called_with('\\tInvalid input:", "value not in ['yes', 'no']: return 'use yes or no'", "test_assertions(self, mock_print, mock_input): def assertion(value): if value not in ['yes',", "'one') mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input') @patch('builtins.print') def", "'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no') mock_print.assert_called_with('\\tInvalid input: use yes or no')", "in ['yes', 'no']: return 'use yes or no' mock_input.side_effect =", "easy2fa import cli class TestCheckInput(TestCase): @patch('builtins.input') def test_default(self, mock_input): mock_input.return_value", "@patch('builtins.print') def test_assertions(self, mock_print, mock_input): def assertion(value): if value not", "mock_input.return_value = 'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input') @patch('builtins.print') def test_assertions(self,", "mock_input): def assertion(value): if value not in ['yes', 'no']: return", "cli class TestCheckInput(TestCase): @patch('builtins.input') def test_default(self, mock_input): mock_input.return_value = ''", "@patch('builtins.input') @patch('builtins.print') def test_assertions(self, mock_print, mock_input): def assertion(value): if value", "from unittest.mock import patch from easy2fa import cli class TestCheckInput(TestCase):", "from easy2fa import cli class TestCheckInput(TestCase): @patch('builtins.input') def test_default(self, mock_input):", "def test_assertions(self, mock_print, mock_input): def assertion(value): if value not in", "'use yes or no' mock_input.side_effect = ['input', '', 'no'] self.assertEquals(cli.check_input('prompt',", "'', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no') mock_print.assert_called_with('\\tInvalid input: use yes or", "def test_default(self, mock_input): mock_input.return_value = '' self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value", "= 'two' self.assertEquals(cli.check_input('prompt', default='one'), 'two') @patch('builtins.input') @patch('builtins.print') def test_assertions(self, mock_print,", "test_default(self, mock_input): mock_input.return_value = '' self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value =", "= ['input', '', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no') mock_print.assert_called_with('\\tInvalid input: use", "not in ['yes', 'no']: return 'use yes or no' mock_input.side_effect", "class TestCheckInput(TestCase): @patch('builtins.input') def test_default(self, mock_input): mock_input.return_value = '' self.assertEquals(cli.check_input('prompt',", "from unittest import TestCase from unittest.mock import patch from easy2fa", "TestCase from unittest.mock import patch from easy2fa import cli class", "'no']: return 'use yes or no' mock_input.side_effect = ['input', '',", "unittest.mock import patch from easy2fa import cli class TestCheckInput(TestCase): @patch('builtins.input')", "def assertion(value): if value not in ['yes', 'no']: return 'use", "mock_input): mock_input.return_value = '' self.assertEquals(cli.check_input('prompt', default='one'), 'one') mock_input.return_value = 'two'", "or no' mock_input.side_effect = ['input', '', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no')", "assertion(value): if value not in ['yes', 'no']: return 'use yes", "patch from easy2fa import cli class TestCheckInput(TestCase): @patch('builtins.input') def test_default(self,", "@patch('builtins.input') def test_default(self, mock_input): mock_input.return_value = '' self.assertEquals(cli.check_input('prompt', default='one'), 'one')", "no' mock_input.side_effect = ['input', '', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no') mock_print.assert_called_with('\\tInvalid", "yes or no' mock_input.side_effect = ['input', '', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion),", "if value not in ['yes', 'no']: return 'use yes or", "['input', '', 'no'] self.assertEquals(cli.check_input('prompt', assertion=assertion), 'no') mock_print.assert_called_with('\\tInvalid input: use yes" ]
[ "def create_loaders(self): \"\"\" Create Torch dataloaders for data splits \"\"\"", "print(\"finished creating dataloaders\") \"\"\" ** FOR DEBUGGING ** if __name__", "{ \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths =", "\"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\",", "self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler = SequentialSampler(validation_data) self.validation_dataloader = DataLoader(", "from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from bert_finetuning.data import", "def __init__( self, data_paths, model_name, do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData, ):", "} ## create dataloaders print(\"creating germeval dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths)", "SequentialSampler(validation_data) self.validation_dataloader = DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size ) test_data =", "\"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create dataloaders print(\"creating", "__init__( self, data_paths, model_name, do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData, ): self.german_data", "splits \"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data = TensorDataset( self.german_data.train_inputs, self.german_data.train_masks,", "GermanDataLoader: def __init__( self, data_paths, model_name, do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData,", "self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data = TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, )", "self.german_data.validation_labels, ) validation_sampler = SequentialSampler(validation_data) self.validation_dataloader = DataLoader( validation_data, sampler=validation_sampler,", "germeval_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", }", "\"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\",", "model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size = batch_size self.create_loaders() def create_loaders(self):", "data_paths, model_name, do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData, ): self.german_data = dataset_cls(", "GermanData class GermanDataLoader: def __init__( self, data_paths, model_name, do_cleansing, max_sequence_length,", "train_data, sampler=train_sampler, batch_size=self.batch_size ) validation_data = TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels,", "data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size = batch_size self.create_loaders() def", "= { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths", "= TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, ) test_sampler = SequentialSampler(test_data) self.test_dataloader", "train_data = TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, ) train_sampler = RandomSampler(train_data)", "self.test_dataloader = DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size ) print(\"finished creating dataloaders\")", "FOR DEBUGGING ** if __name__ == \"__main__\": ## define data", "\"\"\" Create Torch dataloaders for data splits \"\"\" self.german_data.text_to_tensors() print(\"creating", "model_name, do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData, ): self.german_data = dataset_cls( data_paths,", "RandomSampler(train_data) self.train_dataloader = DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size ) validation_data =", "test_data = TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, ) test_sampler = SequentialSampler(test_data)", "self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, ) train_sampler = RandomSampler(train_data) self.train_dataloader = DataLoader(", "sampler=test_sampler, batch_size=self.batch_size ) print(\"finished creating dataloaders\") \"\"\" ** FOR DEBUGGING", "self.german_data.test_labels, ) test_sampler = SequentialSampler(test_data) self.test_dataloader = DataLoader( test_data, sampler=test_sampler,", "import TensorDataset, DataLoader, RandomSampler, SequentialSampler from bert_finetuning.data import GermanData class", "self, data_paths, model_name, do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData, ): self.german_data =", "data paths germeval_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\":", "\"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data = TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels,", "self.german_data = dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size =", "create_loaders(self): \"\"\" Create Torch dataloaders for data splits \"\"\" self.german_data.text_to_tensors()", ") test_sampler = SequentialSampler(test_data) self.test_dataloader = DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size", ") self.batch_size = batch_size self.create_loaders() def create_loaders(self): \"\"\" Create Torch", "bert_finetuning.data import GermanData class GermanDataLoader: def __init__( self, data_paths, model_name,", "= DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size ) test_data = TensorDataset( self.german_data.test_inputs,", "\"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths = {", "self.validation_dataloader = DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size ) test_data = TensorDataset(", "class GermanDataLoader: def __init__( self, data_paths, model_name, do_cleansing, max_sequence_length, batch_size=8,", "** FOR DEBUGGING ** if __name__ == \"__main__\": ## define", "import GermanData class GermanDataLoader: def __init__( self, data_paths, model_name, do_cleansing,", "= { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ##", "\"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths = { \"train\":", "** if __name__ == \"__main__\": ## define data paths germeval_data_paths", "germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating hasoc dataloaders...\") hasoc_german_dataloader = GermanDataLoader(hasoc_german_data_paths) \"\"\"", "## define data paths germeval_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\":", "\"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\":", "validation_data, sampler=validation_sampler, batch_size=self.batch_size ) test_data = TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels,", "## create dataloaders print(\"creating germeval dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating", "germeval dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating hasoc dataloaders...\") hasoc_german_dataloader =", "dataloaders\") train_data = TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, ) train_sampler =", "from bert_finetuning.data import GermanData class GermanDataLoader: def __init__( self, data_paths,", ") train_sampler = RandomSampler(train_data) self.train_dataloader = DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size", "DEBUGGING ** if __name__ == \"__main__\": ## define data paths", "self.german_data.test_masks, self.german_data.test_labels, ) test_sampler = SequentialSampler(test_data) self.test_dataloader = DataLoader( test_data,", "print(\"creating dataloaders\") train_data = TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, ) train_sampler", ") validation_sampler = SequentialSampler(validation_data) self.validation_dataloader = DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size", "== \"__main__\": ## define data paths germeval_data_paths = { \"train\":", "dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating hasoc dataloaders...\") hasoc_german_dataloader = GermanDataLoader(hasoc_german_data_paths)", "DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size ) test_data = TensorDataset( self.german_data.test_inputs, self.german_data.test_masks,", "Torch dataloaders for data splits \"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data", "TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, ) train_sampler = RandomSampler(train_data) self.train_dataloader =", "self.german_data.train_labels, ) train_sampler = RandomSampler(train_data) self.train_dataloader = DataLoader( train_data, sampler=train_sampler,", "= TensorDataset( self.german_data.train_inputs, self.german_data.train_masks, self.german_data.train_labels, ) train_sampler = RandomSampler(train_data) self.train_dataloader", "\"\"\" ** FOR DEBUGGING ** if __name__ == \"__main__\": ##", "print(\"creating germeval dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating hasoc dataloaders...\") hasoc_german_dataloader", "= SequentialSampler(test_data) self.test_dataloader = DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size ) print(\"finished", "batch_size self.create_loaders() def create_loaders(self): \"\"\" Create Torch dataloaders for data", ") print(\"finished creating dataloaders\") \"\"\" ** FOR DEBUGGING ** if", "paths germeval_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\",", "DataLoader, RandomSampler, SequentialSampler from bert_finetuning.data import GermanData class GermanDataLoader: def", "): self.german_data = dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size", "self.batch_size = batch_size self.create_loaders() def create_loaders(self): \"\"\" Create Torch dataloaders", "= batch_size self.create_loaders() def create_loaders(self): \"\"\" Create Torch dataloaders for", "test_sampler = SequentialSampler(test_data) self.test_dataloader = DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size )", "hasoc_german_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", }", "\"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create dataloaders print(\"creating germeval dataloaders...\")", "validation_sampler = SequentialSampler(validation_data) self.validation_dataloader = DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size )", "self.create_loaders() def create_loaders(self): \"\"\" Create Torch dataloaders for data splits", "dataset_cls=GermanData, ): self.german_data = dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, )", "batch_size=self.batch_size ) test_data = TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, ) test_sampler", "= DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size ) validation_data = TensorDataset( self.german_data.validation_inputs,", "DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size ) print(\"finished creating dataloaders\") \"\"\" **", "sampler=validation_sampler, batch_size=self.batch_size ) test_data = TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, )", "= RandomSampler(train_data) self.train_dataloader = DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size ) validation_data", "TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, ) test_sampler = SequentialSampler(test_data) self.test_dataloader =", "\"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create dataloaders print(\"creating germeval dataloaders...\") germ_eval_dataloader =", "for data splits \"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data = TensorDataset(", "self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler = SequentialSampler(validation_data) self.validation_dataloader = DataLoader( validation_data,", "train_sampler = RandomSampler(train_data) self.train_dataloader = DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size )", "Create Torch dataloaders for data splits \"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\")", "= DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size ) print(\"finished creating dataloaders\") \"\"\"", "sampler=train_sampler, batch_size=self.batch_size ) validation_data = TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, )", "} hasoc_german_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\",", "dataloaders print(\"creating germeval dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating hasoc dataloaders...\")", "creating dataloaders\") \"\"\" ** FOR DEBUGGING ** if __name__ ==", "SequentialSampler from bert_finetuning.data import GermanData class GermanDataLoader: def __init__( self,", "self.german_data.train_masks, self.german_data.train_labels, ) train_sampler = RandomSampler(train_data) self.train_dataloader = DataLoader( train_data,", "DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size ) validation_data = TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks,", "TensorDataset, DataLoader, RandomSampler, SequentialSampler from bert_finetuning.data import GermanData class GermanDataLoader:", "dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size = batch_size self.create_loaders()", "test_data, sampler=test_sampler, batch_size=self.batch_size ) print(\"finished creating dataloaders\") \"\"\" ** FOR", ") validation_data = TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler =", "create dataloaders print(\"creating germeval dataloaders...\") germ_eval_dataloader = GermanDataLoader(germeval_data_paths) print(\"creating hasoc", "batch_size=8, dataset_cls=GermanData, ): self.german_data = dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing,", "__name__ == \"__main__\": ## define data paths germeval_data_paths = {", "\"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create dataloaders print(\"creating germeval dataloaders...\") germ_eval_dataloader", "data splits \"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data = TensorDataset( self.german_data.train_inputs,", "{ \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create", "= TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler = SequentialSampler(validation_data) self.validation_dataloader", "batch_size=self.batch_size ) validation_data = TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler", "do_cleansing=do_cleansing, ) self.batch_size = batch_size self.create_loaders() def create_loaders(self): \"\"\" Create", "dataloaders for data splits \"\"\" self.german_data.text_to_tensors() print(\"creating dataloaders\") train_data =", "if __name__ == \"__main__\": ## define data paths germeval_data_paths =", "RandomSampler, SequentialSampler from bert_finetuning.data import GermanData class GermanDataLoader: def __init__(", "\"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } hasoc_german_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\":", "batch_size=self.batch_size ) print(\"finished creating dataloaders\") \"\"\" ** FOR DEBUGGING **", ") test_data = TensorDataset( self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, ) test_sampler =", "max_sequence_length, batch_size=8, dataset_cls=GermanData, ): self.german_data = dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length,", "define data paths germeval_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\",", "= dataset_cls( data_paths, model_name, max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size = batch_size", "SequentialSampler(test_data) self.test_dataloader = DataLoader( test_data, sampler=test_sampler, batch_size=self.batch_size ) print(\"finished creating", "= SequentialSampler(validation_data) self.validation_dataloader = DataLoader( validation_data, sampler=validation_sampler, batch_size=self.batch_size ) test_data", "\"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\", \"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create dataloaders", "validation_data = TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler = SequentialSampler(validation_data)", "\"__main__\": ## define data paths germeval_data_paths = { \"train\": \"./datasets/hasoc_dataset/hasoc_german_train.csv\",", "\"dev\": \"./datasets/hasoc_dataset/hasoc_german_validation.csv\", \"test\": \"./datasets/hasoc_dataset/hasoc_german_test.csv\", } ## create dataloaders print(\"creating germeval", "dataloaders\") \"\"\" ** FOR DEBUGGING ** if __name__ == \"__main__\":", "self.train_dataloader = DataLoader( train_data, sampler=train_sampler, batch_size=self.batch_size ) validation_data = TensorDataset(", "TensorDataset( self.german_data.validation_inputs, self.german_data.validation_masks, self.german_data.validation_labels, ) validation_sampler = SequentialSampler(validation_data) self.validation_dataloader =", "torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from bert_finetuning.data import GermanData", "do_cleansing, max_sequence_length, batch_size=8, dataset_cls=GermanData, ): self.german_data = dataset_cls( data_paths, model_name,", "max_sequence_length=max_sequence_length, do_cleansing=do_cleansing, ) self.batch_size = batch_size self.create_loaders() def create_loaders(self): \"\"\"", "self.german_data.test_inputs, self.german_data.test_masks, self.german_data.test_labels, ) test_sampler = SequentialSampler(test_data) self.test_dataloader = DataLoader(" ]
[ "train_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) valid_dataset =", "valid_subset = Subset(valid_dataset, valid_idx) train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True)", "data from torch.utils.data import Subset from data.fast_mnist import create_MNIST_dataset from", ">= 0) and (val_size <= 1), error_msg # load the", "_ = create_MNIST_dataset() # AmbiguousMNIST does whiten the data itself", "torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") train_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root,", "0) and (val_size <= 1), error_msg # load the dataset", "valid_idx = indices[split:], indices[:split] train_subset = Subset(train_dataset, train_idx) valid_subset =", "device=device),] ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0) return test_loader", "torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") test_dataset = data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root,", "if torch.cuda.is_available() else \"cpu\") train_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True,", "mnist_test_dataset = create_MNIST_dataset() device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")", "error_msg = \"[!] val_size should be in the range [0,", "numpy as np import torch.utils.data as data from torch.utils.data import", "data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) num_train = len(train_dataset) indices", "AmbiguousMNIST(root=root, train=True, device=device),] ) num_train = len(train_dataset) indices = list(range(num_train))", "indices[:split] train_subset = Subset(train_dataset, train_idx) valid_subset = Subset(valid_dataset, valid_idx) train_loader", "else \"cpu\") test_dataset = data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),] )", "create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1,", "data.fast_mnist import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def get_train_valid_loader(root, batch_size,", "= Subset(valid_dataset, valid_idx) train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True) valid_loader", "indices = list(range(num_train)) split = int(np.floor(val_size * num_train)) np.random.seed(val_seed) np.random.shuffle(indices)", "train=True, device=device),] ) num_train = len(train_dataset) indices = list(range(num_train)) split", "as np import torch.utils.data as data from torch.utils.data import Subset", "in the range [0, 1].\" assert (val_size >= 0) and", "* num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] train_subset", "AmbiguousMNIST does whiten the data itself device = torch.device(\"cuda\" if", "\"cpu\") train_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) valid_dataset", "[mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) num_train = len(train_dataset) indices =", ") num_train = len(train_dataset) indices = list(range(num_train)) split = int(np.floor(val_size", "int(np.floor(val_size * num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split]", "from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1, **kwargs):", "does whiten the data itself device = torch.device(\"cuda\" if torch.cuda.is_available()", "= list(range(num_train)) split = int(np.floor(val_size * num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx,", "def get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1, **kwargs): error_msg = \"[!] val_size", "split = int(np.floor(val_size * num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx =", "[mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),] ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False,", "# load the dataset mnist_train_dataset, _ = create_MNIST_dataset() # AmbiguousMNIST", "train_subset = Subset(train_dataset, train_idx) valid_subset = Subset(valid_dataset, valid_idx) train_loader =", "<reponame>Karthik-Ragunath/DDU<filename>data/dirty_mnist.py import torch import numpy as np import torch.utils.data as", "val_size should be in the range [0, 1].\" assert (val_size", "get_test_loader(root, batch_size, **kwargs): # load the dataset _, mnist_test_dataset =", "device=device),] ) num_train = len(train_dataset) indices = list(range(num_train)) split =", "np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] train_subset = Subset(train_dataset,", "train_idx) valid_subset = Subset(valid_dataset, valid_idx) train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0,", "import torch.utils.data as data from torch.utils.data import Subset from data.fast_mnist", "else \"cpu\") train_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] )", "should be in the range [0, 1].\" assert (val_size >=", "return train_loader, valid_loader def get_test_loader(root, batch_size, **kwargs): # load the", "AmbiguousMNIST(root=root, train=True, device=device),] ) valid_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True,", "AmbiguousMNIST(root=root, train=False, device=device),] ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0)", "np import torch.utils.data as data from torch.utils.data import Subset from", "data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) valid_dataset = data.ConcatDataset( [mnist_train_dataset,", "the dataset _, mnist_test_dataset = create_MNIST_dataset() device = torch.device(\"cuda\" if", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") test_dataset = data.ConcatDataset(", "Subset(valid_dataset, valid_idx) train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True) valid_loader =", "[0, 1].\" assert (val_size >= 0) and (val_size <= 1),", "\"[!] val_size should be in the range [0, 1].\" assert", "itself device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") train_dataset =", "= torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") train_dataset = data.ConcatDataset( [mnist_train_dataset,", "train=True, device=device),] ) valid_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),]", "as data from torch.utils.data import Subset from data.fast_mnist import create_MNIST_dataset", "1), error_msg # load the dataset mnist_train_dataset, _ = create_MNIST_dataset()", "train_loader, valid_loader def get_test_loader(root, batch_size, **kwargs): # load the dataset", "the range [0, 1].\" assert (val_size >= 0) and (val_size", "= int(np.floor(val_size * num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx = indices[split:],", "data itself device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") train_dataset", "Subset(train_dataset, train_idx) valid_subset = Subset(valid_dataset, valid_idx) train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size,", "AmbiguousMNIST def get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1, **kwargs): error_msg = \"[!]", "1].\" assert (val_size >= 0) and (val_size <= 1), error_msg", "torch.utils.data as data from torch.utils.data import Subset from data.fast_mnist import", "assert (val_size >= 0) and (val_size <= 1), error_msg #", "= Subset(train_dataset, train_idx) valid_subset = Subset(valid_dataset, valid_idx) train_loader = torch.utils.data.DataLoader(train_subset,", "torch.cuda.is_available() else \"cpu\") train_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),]", "range [0, 1].\" assert (val_size >= 0) and (val_size <=", "num_workers=0, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False) return train_loader,", "list(range(num_train)) split = int(np.floor(val_size * num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx", "(val_size >= 0) and (val_size <= 1), error_msg # load", "= data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) num_train = len(train_dataset)", "num_workers=0, shuffle=False) return train_loader, valid_loader def get_test_loader(root, batch_size, **kwargs): #", "train_idx, valid_idx = indices[split:], indices[:split] train_subset = Subset(train_dataset, train_idx) valid_subset", "val_seed=1, val_size=0.1, **kwargs): error_msg = \"[!] val_size should be in", "mnist_train_dataset, _ = create_MNIST_dataset() # AmbiguousMNIST does whiten the data", "train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size,", "(val_size <= 1), error_msg # load the dataset mnist_train_dataset, _", "batch_size=batch_size, num_workers=0, shuffle=False) return train_loader, valid_loader def get_test_loader(root, batch_size, **kwargs):", "num_train)) np.random.seed(val_seed) np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] train_subset =", "device=device),] ) valid_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] )", "be in the range [0, 1].\" assert (val_size >= 0)", "valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False) return train_loader, valid_loader def", "batch_size, **kwargs): # load the dataset _, mnist_test_dataset = create_MNIST_dataset()", "Subset from data.fast_mnist import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def", "<= 1), error_msg # load the dataset mnist_train_dataset, _ =", "dataset mnist_train_dataset, _ = create_MNIST_dataset() # AmbiguousMNIST does whiten the", "the data itself device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")", "# AmbiguousMNIST does whiten the data itself device = torch.device(\"cuda\"", "len(train_dataset) indices = list(range(num_train)) split = int(np.floor(val_size * num_train)) np.random.seed(val_seed)", "torch import numpy as np import torch.utils.data as data from", "import torch import numpy as np import torch.utils.data as data", "np.random.shuffle(indices) train_idx, valid_idx = indices[split:], indices[:split] train_subset = Subset(train_dataset, train_idx)", "load the dataset _, mnist_test_dataset = create_MNIST_dataset() device = torch.device(\"cuda\"", "and (val_size <= 1), error_msg # load the dataset mnist_train_dataset,", "test_dataset = data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),] ) test_loader =", "**kwargs): # load the dataset _, mnist_test_dataset = create_MNIST_dataset() device", "load the dataset mnist_train_dataset, _ = create_MNIST_dataset() # AmbiguousMNIST does", "val_size=0.1, **kwargs): error_msg = \"[!] val_size should be in the", "import Subset from data.fast_mnist import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST", "shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False) return train_loader, valid_loader", "dataset _, mnist_test_dataset = create_MNIST_dataset() device = torch.device(\"cuda\" if torch.cuda.is_available()", "num_train = len(train_dataset) indices = list(range(num_train)) split = int(np.floor(val_size *", "**kwargs): error_msg = \"[!] val_size should be in the range", "create_MNIST_dataset() # AmbiguousMNIST does whiten the data itself device =", "import numpy as np import torch.utils.data as data from torch.utils.data", "train=False, device=device),] ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=0) return", "# load the dataset _, mnist_test_dataset = create_MNIST_dataset() device =", "torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False)", "error_msg # load the dataset mnist_train_dataset, _ = create_MNIST_dataset() #", "= torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0,", "import AmbiguousMNIST def get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1, **kwargs): error_msg =", "indices[split:], indices[:split] train_subset = Subset(train_dataset, train_idx) valid_subset = Subset(valid_dataset, valid_idx)", "torch.utils.data import Subset from data.fast_mnist import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import", "= data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),] ) test_loader = torch.utils.data.DataLoader(test_dataset,", "data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),] ) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size,", "from data.fast_mnist import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def get_train_valid_loader(root,", "shuffle=False) return train_loader, valid_loader def get_test_loader(root, batch_size, **kwargs): # load", "valid_idx) train_loader = torch.utils.data.DataLoader(train_subset, batch_size=batch_size, num_workers=0, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset,", "[mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) valid_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root,", "= data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) valid_dataset = data.ConcatDataset(", "= create_MNIST_dataset() # AmbiguousMNIST does whiten the data itself device", "torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False) return train_loader, valid_loader def get_test_loader(root, batch_size,", "if torch.cuda.is_available() else \"cpu\") test_dataset = data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False,", "= len(train_dataset) indices = list(range(num_train)) split = int(np.floor(val_size * num_train))", "batch_size, val_seed=1, val_size=0.1, **kwargs): error_msg = \"[!] val_size should be", "= create_MNIST_dataset() device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") test_dataset", "valid_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) num_train =", "= torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") test_dataset = data.ConcatDataset( [mnist_test_dataset,", "the dataset mnist_train_dataset, _ = create_MNIST_dataset() # AmbiguousMNIST does whiten", "= \"[!] val_size should be in the range [0, 1].\"", "import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def get_train_valid_loader(root, batch_size, val_seed=1,", "batch_size=batch_size, num_workers=0, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False) return", "= torch.utils.data.DataLoader(valid_subset, batch_size=batch_size, num_workers=0, shuffle=False) return train_loader, valid_loader def get_test_loader(root,", "whiten the data itself device = torch.device(\"cuda\" if torch.cuda.is_available() else", "valid_loader def get_test_loader(root, batch_size, **kwargs): # load the dataset _,", "create_MNIST_dataset() device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") test_dataset =", "\"cpu\") test_dataset = data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),] ) test_loader", ") valid_dataset = data.ConcatDataset( [mnist_train_dataset, AmbiguousMNIST(root=root, train=True, device=device),] ) num_train", "get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1, **kwargs): error_msg = \"[!] val_size should", "from torch.utils.data import Subset from data.fast_mnist import create_MNIST_dataset from data.ambiguous_mnist.ambiguous_mnist_dataset", "data.ambiguous_mnist.ambiguous_mnist_dataset import AmbiguousMNIST def get_train_valid_loader(root, batch_size, val_seed=1, val_size=0.1, **kwargs): error_msg", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") train_dataset = data.ConcatDataset(", "= indices[split:], indices[:split] train_subset = Subset(train_dataset, train_idx) valid_subset = Subset(valid_dataset,", "def get_test_loader(root, batch_size, **kwargs): # load the dataset _, mnist_test_dataset", "_, mnist_test_dataset = create_MNIST_dataset() device = torch.device(\"cuda\" if torch.cuda.is_available() else", "torch.cuda.is_available() else \"cpu\") test_dataset = data.ConcatDataset( [mnist_test_dataset, AmbiguousMNIST(root=root, train=False, device=device),]" ]
[ "'{user.username}'\") # generate a token that can reset their password", "requested for '{user.username}'\") # generate a token that can reset", "an email\"} # obtain username/email from request' body = request.get_json()", "coding: utf-8 -*- import logging import datetime from flask import", "import request, render_template from flask_jwt_extended import ( create_access_token, decode_token )", "# ------------------------------------------------------------------------------ # Resources / API's # ------------------------------------------------------------------------------ class ResetPassword(ServicesResources):", "= request.get_json() reset_token = body.get(\"reset_token\") password = body.get(\"password\") if not", "user try: user_id = decode_token(reset_token)['identity'].get('id') except DecodeError: return {\"msg\": \"Invalid", "# retrieve user based on email or username body =", "password = body.get(\"password\") if not reset_token or not password: return", "not here we stop! try: if username: user = db.User.get_by_username(username)", "= body.get(\"username\") email = body.get(\"email\") if not (email or username):", "reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self): \"\"\"\"submit email-adress receive", "body.get(\"email\") if not (email or username): return {\"msg\": \"No username", "decode_token(reset_token)['identity'].get('id') except DecodeError: return {\"msg\": \"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id)", "a token that can reset their password expires = datetime.timedelta(hours=1)", "= body.get(\"email\") if not (email or username): return {\"msg\": \"No", "path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services ) # ------------------------------------------------------------------------------ # Resources /", "email generates a token which is mailed.\"\"\" # default return", ") from jwt.exceptions import DecodeError from flasgger import swag_from from", "username body = request.get_json() reset_token = body.get(\"reset_token\") password = body.get(\"password\")", "db.User.get_by_username(username) else: user = db.User.get_by_email(email) except NoResultFound: # we do", "endpoint='recover_password', methods=('POST',), resource_class_kwargs=services ) # ------------------------------------------------------------------------------ # Resources / API's", "flask import request, render_template from flask_jwt_extended import ( create_access_token, decode_token", "{\"msg\": \"password successfully been reset!\"}, \\ HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send", "from jwt.exceptions import DecodeError from flasgger import swag_from from http", "from vantage6.server import db from vantage6.server.resource import ( ServicesResources )", "password user.set_password(password) user.save() log.info(f\"Successfull password reset for '{user.username}'\") return {\"msg\":", "body = request.get_json() reset_token = body.get(\"reset_token\") password = body.get(\"password\") if", "return string ret = {\"msg\": \"If the username or email", "def setup(api, api_base, services): path = \"/\".join([api_base, module_name]) log.info(f'Setting up", "up \"{path}\" and subdirectories') api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services", "HTTPStatus.BAD_REQUEST # obtain user try: user_id = decode_token(reset_token)['identity'].get('id') except DecodeError:", "# generate a token that can reset their password expires", "reset!\"}, \\ HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send a mail containing a", "\"will soon receive an email\"} # obtain username/email from request'", "{\"msg\": \"If the username or email is our database you", "api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services ) api.add_resource( RecoverPassword, path+'/lost',", "db.User.get(user_id) # set password user.set_password(password) user.save() log.info(f\"Successfull password reset for", "their password expires = datetime.timedelta(hours=1) reset_token = create_access_token( {\"id\": str(user.id)},", "import DecodeError from flasgger import swag_from from http import HTTPStatus", "not password: return {\"msg\": \"reset token and/or password is missing!\"},", "logging import datetime from flask import request, render_template from flask_jwt_extended", "methods=('POST',), resource_class_kwargs=services ) api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services )", "@swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self): \"\"\"username or email generates a token", "soon receive an email\"} # obtain username/email from request' body", "vantage6.server.resource import ( ServicesResources ) module_name = logger_name(__name__) log =", "request.get_json() reset_token = body.get(\"reset_token\") password = body.get(\"password\") if not reset_token", "\\ HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send a mail containing a recover", "import NoResultFound from vantage6.common import logger_name from vantage6.server import db", "or email generates a token which is mailed.\"\"\" # default", "= body.get(\"reset_token\") password = body.get(\"password\") if not reset_token or not", "HTTPStatus from pathlib import Path from sqlalchemy.orm.exc import NoResultFound from", "reset_token or not password: return {\"msg\": \"reset token and/or password", "email is our database you \" \"will soon receive an", "their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self): \"\"\"\"submit email-adress receive token.\"\"\"", "module_name]) log.info(f'Setting up \"{path}\" and subdirectories') api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\",", "return {\"msg\": \"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user = db.User.get(user_id)", "a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self): \"\"\"username or email", "------------------------------------------------------------------------------ # Resources / API's # ------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user", "import swag_from from http import HTTPStatus from pathlib import Path", "password is missing!\"}, \\ HTTPStatus.BAD_REQUEST # obtain user try: user_id", "database, if not here we stop! try: if username: user", "recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self): \"\"\"username or email generates", "= \"/\".join([api_base, module_name]) log.info(f'Setting up \"{path}\" and subdirectories') api.add_resource( ResetPassword,", "But we won't continue either return ret log.info(f\"Password reset requested", "username = body.get(\"username\") email = body.get(\"email\") if not (email or", "obtain user try: user_id = decode_token(reset_token)['identity'].get('id') except DecodeError: return {\"msg\":", "sqlalchemy.orm.exc import NoResultFound from vantage6.common import logger_name from vantage6.server import", "for '{user.username}'\") # generate a token that can reset their", "log = logging.getLogger(module_name) def setup(api, api_base, services): path = \"/\".join([api_base,", "reset_token = body.get(\"reset_token\") password = body.get(\"password\") if not reset_token or", "ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services ) api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password',", "resource_class_kwargs=services ) # ------------------------------------------------------------------------------ # Resources / API's # ------------------------------------------------------------------------------", "RecoverPassword(ServicesResources): \"\"\"send a mail containing a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password')", "is our database you \" \"will soon receive an email\"}", "render_template from flask_jwt_extended import ( create_access_token, decode_token ) from jwt.exceptions", "HTTPStatus.BAD_REQUEST log.debug(user_id) user = db.User.get(user_id) # set password user.set_password(password) user.save()", "datetime from flask import request, render_template from flask_jwt_extended import (", "\"password successfully been reset!\"}, \\ HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send a", "\"{path}\" and subdirectories') api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services )", "(email or username): return {\"msg\": \"No username or email provided!\"},", "if not (email or username): return {\"msg\": \"No username or", "subdirectories') api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services ) api.add_resource( RecoverPassword,", "api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services ) # ------------------------------------------------------------------------------ #", ") # ------------------------------------------------------------------------------ # Resources / API's # ------------------------------------------------------------------------------ class", "based on email or username body = request.get_json() reset_token =", "endpoint='reset_password') def post(self): \"\"\"\"submit email-adress receive token.\"\"\" # retrieve user", "from request' body = request.get_json() username = body.get(\"username\") email =", "endpoint='recover_password') def post(self): \"\"\"username or email generates a token which", "mailed.\"\"\" # default return string ret = {\"msg\": \"If the", ") module_name = logger_name(__name__) log = logging.getLogger(module_name) def setup(api, api_base,", "Path from sqlalchemy.orm.exc import NoResultFound from vantage6.common import logger_name from", "RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services ) # ------------------------------------------------------------------------------ # Resources", "user = db.User.get(user_id) # set password user.set_password(password) user.save() log.info(f\"Successfull password", "create_access_token, decode_token ) from jwt.exceptions import DecodeError from flasgger import", "from flasgger import swag_from from http import HTTPStatus from pathlib", "not (email or username): return {\"msg\": \"No username or email", "= db.User.get_by_email(email) except NoResultFound: # we do not tell them....", "\"If the username or email is our database you \"", "to reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self): \"\"\"\"submit email-adress", "or email is our database you \" \"will soon receive", "reset for '{user.username}'\") return {\"msg\": \"password successfully been reset!\"}, \\", "\\ HTTPStatus.BAD_REQUEST # obtain user try: user_id = decode_token(reset_token)['identity'].get('id') except", "\"\"\"send a mail containing a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def", "token which is mailed.\"\"\" # default return string ret =", "def post(self): \"\"\"username or email generates a token which is", "body = request.get_json() username = body.get(\"username\") email = body.get(\"email\") if", "generate a token that can reset their password expires =", "methods=('POST',), resource_class_kwargs=services ) # ------------------------------------------------------------------------------ # Resources / API's #", "from flask_jwt_extended import ( create_access_token, decode_token ) from jwt.exceptions import", "vantage6.server import db from vantage6.server.resource import ( ServicesResources ) module_name", "the database, if not here we stop! try: if username:", "from vantage6.common import logger_name from vantage6.server import db from vantage6.server.resource", "\"password reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\", token=reset_token), html_body=render_template(\"mail/reset_password_token.html\", token=reset_token) ) return", "retrieve user based on email or username body = request.get_json()", "= logger_name(__name__) log = logging.getLogger(module_name) def setup(api, api_base, services): path", "use recover token to reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def", "username: user = db.User.get_by_username(username) else: user = db.User.get_by_email(email) except NoResultFound:", "db from vantage6.server.resource import ( ServicesResources ) module_name = logger_name(__name__)", "on email or username body = request.get_json() reset_token = body.get(\"reset_token\")", "expires = datetime.timedelta(hours=1) reset_token = create_access_token( {\"id\": str(user.id)}, expires_delta=expires )", "# set password user.set_password(password) user.save() log.info(f\"Successfull password reset for '{user.username}'\")", "from vantage6.server.resource import ( ServicesResources ) module_name = logger_name(__name__) log", "= request.get_json() username = body.get(\"username\") email = body.get(\"email\") if not", "username or email is our database you \" \"will soon", ") self.mail.send_email( \"password reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\", token=reset_token), html_body=render_template(\"mail/reset_password_token.html\", token=reset_token)", "reset their password expires = datetime.timedelta(hours=1) reset_token = create_access_token( {\"id\":", "( ServicesResources ) module_name = logger_name(__name__) log = logging.getLogger(module_name) def", "'{user.username}'\") return {\"msg\": \"password successfully been reset!\"}, \\ HTTPStatus.OK class", "email\"} # obtain username/email from request' body = request.get_json() username", "our database you \" \"will soon receive an email\"} #", "you \" \"will soon receive an email\"} # obtain username/email", "body.get(\"password\") if not reset_token or not password: return {\"msg\": \"reset", "HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send a mail containing a recover token\"\"\"", "from sqlalchemy.orm.exc import NoResultFound from vantage6.common import logger_name from vantage6.server", "missing!\"}, \\ HTTPStatus.BAD_REQUEST # obtain user try: user_id = decode_token(reset_token)['identity'].get('id')", "password expires = datetime.timedelta(hours=1) reset_token = create_access_token( {\"id\": str(user.id)}, expires_delta=expires", "containing a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self): \"\"\"username or", "# default return string ret = {\"msg\": \"If the username", "can reset their password expires = datetime.timedelta(hours=1) reset_token = create_access_token(", "receive token.\"\"\" # retrieve user based on email or username", "flasgger import swag_from from http import HTTPStatus from pathlib import", "if not here we stop! try: if username: user =", "or username): return {\"msg\": \"No username or email provided!\"}, \\", "------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user can use recover token to reset", "ResetPassword(ServicesResources): \"\"\"user can use recover token to reset their password.\"\"\"", "here we stop! try: if username: user = db.User.get_by_username(username) else:", "or email provided!\"}, \\ HTTPStatus.BAD_REQUEST # find user in the", "user = db.User.get_by_email(email) except NoResultFound: # we do not tell", "DecodeError: return {\"msg\": \"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user =", "HTTPStatus.BAD_REQUEST # find user in the database, if not here", "return {\"msg\": \"No username or email provided!\"}, \\ HTTPStatus.BAD_REQUEST #", "string ret = {\"msg\": \"If the username or email is", "Resources / API's # ------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user can use", "# -*- coding: utf-8 -*- import logging import datetime from", "import Path from sqlalchemy.orm.exc import NoResultFound from vantage6.common import logger_name", "path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services ) api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',),", "setup(api, api_base, services): path = \"/\".join([api_base, module_name]) log.info(f'Setting up \"{path}\"", "class ResetPassword(ServicesResources): \"\"\"user can use recover token to reset their", "token.\"\"\" # retrieve user based on email or username body", "we won't continue either return ret log.info(f\"Password reset requested for", "user in the database, if not here we stop! try:", "been reset!\"}, \\ HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send a mail containing", "module_name = logger_name(__name__) log = logging.getLogger(module_name) def setup(api, api_base, services):", "mail containing a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self): \"\"\"username", "find user in the database, if not here we stop!", "-*- coding: utf-8 -*- import logging import datetime from flask", "password reset for '{user.username}'\") return {\"msg\": \"password successfully been reset!\"},", "password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self): \"\"\"\"submit email-adress receive token.\"\"\" #", "we do not tell them.... But we won't continue either", "= body.get(\"password\") if not reset_token or not password: return {\"msg\":", "{\"msg\": \"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user = db.User.get(user_id) #", "{\"msg\": \"No username or email provided!\"}, \\ HTTPStatus.BAD_REQUEST # find", "user.set_password(password) user.save() log.info(f\"Successfull password reset for '{user.username}'\") return {\"msg\": \"password", "post(self): \"\"\"\"submit email-adress receive token.\"\"\" # retrieve user based on", "{\"id\": str(user.id)}, expires_delta=expires ) self.mail.send_email( \"password reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\",", "tell them.... But we won't continue either return ret log.info(f\"Password", "obtain username/email from request' body = request.get_json() username = body.get(\"username\")", "-*- import logging import datetime from flask import request, render_template", "str(user.id)}, expires_delta=expires ) self.mail.send_email( \"password reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\", token=reset_token),", "= datetime.timedelta(hours=1) reset_token = create_access_token( {\"id\": str(user.id)}, expires_delta=expires ) self.mail.send_email(", "if not reset_token or not password: return {\"msg\": \"reset token", "= create_access_token( {\"id\": str(user.id)}, expires_delta=expires ) self.mail.send_email( \"password reset\", sender=\"<EMAIL>\",", "http import HTTPStatus from pathlib import Path from sqlalchemy.orm.exc import", "= db.User.get(user_id) # set password user.set_password(password) user.save() log.info(f\"Successfull password reset", "import db from vantage6.server.resource import ( ServicesResources ) module_name =", "from http import HTTPStatus from pathlib import Path from sqlalchemy.orm.exc", "username): return {\"msg\": \"No username or email provided!\"}, \\ HTTPStatus.BAD_REQUEST", "provided!\"}, \\ HTTPStatus.BAD_REQUEST # find user in the database, if", "\\ HTTPStatus.BAD_REQUEST # find user in the database, if not", "token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self): \"\"\"username or email generates a", "we stop! try: if username: user = db.User.get_by_username(username) else: user", "import HTTPStatus from pathlib import Path from sqlalchemy.orm.exc import NoResultFound", "\"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user = db.User.get(user_id) # set", "{\"msg\": \"reset token and/or password is missing!\"}, \\ HTTPStatus.BAD_REQUEST #", "except DecodeError: return {\"msg\": \"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user", "= db.User.get_by_username(username) else: user = db.User.get_by_email(email) except NoResultFound: # we", "path = \"/\".join([api_base, module_name]) log.info(f'Setting up \"{path}\" and subdirectories') api.add_resource(", "try: user_id = decode_token(reset_token)['identity'].get('id') except DecodeError: return {\"msg\": \"Invalid recovery", "is missing!\"}, \\ HTTPStatus.BAD_REQUEST # obtain user try: user_id =", "a mail containing a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")), endpoint='recover_password') def post(self):", "reset_token = create_access_token( {\"id\": str(user.id)}, expires_delta=expires ) self.mail.send_email( \"password reset\",", "which is mailed.\"\"\" # default return string ret = {\"msg\":", "either return ret log.info(f\"Password reset requested for '{user.username}'\") # generate", "token and/or password is missing!\"}, \\ HTTPStatus.BAD_REQUEST # obtain user", "import logger_name from vantage6.server import db from vantage6.server.resource import (", "ret log.info(f\"Password reset requested for '{user.username}'\") # generate a token", "import ( ServicesResources ) module_name = logger_name(__name__) log = logging.getLogger(module_name)", "user_id = decode_token(reset_token)['identity'].get('id') except DecodeError: return {\"msg\": \"Invalid recovery token!\"},", "import datetime from flask import request, render_template from flask_jwt_extended import", "token that can reset their password expires = datetime.timedelta(hours=1) reset_token", "receive an email\"} # obtain username/email from request' body =", "@swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self): \"\"\"\"submit email-adress receive token.\"\"\" # retrieve", "from pathlib import Path from sqlalchemy.orm.exc import NoResultFound from vantage6.common", "email = body.get(\"email\") if not (email or username): return {\"msg\":", "recover token to reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self):", "not tell them.... But we won't continue either return ret", "# Resources / API's # ------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user can", "that can reset their password expires = datetime.timedelta(hours=1) reset_token =", "import ( create_access_token, decode_token ) from jwt.exceptions import DecodeError from", "log.info(f\"Password reset requested for '{user.username}'\") # generate a token that", "is mailed.\"\"\" # default return string ret = {\"msg\": \"If", "endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services ) api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services", "flask_jwt_extended import ( create_access_token, decode_token ) from jwt.exceptions import DecodeError", "ret = {\"msg\": \"If the username or email is our", "= {\"msg\": \"If the username or email is our database", "from flask import request, render_template from flask_jwt_extended import ( create_access_token,", "generates a token which is mailed.\"\"\" # default return string", "/ API's # ------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user can use recover", "email-adress receive token.\"\"\" # retrieve user based on email or", "create_access_token( {\"id\": str(user.id)}, expires_delta=expires ) self.mail.send_email( \"password reset\", sender=\"<EMAIL>\", recipients=[user.email],", "log.info(f\"Successfull password reset for '{user.username}'\") return {\"msg\": \"password successfully been", ") api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services ) # ------------------------------------------------------------------------------", "db.User.get_by_email(email) except NoResultFound: # we do not tell them.... But", "body.get(\"reset_token\") password = body.get(\"password\") if not reset_token or not password:", "\"\"\"\"submit email-adress receive token.\"\"\" # retrieve user based on email", "logger_name from vantage6.server import db from vantage6.server.resource import ( ServicesResources", "email provided!\"}, \\ HTTPStatus.BAD_REQUEST # find user in the database,", "stop! try: if username: user = db.User.get_by_username(username) else: user =", "\"No username or email provided!\"}, \\ HTTPStatus.BAD_REQUEST # find user", "or username body = request.get_json() reset_token = body.get(\"reset_token\") password =", "api_base, services): path = \"/\".join([api_base, module_name]) log.info(f'Setting up \"{path}\" and", "them.... But we won't continue either return ret log.info(f\"Password reset", "request' body = request.get_json() username = body.get(\"username\") email = body.get(\"email\")", "the username or email is our database you \" \"will", "return {\"msg\": \"reset token and/or password is missing!\"}, \\ HTTPStatus.BAD_REQUEST", "do not tell them.... But we won't continue either return", "datetime.timedelta(hours=1) reset_token = create_access_token( {\"id\": str(user.id)}, expires_delta=expires ) self.mail.send_email( \"password", "# obtain user try: user_id = decode_token(reset_token)['identity'].get('id') except DecodeError: return", "\"reset token and/or password is missing!\"}, \\ HTTPStatus.BAD_REQUEST # obtain", "decode_token ) from jwt.exceptions import DecodeError from flasgger import swag_from", "a token which is mailed.\"\"\" # default return string ret", "token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user = db.User.get(user_id) # set password user.set_password(password)", "self.mail.send_email( \"password reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\", token=reset_token), html_body=render_template(\"mail/reset_password_token.html\", token=reset_token) )", "pathlib import Path from sqlalchemy.orm.exc import NoResultFound from vantage6.common import", "reset requested for '{user.username}'\") # generate a token that can", "username/email from request' body = request.get_json() username = body.get(\"username\") email", "# ------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user can use recover token to", "for '{user.username}'\") return {\"msg\": \"password successfully been reset!\"}, \\ HTTPStatus.OK", "try: if username: user = db.User.get_by_username(username) else: user = db.User.get_by_email(email)", "return {\"msg\": \"password successfully been reset!\"}, \\ HTTPStatus.OK class RecoverPassword(ServicesResources):", "password: return {\"msg\": \"reset token and/or password is missing!\"}, \\", "continue either return ret log.info(f\"Password reset requested for '{user.username}'\") #", "NoResultFound: # we do not tell them.... But we won't", "= decode_token(reset_token)['identity'].get('id') except DecodeError: return {\"msg\": \"Invalid recovery token!\"}, HTTPStatus.BAD_REQUEST", "request, render_template from flask_jwt_extended import ( create_access_token, decode_token ) from", "recovery token!\"}, HTTPStatus.BAD_REQUEST log.debug(user_id) user = db.User.get(user_id) # set password", "except NoResultFound: # we do not tell them.... But we", "# we do not tell them.... But we won't continue", "can use recover token to reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password')", "\"/\".join([api_base, module_name]) log.info(f'Setting up \"{path}\" and subdirectories') api.add_resource( ResetPassword, path+'/reset',", "API's # ------------------------------------------------------------------------------ class ResetPassword(ServicesResources): \"\"\"user can use recover token", "else: user = db.User.get_by_email(email) except NoResultFound: # we do not", "def post(self): \"\"\"\"submit email-adress receive token.\"\"\" # retrieve user based", "reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\", token=reset_token), html_body=render_template(\"mail/reset_password_token.html\", token=reset_token) ) return ret", "swag_from from http import HTTPStatus from pathlib import Path from", "# obtain username/email from request' body = request.get_json() username =", "DecodeError from flasgger import swag_from from http import HTTPStatus from", "user.save() log.info(f\"Successfull password reset for '{user.username}'\") return {\"msg\": \"password successfully", "logger_name(__name__) log = logging.getLogger(module_name) def setup(api, api_base, services): path =", "class RecoverPassword(ServicesResources): \"\"\"send a mail containing a recover token\"\"\" @swag_from(str(Path(r\"swagger/post_recover_password.yaml\")),", "# find user in the database, if not here we", "token to reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")), endpoint='reset_password') def post(self): \"\"\"\"submit", "( create_access_token, decode_token ) from jwt.exceptions import DecodeError from flasgger", "database you \" \"will soon receive an email\"} # obtain", "and/or password is missing!\"}, \\ HTTPStatus.BAD_REQUEST # obtain user try:", "expires_delta=expires ) self.mail.send_email( \"password reset\", sender=\"<EMAIL>\", recipients=[user.email], text_body=render_template(\"mail/reset_password_token.txt\", token=reset_token), html_body=render_template(\"mail/reset_password_token.html\",", "and subdirectories') api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',), resource_class_kwargs=services ) api.add_resource(", "log.info(f'Setting up \"{path}\" and subdirectories') api.add_resource( ResetPassword, path+'/reset', endpoint=\"reset_password\", methods=('POST',),", "not reset_token or not password: return {\"msg\": \"reset token and/or", "if username: user = db.User.get_by_username(username) else: user = db.User.get_by_email(email) except", "logging.getLogger(module_name) def setup(api, api_base, services): path = \"/\".join([api_base, module_name]) log.info(f'Setting", "= logging.getLogger(module_name) def setup(api, api_base, services): path = \"/\".join([api_base, module_name])", "jwt.exceptions import DecodeError from flasgger import swag_from from http import", "log.debug(user_id) user = db.User.get(user_id) # set password user.set_password(password) user.save() log.info(f\"Successfull", "body.get(\"username\") email = body.get(\"email\") if not (email or username): return", "\"\"\"username or email generates a token which is mailed.\"\"\" #", "default return string ret = {\"msg\": \"If the username or", "or not password: return {\"msg\": \"reset token and/or password is", "user = db.User.get_by_username(username) else: user = db.User.get_by_email(email) except NoResultFound: #", "resource_class_kwargs=services ) api.add_resource( RecoverPassword, path+'/lost', endpoint='recover_password', methods=('POST',), resource_class_kwargs=services ) #", "username or email provided!\"}, \\ HTTPStatus.BAD_REQUEST # find user in", "import logging import datetime from flask import request, render_template from", "set password user.set_password(password) user.save() log.info(f\"Successfull password reset for '{user.username}'\") return", "NoResultFound from vantage6.common import logger_name from vantage6.server import db from", "post(self): \"\"\"username or email generates a token which is mailed.\"\"\"", "services): path = \"/\".join([api_base, module_name]) log.info(f'Setting up \"{path}\" and subdirectories')", "won't continue either return ret log.info(f\"Password reset requested for '{user.username}'\")", "utf-8 -*- import logging import datetime from flask import request,", "request.get_json() username = body.get(\"username\") email = body.get(\"email\") if not (email", "\" \"will soon receive an email\"} # obtain username/email from", "successfully been reset!\"}, \\ HTTPStatus.OK class RecoverPassword(ServicesResources): \"\"\"send a mail", "vantage6.common import logger_name from vantage6.server import db from vantage6.server.resource import", "user based on email or username body = request.get_json() reset_token", "email or username body = request.get_json() reset_token = body.get(\"reset_token\") password", "return ret log.info(f\"Password reset requested for '{user.username}'\") # generate a", "ServicesResources ) module_name = logger_name(__name__) log = logging.getLogger(module_name) def setup(api,", "\"\"\"user can use recover token to reset their password.\"\"\" @swag_from(str(Path(r\"swagger/post_reset_password.yaml\")),", "in the database, if not here we stop! try: if" ]
[ "Several middlewares can be chained. message_middleware = [middleware_function] # Some", "**kwargs) # There's also the possibility to pass in extra", "to pass in extra arguments or keywords arguments, for example:", "= \"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\") or \"\") # Build own", "for testing }, } @aws_sns_sqs(\"example-route1\") async def route1a(self, data: Any)", "# return_value = await func(*args, id='overridden', **kwargs) # Functinoality after", "the possibility to pass in extra arguments or keywords arguments,", "localstack is used for testing }, } @aws_sns_sqs(\"example-route1\") async def", "chained. message_middleware = [middleware_function] # Some options can be specified", "def route1a(self, data: Any) -> None: self.log('Received data (function: route1a)", "{ \"sns\": None, # For example 'http://localhost:4575' if localstack is", "is run on every incoming message. # Several middlewares can", "define credentials, used ports, hostnames, access log, etc. options =", "service.log(\"middleware before\") return_value = await func(*args, **kwargs) # There's also", "specify AWS region (example: 'eu-west-1') \"aws_access_key_id\": None, # specify AWS", "for testing \"sqs\": None, # For example 'http://localhost:4576' if localstack", "example discovery = [AWSSNSRegistration] # The message envelope class defines", "message envelope class defines how a message should be processed", "# There's also the possibility to pass in extra arguments", "sent and received # See tomodachi/envelope/json_base.py for a basic example", "async def middleware_function( func: Callable, service: Any, message: Any, topic:", "-> None: async def publish(data: Any, topic: str) -> None:", "Any, Callable, Dict import tomodachi from tomodachi import aws_sns_sqs, aws_sns_sqs_publish", "See tomodachi/envelope/json_base.py for a basic example using JSON and transferring", "\"\") # Build own \"discovery\" functions, to be run on", "example 'http://localhost:4576' if localstack is used for testing }, }", "JsonBase async def middleware_function( func: Callable, service: Any, message: Any,", "before function is called service.log(\"middleware before\") return_value = await func(*args,", "# For example 'http://localhost:4576' if localstack is used for testing", "For example 'http://localhost:4575' if localstack is used for testing \"sqs\":", "# specify AWS region (example: 'eu-west-1') \"aws_access_key_id\": None, # specify", "-> None: self.log('Publish data \"{}\"'.format(data)) await aws_sns_sqs_publish(self, data, topic=topic, wait=False)", "from tomodachi.discovery import AWSSNSRegistration from tomodachi.envelope import JsonBase async def", "[AWSSNSRegistration] # The message envelope class defines how a message", "middlewares can be chained. message_middleware = [middleware_function] # Some options", "possibility to pass in extra arguments or keywords arguments, for", "Some options can be specified to define credentials, used ports,", "# For example 'http://localhost:4575' if localstack is used for testing", "that is run on every incoming message. # Several middlewares", "\"region_name\": None, # specify AWS region (example: 'eu-west-1') \"aws_access_key_id\": None,", "after function is called service.log(\"middleware after\") return return_value class ExampleAWSSNSSQSService(tomodachi.Service):", "route1a) - \"{}\"'.format(data)) async def _started_service(self) -> None: async def", "using JSON and transferring some metadata message_envelope = JsonBase #", "is used for testing \"sqs\": None, # For example 'http://localhost:4576'", "# Adds a middleware function that is run on every", "tomodachi from tomodachi import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration", "Dict, *args: Any, **kwargs: Any ) -> Any: # Functionality", "*args: Any, **kwargs: Any ) -> Any: # Functionality before", "from tomodachi.envelope import JsonBase async def middleware_function( func: Callable, service:", "Functionality before function is called service.log(\"middleware before\") return_value = await", "log_level = \"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\") or \"\") # Build", "run on start and stop # See tomodachi/discovery/aws_sns_registration.py for example", "# See tomodachi/envelope/json_base.py for a basic example using JSON and", "function is called service.log(\"middleware after\") return return_value class ExampleAWSSNSSQSService(tomodachi.Service): name", "some metadata message_envelope = JsonBase # Adds a middleware function", "# Some options can be specified to define credentials, used", "log, etc. options = { \"aws_sns_sqs\": { \"region_name\": None, #", "used for testing }, } @aws_sns_sqs(\"example-route1\") async def route1a(self, data:", "'http://localhost:4576' if localstack is used for testing }, } @aws_sns_sqs(\"example-route1\")", "import tomodachi from tomodachi import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import", "func(*args, **kwargs) # There's also the possibility to pass in", "= [AWSSNSRegistration] # The message envelope class defines how a", "Build own \"discovery\" functions, to be run on start and", "import os from typing import Any, Callable, Dict import tomodachi", "from tomodachi import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration from", "tomodachi.discovery import AWSSNSRegistration from tomodachi.envelope import JsonBase async def middleware_function(", "middleware_function( func: Callable, service: Any, message: Any, topic: str, context:", "Callable, service: Any, message: Any, topic: str, context: Dict, *args:", "JSON and transferring some metadata message_envelope = JsonBase # Adds", "specify AWS secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": { \"sns\":", "\"sns\": None, # For example 'http://localhost:4575' if localstack is used", "and received # See tomodachi/envelope/json_base.py for a basic example using", "tomodachi/envelope/json_base.py for a basic example using JSON and transferring some", "access log, etc. options = { \"aws_sns_sqs\": { \"region_name\": None,", "aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration from tomodachi.envelope import JsonBase", "class defines how a message should be processed when sent", "called service.log(\"middleware after\") return return_value class ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\"", "message should be processed when sent and received # See", "can be chained. message_middleware = [middleware_function] # Some options can", "called service.log(\"middleware before\") return_value = await func(*args, **kwargs) # There's", "'eu-west-1') \"aws_access_key_id\": None, # specify AWS access key (example: '<KEY>')", "own \"discovery\" functions, to be run on start and stop", "testing \"sqs\": None, # For example 'http://localhost:4576' if localstack is", "for a basic example using JSON and transferring some metadata", "be specified to define credentials, used ports, hostnames, access log,", "\"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\") or \"\") # Build own \"discovery\"", "transferring some metadata message_envelope = JsonBase # Adds a middleware", "# Functionality before function is called service.log(\"middleware before\") return_value =", "Any, **kwargs: Any ) -> Any: # Functionality before function", "in extra arguments or keywords arguments, for example: # return_value", "received # See tomodachi/envelope/json_base.py for a basic example using JSON", "message: Any, topic: str, context: Dict, *args: Any, **kwargs: Any", "Any, message: Any, topic: str, context: Dict, *args: Any, **kwargs:", "= await func(*args, id='overridden', **kwargs) # Functinoality after function is", "For example 'http://localhost:4576' if localstack is used for testing },", "before\") return_value = await func(*args, **kwargs) # There's also the", "name = \"example-aws-sns-sqs-service\" log_level = \"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\") or", "be run on start and stop # See tomodachi/discovery/aws_sns_registration.py for", ") -> Any: # Functionality before function is called service.log(\"middleware", "\"{}\"'.format(data)) async def _started_service(self) -> None: async def publish(data: Any,", "on every incoming message. # Several middlewares can be chained.", "await func(*args, **kwargs) # There's also the possibility to pass", "specify AWS access key (example: '<KEY>') \"aws_secret_access_key\": None, # specify", "await func(*args, id='overridden', **kwargs) # Functinoality after function is called", "every incoming message. # Several middlewares can be chained. message_middleware", "async def route1a(self, data: Any) -> None: self.log('Received data (function:", "message. # Several middlewares can be chained. message_middleware = [middleware_function]", "key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": { \"sns\": None, # For", "how a message should be processed when sent and received", "'http://localhost:4575' if localstack is used for testing \"sqs\": None, #", "function that is run on every incoming message. # Several", "Callable, Dict import tomodachi from tomodachi import aws_sns_sqs, aws_sns_sqs_publish from", "for example discovery = [AWSSNSRegistration] # The message envelope class", "# Functinoality after function is called service.log(\"middleware after\") return return_value", "import AWSSNSRegistration from tomodachi.envelope import JsonBase async def middleware_function( func:", "return return_value class ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\" log_level = \"INFO\"", "ports, hostnames, access log, etc. options = { \"aws_sns_sqs\": {", "import JsonBase async def middleware_function( func: Callable, service: Any, message:", "also the possibility to pass in extra arguments or keywords", "-> None: self.log('Received data (function: route1a) - \"{}\"'.format(data)) async def", "async def publish(data: Any, topic: str) -> None: self.log('Publish data", "self.log('Received data (function: route1a) - \"{}\"'.format(data)) async def _started_service(self) ->", "ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\" log_level = \"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\")", "None, # specify AWS region (example: 'eu-west-1') \"aws_access_key_id\": None, #", "testing }, } @aws_sns_sqs(\"example-route1\") async def route1a(self, data: Any) ->", "import Any, Callable, Dict import tomodachi from tomodachi import aws_sns_sqs,", "to be run on start and stop # See tomodachi/discovery/aws_sns_registration.py", "arguments or keywords arguments, for example: # return_value = await", "topic: str) -> None: self.log('Publish data \"{}\"'.format(data)) await aws_sns_sqs_publish(self, data,", "envelope class defines how a message should be processed when", "@aws_sns_sqs(\"example-route1\") async def route1a(self, data: Any) -> None: self.log('Received data", "Adds a middleware function that is run on every incoming", "tomodachi import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration from tomodachi.envelope", "can be specified to define credentials, used ports, hostnames, access", "AWS region (example: 'eu-west-1') \"aws_access_key_id\": None, # specify AWS access", "Any, topic: str, context: Dict, *args: Any, **kwargs: Any )", "return_value = await func(*args, **kwargs) # There's also the possibility", "be chained. message_middleware = [middleware_function] # Some options can be", "(example: 'eu-west-1') \"aws_access_key_id\": None, # specify AWS access key (example:", "extra arguments or keywords arguments, for example: # return_value =", "credentials, used ports, hostnames, access log, etc. options = {", "{ \"aws_sns_sqs\": { \"region_name\": None, # specify AWS region (example:", "There's also the possibility to pass in extra arguments or", "AWSSNSRegistration from tomodachi.envelope import JsonBase async def middleware_function( func: Callable,", "from typing import Any, Callable, Dict import tomodachi from tomodachi", "example using JSON and transferring some metadata message_envelope = JsonBase", "Any ) -> Any: # Functionality before function is called", "async def _started_service(self) -> None: async def publish(data: Any, topic:", "key (example: '<KEY>') \"aws_secret_access_key\": None, # specify AWS secret key", "run on every incoming message. # Several middlewares can be", "# Several middlewares can be chained. message_middleware = [middleware_function] #", "localstack is used for testing \"sqs\": None, # For example", "None, # For example 'http://localhost:4576' if localstack is used for", "None: self.log('Publish data \"{}\"'.format(data)) await aws_sns_sqs_publish(self, data, topic=topic, wait=False) await", "**kwargs: Any ) -> Any: # Functionality before function is", "context: Dict, *args: Any, **kwargs: Any ) -> Any: #", "example: # return_value = await func(*args, id='overridden', **kwargs) # Functinoality", "Functinoality after function is called service.log(\"middleware after\") return return_value class", "str, context: Dict, *args: Any, **kwargs: Any ) -> Any:", "\"example-aws-sns-sqs-service\" log_level = \"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\") or \"\") #", "specified to define credentials, used ports, hostnames, access log, etc.", "**kwargs) # Functinoality after function is called service.log(\"middleware after\") return", "= await func(*args, **kwargs) # There's also the possibility to", "# The message envelope class defines how a message should", "= { \"aws_sns_sqs\": { \"region_name\": None, # specify AWS region", "# specify AWS secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": {", "class ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\" log_level = \"INFO\" uuid =", "= str(os.environ.get(\"SERVICE_UUID\") or \"\") # Build own \"discovery\" functions, to", "a middleware function that is run on every incoming message.", "str) -> None: self.log('Publish data \"{}\"'.format(data)) await aws_sns_sqs_publish(self, data, topic=topic,", "or \"\") # Build own \"discovery\" functions, to be run", "return_value = await func(*args, id='overridden', **kwargs) # Functinoality after function", "is called service.log(\"middleware after\") return return_value class ExampleAWSSNSSQSService(tomodachi.Service): name =", "and stop # See tomodachi/discovery/aws_sns_registration.py for example discovery = [AWSSNSRegistration]", "and transferring some metadata message_envelope = JsonBase # Adds a", "or keywords arguments, for example: # return_value = await func(*args,", "os from typing import Any, Callable, Dict import tomodachi from", "message_middleware = [middleware_function] # Some options can be specified to", "import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration from tomodachi.envelope import", "a message should be processed when sent and received #", "aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration from tomodachi.envelope import JsonBase async", "is used for testing }, } @aws_sns_sqs(\"example-route1\") async def route1a(self,", "data (function: route1a) - \"{}\"'.format(data)) async def _started_service(self) -> None:", "keywords arguments, for example: # return_value = await func(*args, id='overridden',", "func(*args, id='overridden', **kwargs) # Functinoality after function is called service.log(\"middleware", "service.log(\"middleware after\") return return_value class ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\" log_level", "a basic example using JSON and transferring some metadata message_envelope", "hostnames, access log, etc. options = { \"aws_sns_sqs\": { \"region_name\":", "\"aws_access_key_id\": None, # specify AWS access key (example: '<KEY>') \"aws_secret_access_key\":", "function is called service.log(\"middleware before\") return_value = await func(*args, **kwargs)", "None, # specify AWS secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\":", "func: Callable, service: Any, message: Any, topic: str, context: Dict,", "region (example: 'eu-west-1') \"aws_access_key_id\": None, # specify AWS access key", "AWS access key (example: '<KEY>') \"aws_secret_access_key\": None, # specify AWS", "- \"{}\"'.format(data)) async def _started_service(self) -> None: async def publish(data:", "arguments, for example: # return_value = await func(*args, id='overridden', **kwargs)", "example 'http://localhost:4575' if localstack is used for testing \"sqs\": None,", "uuid = str(os.environ.get(\"SERVICE_UUID\") or \"\") # Build own \"discovery\" functions,", "incoming message. # Several middlewares can be chained. message_middleware =", "options can be specified to define credentials, used ports, hostnames,", "defines how a message should be processed when sent and", "}, } @aws_sns_sqs(\"example-route1\") async def route1a(self, data: Any) -> None:", "tomodachi/discovery/aws_sns_registration.py for example discovery = [AWSSNSRegistration] # The message envelope", "message_envelope = JsonBase # Adds a middleware function that is", "_started_service(self) -> None: async def publish(data: Any, topic: str) ->", "processed when sent and received # See tomodachi/envelope/json_base.py for a", "functions, to be run on start and stop # See", "discovery = [AWSSNSRegistration] # The message envelope class defines how", "\"sqs\": None, # For example 'http://localhost:4576' if localstack is used", "to define credentials, used ports, hostnames, access log, etc. options", "= \"example-aws-sns-sqs-service\" log_level = \"INFO\" uuid = str(os.environ.get(\"SERVICE_UUID\") or \"\")", "None, # For example 'http://localhost:4575' if localstack is used for", "def middleware_function( func: Callable, service: Any, message: Any, topic: str,", "data: Any) -> None: self.log('Received data (function: route1a) - \"{}\"'.format(data))", "self.log('Publish data \"{}\"'.format(data)) await aws_sns_sqs_publish(self, data, topic=topic, wait=False) await publish(\"友達\",", "for example: # return_value = await func(*args, id='overridden', **kwargs) #", "return_value class ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\" log_level = \"INFO\" uuid", "on start and stop # See tomodachi/discovery/aws_sns_registration.py for example discovery", "'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": { \"sns\": None, # For example 'http://localhost:4575'", "access key (example: '<KEY>') \"aws_secret_access_key\": None, # specify AWS secret", "Any, topic: str) -> None: self.log('Publish data \"{}\"'.format(data)) await aws_sns_sqs_publish(self,", "str(os.environ.get(\"SERVICE_UUID\") or \"\") # Build own \"discovery\" functions, to be", "# See tomodachi/discovery/aws_sns_registration.py for example discovery = [AWSSNSRegistration] # The", "if localstack is used for testing \"sqs\": None, # For", "if localstack is used for testing }, } @aws_sns_sqs(\"example-route1\") async", "publish(data: Any, topic: str) -> None: self.log('Publish data \"{}\"'.format(data)) await", "The message envelope class defines how a message should be", "middleware function that is run on every incoming message. #", "# specify AWS access key (example: '<KEY>') \"aws_secret_access_key\": None, #", "} @aws_sns_sqs(\"example-route1\") async def route1a(self, data: Any) -> None: self.log('Received", "-> Any: # Functionality before function is called service.log(\"middleware before\")", "\"discovery\" functions, to be run on start and stop #", "See tomodachi/discovery/aws_sns_registration.py for example discovery = [AWSSNSRegistration] # The message", "service: Any, message: Any, topic: str, context: Dict, *args: Any,", "= JsonBase # Adds a middleware function that is run", "typing import Any, Callable, Dict import tomodachi from tomodachi import", "tomodachi.envelope import JsonBase async def middleware_function( func: Callable, service: Any,", "\"aws_endpoint_urls\": { \"sns\": None, # For example 'http://localhost:4575' if localstack", "\"aws_secret_access_key\": None, # specify AWS secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') },", "id='overridden', **kwargs) # Functinoality after function is called service.log(\"middleware after\")", "Any: # Functionality before function is called service.log(\"middleware before\") return_value", "pass in extra arguments or keywords arguments, for example: #", "None: self.log('Received data (function: route1a) - \"{}\"'.format(data)) async def _started_service(self)", "def publish(data: Any, topic: str) -> None: self.log('Publish data \"{}\"'.format(data))", "is called service.log(\"middleware before\") return_value = await func(*args, **kwargs) #", "should be processed when sent and received # See tomodachi/envelope/json_base.py", "metadata message_envelope = JsonBase # Adds a middleware function that", "when sent and received # See tomodachi/envelope/json_base.py for a basic", "used for testing \"sqs\": None, # For example 'http://localhost:4576' if", "(function: route1a) - \"{}\"'.format(data)) async def _started_service(self) -> None: async", "(example: '<KEY>') \"aws_secret_access_key\": None, # specify AWS secret key (example:", "\"aws_sns_sqs\": { \"region_name\": None, # specify AWS region (example: 'eu-west-1')", "options = { \"aws_sns_sqs\": { \"region_name\": None, # specify AWS", "'<KEY>') \"aws_secret_access_key\": None, # specify AWS secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA')", "# Build own \"discovery\" functions, to be run on start", "data \"{}\"'.format(data)) await aws_sns_sqs_publish(self, data, topic=topic, wait=False) await publish(\"友達\", \"example-route1\")", "basic example using JSON and transferring some metadata message_envelope =", "(example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": { \"sns\": None, # For example", "be processed when sent and received # See tomodachi/envelope/json_base.py for", "[middleware_function] # Some options can be specified to define credentials,", "None, # specify AWS access key (example: '<KEY>') \"aws_secret_access_key\": None,", "secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": { \"sns\": None, #", "etc. options = { \"aws_sns_sqs\": { \"region_name\": None, # specify", "route1a(self, data: Any) -> None: self.log('Received data (function: route1a) -", "Any) -> None: self.log('Received data (function: route1a) - \"{}\"'.format(data)) async", "Dict import tomodachi from tomodachi import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery", "None: async def publish(data: Any, topic: str) -> None: self.log('Publish", "= [middleware_function] # Some options can be specified to define", "JsonBase # Adds a middleware function that is run on", "stop # See tomodachi/discovery/aws_sns_registration.py for example discovery = [AWSSNSRegistration] #", "def _started_service(self) -> None: async def publish(data: Any, topic: str)", "start and stop # See tomodachi/discovery/aws_sns_registration.py for example discovery =", "topic: str, context: Dict, *args: Any, **kwargs: Any ) ->", "after\") return return_value class ExampleAWSSNSSQSService(tomodachi.Service): name = \"example-aws-sns-sqs-service\" log_level =", "}, \"aws_endpoint_urls\": { \"sns\": None, # For example 'http://localhost:4575' if", "{ \"region_name\": None, # specify AWS region (example: 'eu-west-1') \"aws_access_key_id\":", "used ports, hostnames, access log, etc. options = { \"aws_sns_sqs\":", "AWS secret key (example: 'f7sha92hNotarealsecretkeyn29ShnSYQi3nzgA') }, \"aws_endpoint_urls\": { \"sns\": None," ]
[ "= False joke_evaluation = \"Isn't that joke so funny?! {}\"", "do_not = \"don't\" y = f\"Those who know {binary} and", "so funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This is the left side of...\"", "y = f\"Those who know {binary} and those who {do_not}.\"", "also said: '{y}'\") hilarious = False joke_evaluation = \"Isn't that", "those who {do_not}.\" print(x) print(y) print(f\"I said: {x}\") print(f\"I also", "= f\"Those who know {binary} and those who {do_not}.\" print(x)", "binary = \"binary\" do_not = \"don't\" y = f\"Those who", "x = f\"There are {types_of_people} types of people.\" binary =", "types_of_people = 10 x = f\"There are {types_of_people} types of", "of...\" e=\"a string with a right side.\" print(w + e)", "= f\"There are {types_of_people} types of people.\" binary = \"binary\"", "print(f\"I said: {x}\") print(f\"I also said: '{y}'\") hilarious = False", "\"binary\" do_not = \"don't\" y = f\"Those who know {binary}", "said: '{y}'\") hilarious = False joke_evaluation = \"Isn't that joke", "False joke_evaluation = \"Isn't that joke so funny?! {}\" print(joke_evaluation.format(hilarious))", "10 x = f\"There are {types_of_people} types of people.\" binary", "said: {x}\") print(f\"I also said: '{y}'\") hilarious = False joke_evaluation", "{x}\") print(f\"I also said: '{y}'\") hilarious = False joke_evaluation =", "know {binary} and those who {do_not}.\" print(x) print(y) print(f\"I said:", "types of people.\" binary = \"binary\" do_not = \"don't\" y", "'{y}'\") hilarious = False joke_evaluation = \"Isn't that joke so", "= \"don't\" y = f\"Those who know {binary} and those", "who {do_not}.\" print(x) print(y) print(f\"I said: {x}\") print(f\"I also said:", "= \"Isn't that joke so funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This is", "is the left side of...\" e=\"a string with a right", "people.\" binary = \"binary\" do_not = \"don't\" y = f\"Those", "funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This is the left side of...\" e=\"a", "w=\"This is the left side of...\" e=\"a string with a", "<reponame>ThitsarAung/python-exercises types_of_people = 10 x = f\"There are {types_of_people} types", "left side of...\" e=\"a string with a right side.\" print(w", "{do_not}.\" print(x) print(y) print(f\"I said: {x}\") print(f\"I also said: '{y}'\")", "of people.\" binary = \"binary\" do_not = \"don't\" y =", "print(y) print(f\"I said: {x}\") print(f\"I also said: '{y}'\") hilarious =", "are {types_of_people} types of people.\" binary = \"binary\" do_not =", "f\"Those who know {binary} and those who {do_not}.\" print(x) print(y)", "who know {binary} and those who {do_not}.\" print(x) print(y) print(f\"I", "print(x) print(y) print(f\"I said: {x}\") print(f\"I also said: '{y}'\") hilarious", "print(joke_evaluation.format(hilarious)) w=\"This is the left side of...\" e=\"a string with", "side of...\" e=\"a string with a right side.\" print(w +", "f\"There are {types_of_people} types of people.\" binary = \"binary\" do_not", "{binary} and those who {do_not}.\" print(x) print(y) print(f\"I said: {x}\")", "= \"binary\" do_not = \"don't\" y = f\"Those who know", "joke so funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This is the left side", "the left side of...\" e=\"a string with a right side.\"", "print(f\"I also said: '{y}'\") hilarious = False joke_evaluation = \"Isn't", "= 10 x = f\"There are {types_of_people} types of people.\"", "and those who {do_not}.\" print(x) print(y) print(f\"I said: {x}\") print(f\"I", "that joke so funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This is the left", "{}\" print(joke_evaluation.format(hilarious)) w=\"This is the left side of...\" e=\"a string", "joke_evaluation = \"Isn't that joke so funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This", "\"Isn't that joke so funny?! {}\" print(joke_evaluation.format(hilarious)) w=\"This is the", "\"don't\" y = f\"Those who know {binary} and those who", "{types_of_people} types of people.\" binary = \"binary\" do_not = \"don't\"", "hilarious = False joke_evaluation = \"Isn't that joke so funny?!" ]
[ "return '%s=%s' % (key, value) args = [] for input", "return self.statement('from dlconv.%s import %s\\n' % (self.target, self.net)) def emit_class_def(self,", "<title>Keras</title> </head> <body> <img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded)", "'wb') as f: np.save(f, self.data) return code_output_path, data_output_path def emit(self):", "self.prefix + s + '\\n' def emit_imports(self): return self.statement('from dlconv.%s", "os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir, file_name +", "class_name = get_upper_case(file_name) net = getattr(module, class_name) return net.dump(self.data_output_path, model_output_dir)", "node.name + \"'\")) # Set the node name args =", "open(data_output_path, 'wb') as f: np.save(f, self.data) return code_output_path, data_output_path def", "new chain for this node. attach_to_chain = [] chains.append(attach_to_chain) attach_to_chain.append(node)", "html_path): with open(png_path, \"rb\") as f: encoded = base64.b64encode(f.read()).decode('utf-8') source", "= code_output_path self.data_output_path = data_output_path def dump(self, model_output_dir): '''Return the", "code_output_path self.data_output_path = data_output_path def dump(self, model_output_dir): '''Return the file", "__init__(self, toolkit, meta_path): self.toolkit = toolkit.lower() self.meta_path = meta_path def", "input in node.input: input = input.strip().split(':') name = ''.join(input[:-1]) idx", "# Node is part of an existing chain. attach_to_chain =", "fetch_attr_value from mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case, get_real_name class JsonFormatter(object): '''Dumpt", "value) args = [] for input in node.input: input =", "for node in self.graph.topologically_sorted(): attach_to_chain = None if len(node.input) ==", "dump(self, json_path): json_txt = json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt) formatted =", "Python code line by line source = self.emit_imports() source +=", "os.path.join(code_output_dir, file_name + '.npy') with open(code_output_path, 'w') as f: f.write(self.emit())", "get_upper_case(file_name) net = getattr(module, class_name) return net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object):", "not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir, file_name", "in chains: if chain[-1].name == parent: # Node is part", "node.output for k, v in node.attr: if k == 'cell_type':", "+= self.tab def outdent(self): self.prefix = self.prefix[:-len(self.tab)] def statement(self, s):", "attach_to_chain = chain break if attach_to_chain is None: # Start", "'.join(output), node.op, args)) def dump(self, code_output_dir): if not os.path.exists(code_output_dir): os.makedirs(code_output_dir)", "node in self.graph.topologically_sorted(): attach_to_chain = None if len(node.input) == 1:", "target = target.lower() if target == 'tensorflow': self.target = target", "os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name) class_name =", "code_output_path = os.path.join(code_output_dir, file_name + '.py') data_output_path = os.path.join(code_output_dir, file_name", "statement(self, s): return self.prefix + s + '\\n' def emit_imports(self):", "self.tab def outdent(self): self.prefix = self.prefix[:-len(self.tab)] def statement(self, s): return", "for input in node.input: input = input.strip().split(':') name = ''.join(input[:-1])", "meta_path): self.toolkit = toolkit.lower() self.meta_path = meta_path def dump(self, graph_path):", "json import numpy as np import os import sys from", "fetch_attr_value(v))) args.append(pair('name', \"'\" + node.name + \"'\")) # Set the", "yet.' % target) def indent(self): self.prefix += self.tab def outdent(self):", "for this node. attach_to_chain = [] chains.append(attach_to_chain) attach_to_chain.append(node) # Generate", "self.net = 'KerasNetwork' elif target == 'caffe': self.target = target", "Set the node name args = ', '.join(args) return self.statement('%s", "if html_path: self._png_to_html(png_path, html_path) os.remove(png_path) else: raise NotImplementedError('Visualization of %s", "\"'\" + fetch_attr_value(v) + \"'\")) else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\"", "= int(input[-1]) assert name in self.graph.node_dict parent = self.graph.get_node(name) args.append(parent.output[idx])", "get_real_name(node.input[0]) for chain in chains: if chain[-1].name == parent: #", "import os import sys from mmdnn.conversion.caffe.errors import ConversionError from mmdnn.conversion.caffe.common_graph", "if not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir,", "target == 'keras': self.target = target self.net = 'KerasNetwork' elif", "args.append(pair(k, \"'\" + fetch_attr_value(v) + \"'\")) else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name',", "k, v in node.attr: if k == 'cell_type': args.append(pair(k, \"'\"", "format or %s is unsupported!' % graph_path) elif self.toolkit ==", "Python source for this node.''' def pair(key, value): return '%s=%s'", "self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image format or %s is unsupported!'", "mmdnn.conversion.caffe.errors import ConversionError from mmdnn.conversion.caffe.common_graph import fetch_attr_value from mmdnn.conversion.caffe.utils import", "png_path, html_path = (None, None) if graph_path.endswith('.png'): png_path = graph_path", "args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\" + node.name + \"'\")) # Set", "attach_to_chain is None: # Start a new chain for this", "'.join(args) return self.statement('%s = self.%s(%s)' % (', '.join(output), node.op, args))", "+ '\\n' def emit_imports(self): return self.statement('from dlconv.%s import %s\\n' %", "return source class ModelSaver(object): def __init__(self, code_output_path, data_output_path): self.code_output_path =", "', '.join(args) return self.statement('%s = self.%s(%s)' % (', '.join(output), node.op,", "data_output_path def dump(self, model_output_dir): '''Return the file path containing graph", "args.append(pair('name', \"'\" + node.name + \"'\")) # Set the node", "= os.path.join(code_output_dir, file_name + '.py') data_output_path = os.path.join(code_output_dir, file_name +", "Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded) with open(html_path, 'w', encoding='utf-8') as", "__init__(self, graph): self.graph_def = graph.as_graph_def() def dump(self, json_path): json_txt =", "elif self.toolkit == 'keras': from dlconv.keras.visualizer import KerasVisualizer png_path, html_path", "'CaffeNetwork' else: raise ConversionError('Target %s is not supported yet.' %", "'htm') def _png_to_html(self, png_path, html_path): with open(png_path, \"rb\") as f:", "raise NotImplementedError('Image format or %s is unsupported!' % graph_path) elif", "dlconv.tensorflow.visualizer import TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image format", "# Set the node name args = ', '.join(args) return", "name args = ', '.join(args) return self.statement('%s = self.%s(%s)' %", "'keras': from dlconv.keras.visualizer import KerasVisualizer png_path, html_path = (None, None)", "return self.statement('%s = self.%s(%s)' % (', '.join(output), node.op, args)) def", "attach_to_chain = None if len(node.input) == 1: parent = get_real_name(node.input[0])", "from mmdnn.conversion.caffe.errors import ConversionError from mmdnn.conversion.caffe.common_graph import fetch_attr_value from mmdnn.conversion.caffe.utils", "= 'CaffeNetwork' else: raise ConversionError('Target %s is not supported yet.'", "target): self.graph = graph self.data = data self.tab = '", "is unsupported!' % self.toolkit) def _is_web_page(self, path): return path.split('.')[-1] in", "self.prefix = self.prefix[:-len(self.tab)] def statement(self, s): return self.prefix + s", "name): return self.statement('class %s(%s):' % (name, self.net)) def emit_setup_def(self): return", "= json.loads(json_txt) formatted = json.dumps(parsed, indent=4, sort_keys=True) with open(json_path, 'w')", "(', '.join(output), node.op, args)) def dump(self, code_output_dir): if not os.path.exists(code_output_dir):", "the Python source for this node.''' def pair(key, value): return", "for chain in chains: b = '' for node in", "= graph self.data = data self.tab = ' ' *", "[] for chain in chains: b = '' for node", "chains.append(attach_to_chain) attach_to_chain.append(node) # Generate Python code line by line source", "self.emit_setup_def() self.indent() blocks = [] for chain in chains: b", "import %s\\n' % (self.target, self.net)) def emit_class_def(self, name): return self.statement('class", "dump(self, code_output_dir): if not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name) code_output_path", "'.npy') with open(code_output_path, 'w') as f: f.write(self.emit()) with open(data_output_path, 'wb')", "sys from mmdnn.conversion.caffe.errors import ConversionError from mmdnn.conversion.caffe.common_graph import fetch_attr_value from", "line source = self.emit_imports() source += self.emit_class_def(self.graph.name) self.indent() source +=", "''.join(input[:-1]) idx = int(input[-1]) assert name in self.graph.node_dict parent =", "f: f.write(formatted) class PyWriter(object): '''Dumpt a DL graph into a", "if graph_path.endswith('.png'): png_path = graph_path elif self._is_web_page(graph_path): png_path = graph_path", "from mmdnn.conversion.caffe.common_graph import fetch_attr_value from mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case, get_real_name", "generated model files.''' if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name =", "file_name = get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir, file_name + '.py') data_output_path", "self.tab = ' ' * 4 self.prefix = '' target", "Python script.''' def __init__(self, graph, data, target): self.graph = graph", "mmdnn.conversion.caffe.common_graph import fetch_attr_value from mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case, get_real_name class", "self.net = 'CaffeNetwork' else: raise ConversionError('Target %s is not supported", "in node.input: input = input.strip().split(':') name = ''.join(input[:-1]) idx =", "4 self.prefix = '' target = target.lower() if target ==", "f: np.save(f, self.data) return code_output_path, data_output_path def emit(self): # Decompose", "node.op, args)) def dump(self, code_output_dir): if not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name", "not supported yet.' % target) def indent(self): self.prefix += self.tab", "get_lower_case, get_upper_case, get_real_name class JsonFormatter(object): '''Dumpt a DL graph into", "if k == 'cell_type': args.append(pair(k, \"'\" + fetch_attr_value(v) + \"'\"))", "self.emit_imports() source += self.emit_class_def(self.graph.name) self.indent() source += self.emit_setup_def() self.indent() blocks", "def dump(self, code_output_dir): if not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name)", "'KerasNetwork' elif target == 'caffe': self.target = target self.net =", "= graph_path elif self._is_web_page(graph_path): png_path = graph_path + \".png\" html_path", "base64 from google.protobuf import json_format from importlib import import_module import", "\"'\")) # Set the node name args = ', '.join(args)", "self.prefix += self.tab def outdent(self): self.prefix = self.prefix[:-len(self.tab)] def statement(self,", "from dlconv.keras.visualizer import KerasVisualizer png_path, html_path = (None, None) if", "node.''' def pair(key, value): return '%s=%s' % (key, value) args", "def dump(self, graph_path): if self.toolkit == 'tensorflow': from dlconv.tensorflow.visualizer import", "a DL graph into a Python script.''' def __init__(self, graph,", "chains: if chain[-1].name == parent: # Node is part of", "' ' * 4 self.prefix = '' target = target.lower()", "<reponame>2yz/MMdnn import base64 from google.protobuf import json_format from importlib import", "part of an existing chain. attach_to_chain = chain break if", "TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image format or %s", "for chain in chains: if chain[-1].name == parent: # Node", "% graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path, html_path) os.remove(png_path) else: raise", "script.''' def __init__(self, graph, data, target): self.graph = graph self.data", "json_path): json_txt = json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt) formatted = json.dumps(parsed,", "graph_path): if self.toolkit == 'tensorflow': from dlconv.tensorflow.visualizer import TensorFlowVisualizer if", "= json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt) formatted = json.dumps(parsed, indent=4, sort_keys=True)", "chain for this node. attach_to_chain = [] chains.append(attach_to_chain) attach_to_chain.append(node) #", "GraphDrawer(object): def __init__(self, toolkit, meta_path): self.toolkit = toolkit.lower() self.meta_path =", "+= '\\n\\n'.join(blocks) return source class ModelSaver(object): def __init__(self, code_output_path, data_output_path):", "f: encoded = base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE> <html> <head> <meta", "target self.net = 'KerasNetwork' elif target == 'caffe': self.target =", "self._is_web_page(graph_path): png_path = graph_path + \".png\" html_path = graph_path else:", "in self.graph.node_dict parent = self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output = [node.output[0]]", "= 'TensorFlowNetwork' elif target == 'keras': self.target = target self.net", "else: raise NotImplementedError('Image format or %s is unsupported!' % graph_path)", "\"rb\") as f: encoded = base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE> <html>", "'tensorflow': self.target = target self.net = 'TensorFlowNetwork' elif target ==", "elif target == 'keras': self.target = target self.net = 'KerasNetwork'", "np.save(f, self.data) return code_output_path, data_output_path def emit(self): # Decompose DAG", "#FIXME: output = [node.output[0]] # output = node.output for k,", "[node.output[0]] # output = node.output for k, v in node.attr:", "def indent(self): self.prefix += self.tab def outdent(self): self.prefix = self.prefix[:-len(self.tab)]", "'%s=%s' % (key, value) args = [] for input in", "get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir, file_name + '.py') data_output_path = os.path.join(code_output_dir,", "== 'keras': from dlconv.keras.visualizer import KerasVisualizer png_path, html_path = (None,", "raise NotImplementedError('Visualization of %s is unsupported!' % self.toolkit) def _is_web_page(self,", "s): return self.prefix + s + '\\n' def emit_imports(self): return", "ConversionError('Target %s is not supported yet.' % target) def indent(self):", "def outdent(self): self.prefix = self.prefix[:-len(self.tab)] def statement(self, s): return self.prefix", "ModelSaver(object): def __init__(self, code_output_path, data_output_path): self.code_output_path = code_output_path self.data_output_path =", "import_module import json import numpy as np import os import", "= import_module(file_name) class_name = get_upper_case(file_name) net = getattr(module, class_name) return", "b = '' for node in chain: b += self.emit_node(node)", "html_path = graph_path else: raise NotImplementedError('Image format or %s is", "graph.as_graph_def() def dump(self, json_path): json_txt = json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt)", "self.indent() blocks = [] for chain in chains: b =", "self._png_to_html(png_path, html_path) os.remove(png_path) else: raise NotImplementedError('Visualization of %s is unsupported!'", "file.''' def __init__(self, graph): self.graph_def = graph.as_graph_def() def dump(self, json_path):", "= self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output = [node.output[0]] # output =", "name in self.graph.node_dict parent = self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output =", "chain[-1].name == parent: # Node is part of an existing", "return self.prefix + s + '\\n' def emit_imports(self): return self.statement('from", "class GraphDrawer(object): def __init__(self, toolkit, meta_path): self.toolkit = toolkit.lower() self.meta_path", "html_path: self._png_to_html(png_path, html_path) os.remove(png_path) else: raise NotImplementedError('Visualization of %s is", "unsupported!' % graph_path) elif self.toolkit == 'keras': from dlconv.keras.visualizer import", "parent = get_real_name(node.input[0]) for chain in chains: if chain[-1].name ==", "self.%s(%s)' % (', '.join(output), node.op, args)) def dump(self, code_output_dir): if", "\"'\" + node.name + \"'\")) # Set the node name", "parent = self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output = [node.output[0]] # output", "(self.target, self.net)) def emit_class_def(self, name): return self.statement('class %s(%s):' % (name,", "NotImplementedError('Image format or %s is unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if", "data_output_path def emit(self): # Decompose DAG into chains chains =", "code_output_path, data_output_path def emit(self): # Decompose DAG into chains chains", "= 'KerasNetwork' elif target == 'caffe': self.target = target self.net", "self.toolkit == 'keras': from dlconv.keras.visualizer import KerasVisualizer png_path, html_path =", "import import_module import json import numpy as np import os", "in self.graph.topologically_sorted(): attach_to_chain = None if len(node.input) == 1: parent", "graph into a Json file.''' def __init__(self, graph): self.graph_def =", "input.strip().split(':') name = ''.join(input[:-1]) idx = int(input[-1]) assert name in", "json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt) formatted = json.dumps(parsed, indent=4, sort_keys=True) with", "= base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE> <html> <head> <meta charset=\"utf-8\"> <title>Keras</title>", "self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output = [node.output[0]] # output = node.output", "= getattr(module, class_name) return net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object): def __init__(self,", "= graph.as_graph_def() def dump(self, json_path): json_txt = json_format.MessageToJson(self.graph_def) parsed =", "os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir, file_name + '.py')", "def _is_web_page(self, path): return path.split('.')[-1] in ('html', 'htm') def _png_to_html(self,", "% target) def indent(self): self.prefix += self.tab def outdent(self): self.prefix", "self.data_output_path = data_output_path def dump(self, model_output_dir): '''Return the file path", "node.attr: if k == 'cell_type': args.append(pair(k, \"'\" + fetch_attr_value(v) +", "graph self.data = data self.tab = ' ' * 4", "self.graph = graph self.data = data self.tab = ' '", "target.lower() if target == 'tensorflow': self.target = target self.net =", "dump(self, model_output_dir): '''Return the file path containing graph in generated", "len(node.input) == 1: parent = get_real_name(node.input[0]) for chain in chains:", "as f: f.write(self.emit()) with open(data_output_path, 'wb') as f: np.save(f, self.data)", "NotImplementedError('Image format or %s is unsupported!' % graph_path) elif self.toolkit", "module = import_module(file_name) class_name = get_upper_case(file_name) net = getattr(module, class_name)", "TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image format or %s is unsupported!' %", "= \"\"\"<!DOCTYPE> <html> <head> <meta charset=\"utf-8\"> <title>Keras</title> </head> <body> <img", "b += self.emit_node(node) blocks.append(b[:-1]) source += '\\n\\n'.join(blocks) return source class", "self.emit_class_def(self.graph.name) self.indent() source += self.emit_setup_def() self.indent() blocks = [] for", "KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path, html_path) os.remove(png_path) else: raise NotImplementedError('Visualization of", "the node name args = ', '.join(args) return self.statement('%s =", "Decompose DAG into chains chains = [] for node in", "google.protobuf import json_format from importlib import import_module import json import", "= meta_path def dump(self, graph_path): if self.toolkit == 'tensorflow': from", "emit(self): # Decompose DAG into chains chains = [] for", "emit_class_def(self, name): return self.statement('class %s(%s):' % (name, self.net)) def emit_setup_def(self):", "def emit_class_def(self, name): return self.statement('class %s(%s):' % (name, self.net)) def", "= input.strip().split(':') name = ''.join(input[:-1]) idx = int(input[-1]) assert name", "chain: b += self.emit_node(node) blocks.append(b[:-1]) source += '\\n\\n'.join(blocks) return source", "target == 'caffe': self.target = target self.net = 'CaffeNetwork' else:", "graph into a Python script.''' def __init__(self, graph, data, target):", "+ \"'\")) # Set the node name args = ',", "self.net)) def emit_class_def(self, name): return self.statement('class %s(%s):' % (name, self.net))", "% graph_path) elif self.toolkit == 'keras': from dlconv.keras.visualizer import KerasVisualizer", "[] for node in self.graph.topologically_sorted(): attach_to_chain = None if len(node.input)", "in chains: b = '' for node in chain: b", "for k, v in node.attr: if k == 'cell_type': args.append(pair(k,", "chains: b = '' for node in chain: b +=", "None) if graph_path.endswith('.png'): png_path = graph_path elif self._is_web_page(graph_path): png_path =", "in generated model files.''' if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name", "args)) def dump(self, code_output_dir): if not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name =", "import fetch_attr_value from mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case, get_real_name class JsonFormatter(object):", "if attach_to_chain is None: # Start a new chain for", "with open(code_output_path, 'w') as f: f.write(self.emit()) with open(data_output_path, 'wb') as", "in ('html', 'htm') def _png_to_html(self, png_path, html_path): with open(png_path, \"rb\")", "PyWriter(object): '''Dumpt a DL graph into a Python script.''' def", "self.target = target self.net = 'CaffeNetwork' else: raise ConversionError('Target %s", "net = getattr(module, class_name) return net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object): def", "assert name in self.graph.node_dict parent = self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output", "% (', '.join(output), node.op, args)) def dump(self, code_output_dir): if not", "'' for node in chain: b += self.emit_node(node) blocks.append(b[:-1]) source", "is unsupported!' % graph_path) elif self.toolkit == 'keras': from dlconv.keras.visualizer", "return self.statement('class %s(%s):' % (name, self.net)) def emit_setup_def(self): return self.statement('def", "is part of an existing chain. attach_to_chain = chain break", "os.remove(png_path) else: raise NotImplementedError('Visualization of %s is unsupported!' % self.toolkit)", "self.prefix[:-len(self.tab)] def statement(self, s): return self.prefix + s + '\\n'", "graph_path + \".png\" html_path = graph_path else: raise NotImplementedError('Image format", "target self.net = 'TensorFlowNetwork' elif target == 'keras': self.target =", "file_name + '.py') data_output_path = os.path.join(code_output_dir, file_name + '.npy') with", "<body> <img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded) with open(html_path,", "'''Dumpt a DL graph into a Json file.''' def __init__(self,", "meta_path def dump(self, graph_path): if self.toolkit == 'tensorflow': from dlconv.tensorflow.visualizer", "def __init__(self, graph): self.graph_def = graph.as_graph_def() def dump(self, json_path): json_txt", "self.prefix = '' target = target.lower() if target == 'tensorflow':", "= ', '.join(args) return self.statement('%s = self.%s(%s)' % (', '.join(output),", "chains chains = [] for node in self.graph.topologically_sorted(): attach_to_chain =", "this node. attach_to_chain = [] chains.append(attach_to_chain) attach_to_chain.append(node) # Generate Python", "importlib import import_module import json import numpy as np import", "+ \"'\")) else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\" + node.name +", "open(json_path, 'w') as f: f.write(formatted) class PyWriter(object): '''Dumpt a DL", "('html', 'htm') def _png_to_html(self, png_path, html_path): with open(png_path, \"rb\") as", "model_output_dir): '''Return the file path containing graph in generated model", "containing graph in generated model files.''' if not os.path.exists(model_output_dir): os.makedirs(model_output_dir)", "= ' ' * 4 self.prefix = '' target =", "def __init__(self, code_output_path, data_output_path): self.code_output_path = code_output_path self.data_output_path = data_output_path", "fetch_attr_value(v) + \"'\")) else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\" + node.name", "= toolkit.lower() self.meta_path = meta_path def dump(self, graph_path): if self.toolkit", "/> </body> </html>\"\"\".format(base64_str=encoded) with open(html_path, 'w', encoding='utf-8') as f: f.write(source)", "+ '.py') data_output_path = os.path.join(code_output_dir, file_name + '.npy') with open(code_output_path,", "'''Emits the Python source for this node.''' def pair(key, value):", "an existing chain. attach_to_chain = chain break if attach_to_chain is", "def __init__(self, toolkit, meta_path): self.toolkit = toolkit.lower() self.meta_path = meta_path", "<meta charset=\"utf-8\"> <title>Keras</title> </head> <body> <img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" />", "%s is unsupported!' % graph_path) elif self.toolkit == 'keras': from", "'w') as f: f.write(formatted) class PyWriter(object): '''Dumpt a DL graph", "args = [] for input in node.input: input = input.strip().split(':')", "model_output_dir) class GraphDrawer(object): def __init__(self, toolkit, meta_path): self.toolkit = toolkit.lower()", "# Generate Python code line by line source = self.emit_imports()", "chains = [] for node in self.graph.topologically_sorted(): attach_to_chain = None", "formatted = json.dumps(parsed, indent=4, sort_keys=True) with open(json_path, 'w') as f:", "if chain[-1].name == parent: # Node is part of an", "% self.toolkit) def _is_web_page(self, path): return path.split('.')[-1] in ('html', 'htm')", "target self.net = 'CaffeNetwork' else: raise ConversionError('Target %s is not", "= get_upper_case(file_name) net = getattr(module, class_name) return net.dump(self.data_output_path, model_output_dir) class", "self.graph.topologically_sorted(): attach_to_chain = None if len(node.input) == 1: parent =", "graph): self.graph_def = graph.as_graph_def() def dump(self, json_path): json_txt = json_format.MessageToJson(self.graph_def)", "'''Dumpt a DL graph into a Python script.''' def __init__(self,", "source += self.emit_class_def(self.graph.name) self.indent() source += self.emit_setup_def() self.indent() blocks =", "with open(png_path, \"rb\") as f: encoded = base64.b64encode(f.read()).decode('utf-8') source =", "self.statement('%s = self.%s(%s)' % (', '.join(output), node.op, args)) def dump(self,", "def pair(key, value): return '%s=%s' % (key, value) args =", "Generate Python code line by line source = self.emit_imports() source", "== 'tensorflow': from dlconv.tensorflow.visualizer import TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else:", "pair(key, value): return '%s=%s' % (key, value) args = []", "f.write(self.emit()) with open(data_output_path, 'wb') as f: np.save(f, self.data) return code_output_path,", "= [] for node in self.graph.topologically_sorted(): attach_to_chain = None if", "setup(self):') def emit_node(self, node): '''Emits the Python source for this", "data self.tab = ' ' * 4 self.prefix = ''", "this node.''' def pair(key, value): return '%s=%s' % (key, value)", "from importlib import import_module import json import numpy as np", "else: raise ConversionError('Target %s is not supported yet.' % target)", "if target == 'tensorflow': self.target = target self.net = 'TensorFlowNetwork'", "graph, data, target): self.graph = graph self.data = data self.tab", "get_real_name class JsonFormatter(object): '''Dumpt a DL graph into a Json", "path): return path.split('.')[-1] in ('html', 'htm') def _png_to_html(self, png_path, html_path):", "ConversionError from mmdnn.conversion.caffe.common_graph import fetch_attr_value from mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case,", "self.graph_def = graph.as_graph_def() def dump(self, json_path): json_txt = json_format.MessageToJson(self.graph_def) parsed", "self.statement('def setup(self):') def emit_node(self, node): '''Emits the Python source for", "idx = int(input[-1]) assert name in self.graph.node_dict parent = self.graph.get_node(name)", "node in chain: b += self.emit_node(node) blocks.append(b[:-1]) source += '\\n\\n'.join(blocks)", "os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name) class_name", "return path.split('.')[-1] in ('html', 'htm') def _png_to_html(self, png_path, html_path): with", "def dump(self, model_output_dir): '''Return the file path containing graph in", "'w') as f: f.write(self.emit()) with open(data_output_path, 'wb') as f: np.save(f,", "toolkit, meta_path): self.toolkit = toolkit.lower() self.meta_path = meta_path def dump(self,", "graph_path.endswith('.png'): png_path = graph_path elif self._is_web_page(graph_path): png_path = graph_path +", "emit_setup_def(self): return self.statement('def setup(self):') def emit_node(self, node): '''Emits the Python", "% (self.target, self.net)) def emit_class_def(self, name): return self.statement('class %s(%s):' %", "in node.attr: if k == 'cell_type': args.append(pair(k, \"'\" + fetch_attr_value(v)", "graph in generated model files.''' if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path))", "%s is unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path, html_path)", "self.toolkit = toolkit.lower() self.meta_path = meta_path def dump(self, graph_path): if", "for node in chain: b += self.emit_node(node) blocks.append(b[:-1]) source +=", "self.target = target self.net = 'KerasNetwork' elif target == 'caffe':", "numpy as np import os import sys from mmdnn.conversion.caffe.errors import", "dump(self, graph_path): if self.toolkit == 'tensorflow': from dlconv.tensorflow.visualizer import TensorFlowVisualizer", "self.indent() source += self.emit_setup_def() self.indent() blocks = [] for chain", "DL graph into a Json file.''' def __init__(self, graph): self.graph_def", "class PyWriter(object): '''Dumpt a DL graph into a Python script.'''", "# Decompose DAG into chains chains = [] for node", "Json file.''' def __init__(self, graph): self.graph_def = graph.as_graph_def() def dump(self,", "indent=4, sort_keys=True) with open(json_path, 'w') as f: f.write(formatted) class PyWriter(object):", "= (None, None) if graph_path.endswith('.png'): png_path = graph_path elif self._is_web_page(graph_path):", "import ConversionError from mmdnn.conversion.caffe.common_graph import fetch_attr_value from mmdnn.conversion.caffe.utils import get_lower_case,", "+ node.name + \"'\")) # Set the node name args", "'''Return the file path containing graph in generated model files.'''", "= target self.net = 'KerasNetwork' elif target == 'caffe': self.target", "node name args = ', '.join(args) return self.statement('%s = self.%s(%s)'", "output = [node.output[0]] # output = node.output for k, v", "KerasVisualizer png_path, html_path = (None, None) if graph_path.endswith('.png'): png_path =", "into a Json file.''' def __init__(self, graph): self.graph_def = graph.as_graph_def()", "attach_to_chain.append(node) # Generate Python code line by line source =", "code line by line source = self.emit_imports() source += self.emit_class_def(self.graph.name)", "* 4 self.prefix = '' target = target.lower() if target", "+ '.npy') with open(code_output_path, 'w') as f: f.write(self.emit()) with open(data_output_path,", "= json.dumps(parsed, indent=4, sort_keys=True) with open(json_path, 'w') as f: f.write(formatted)", "a Json file.''' def __init__(self, graph): self.graph_def = graph.as_graph_def() def", "== 'tensorflow': self.target = target self.net = 'TensorFlowNetwork' elif target", "if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image format or %s is", "'' target = target.lower() if target == 'tensorflow': self.target =", "break if attach_to_chain is None: # Start a new chain", "elif self._is_web_page(graph_path): png_path = graph_path + \".png\" html_path = graph_path", "def statement(self, s): return self.prefix + s + '\\n' def", "<img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded) with open(html_path, 'w',", "from google.protobuf import json_format from importlib import import_module import json", "import sys from mmdnn.conversion.caffe.errors import ConversionError from mmdnn.conversion.caffe.common_graph import fetch_attr_value", "file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name) class_name = get_upper_case(file_name) net", "input = input.strip().split(':') name = ''.join(input[:-1]) idx = int(input[-1]) assert", "src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded) with open(html_path, 'w', encoding='utf-8') as f:", "import TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image format or", "with open(data_output_path, 'wb') as f: np.save(f, self.data) return code_output_path, data_output_path", "\"\"\"<!DOCTYPE> <html> <head> <meta charset=\"utf-8\"> <title>Keras</title> </head> <body> <img alt=\"Model", "indent(self): self.prefix += self.tab def outdent(self): self.prefix = self.prefix[:-len(self.tab)] def", "or %s is unsupported!' % graph_path) elif self.toolkit == 'keras':", "[] for input in node.input: input = input.strip().split(':') name =", "model files.''' if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0]", "DAG into chains chains = [] for node in self.graph.topologically_sorted():", "raise NotImplementedError('Image format or %s is unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path)", "</head> <body> <img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded) with", "== 'caffe': self.target = target self.net = 'CaffeNetwork' else: raise", "of an existing chain. attach_to_chain = chain break if attach_to_chain", "args = ', '.join(args) return self.statement('%s = self.%s(%s)' % (',", "'\\n' def emit_imports(self): return self.statement('from dlconv.%s import %s\\n' % (self.target,", "not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name)", "%s\\n' % (self.target, self.net)) def emit_class_def(self, name): return self.statement('class %s(%s):'", "chain. attach_to_chain = chain break if attach_to_chain is None: #", "<html> <head> <meta charset=\"utf-8\"> <title>Keras</title> </head> <body> <img alt=\"Model Graph\"", "chain in chains: b = '' for node in chain:", "if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module =", "self.toolkit) def _is_web_page(self, path): return path.split('.')[-1] in ('html', 'htm') def", "parent: # Node is part of an existing chain. attach_to_chain", "NotImplementedError('Visualization of %s is unsupported!' % self.toolkit) def _is_web_page(self, path):", "(name, self.net)) def emit_setup_def(self): return self.statement('def setup(self):') def emit_node(self, node):", "% (name, self.net)) def emit_setup_def(self): return self.statement('def setup(self):') def emit_node(self,", "json_format from importlib import import_module import json import numpy as", "v in node.attr: if k == 'cell_type': args.append(pair(k, \"'\" +", "'keras': self.target = target self.net = 'KerasNetwork' elif target ==", "source for this node.''' def pair(key, value): return '%s=%s' %", "source = self.emit_imports() source += self.emit_class_def(self.graph.name) self.indent() source += self.emit_setup_def()", "toolkit.lower() self.meta_path = meta_path def dump(self, graph_path): if self.toolkit ==", "open(code_output_path, 'w') as f: f.write(self.emit()) with open(data_output_path, 'wb') as f:", "data_output_path = os.path.join(code_output_dir, file_name + '.npy') with open(code_output_path, 'w') as", "Start a new chain for this node. attach_to_chain = []", "alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body> </html>\"\"\".format(base64_str=encoded) with open(html_path, 'w', encoding='utf-8')", "dlconv.keras.visualizer import KerasVisualizer png_path, html_path = (None, None) if graph_path.endswith('.png'):", "output = node.output for k, v in node.attr: if k", "' * 4 self.prefix = '' target = target.lower() if", "a new chain for this node. attach_to_chain = [] chains.append(attach_to_chain)", "file path containing graph in generated model files.''' if not", "unsupported!' % self.toolkit) def _is_web_page(self, path): return path.split('.')[-1] in ('html',", "= os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name) class_name = get_upper_case(file_name) net =", "the file path containing graph in generated model files.''' if", "path containing graph in generated model files.''' if not os.path.exists(model_output_dir):", "source += '\\n\\n'.join(blocks) return source class ModelSaver(object): def __init__(self, code_output_path,", "= data self.tab = ' ' * 4 self.prefix =", "target) def indent(self): self.prefix += self.tab def outdent(self): self.prefix =", "line by line source = self.emit_imports() source += self.emit_class_def(self.graph.name) self.indent()", "def _png_to_html(self, png_path, html_path): with open(png_path, \"rb\") as f: encoded", "self.target = target self.net = 'TensorFlowNetwork' elif target == 'keras':", "= self.%s(%s)' % (', '.join(output), node.op, args)) def dump(self, code_output_dir):", "emit_imports(self): return self.statement('from dlconv.%s import %s\\n' % (self.target, self.net)) def", "base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE> <html> <head> <meta charset=\"utf-8\"> <title>Keras</title> </head>", "== 'keras': self.target = target self.net = 'KerasNetwork' elif target", "self.code_output_path = code_output_path self.data_output_path = data_output_path def dump(self, model_output_dir): '''Return", "path.split('.')[-1] in ('html', 'htm') def _png_to_html(self, png_path, html_path): with open(png_path,", "into chains chains = [] for node in self.graph.topologically_sorted(): attach_to_chain", "= self.emit_imports() source += self.emit_class_def(self.graph.name) self.indent() source += self.emit_setup_def() self.indent()", "== 1: parent = get_real_name(node.input[0]) for chain in chains: if", "files.''' if not os.path.exists(model_output_dir): os.makedirs(model_output_dir) sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module", "def dump(self, json_path): json_txt = json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt) formatted", "self.net)) def emit_setup_def(self): return self.statement('def setup(self):') def emit_node(self, node): '''Emits", "if len(node.input) == 1: parent = get_real_name(node.input[0]) for chain in", "class JsonFormatter(object): '''Dumpt a DL graph into a Json file.'''", "[] chains.append(attach_to_chain) attach_to_chain.append(node) # Generate Python code line by line", "target == 'tensorflow': self.target = target self.net = 'TensorFlowNetwork' elif", "= target self.net = 'CaffeNetwork' else: raise ConversionError('Target %s is", "as np import os import sys from mmdnn.conversion.caffe.errors import ConversionError", "existing chain. attach_to_chain = chain break if attach_to_chain is None:", "data_output_path): self.code_output_path = code_output_path self.data_output_path = data_output_path def dump(self, model_output_dir):", "as f: np.save(f, self.data) return code_output_path, data_output_path def emit(self): #", "__init__(self, code_output_path, data_output_path): self.code_output_path = code_output_path self.data_output_path = data_output_path def", "html_path = (None, None) if graph_path.endswith('.png'): png_path = graph_path elif", "= self.prefix[:-len(self.tab)] def statement(self, s): return self.prefix + s +", "'TensorFlowNetwork' elif target == 'keras': self.target = target self.net =", "f: f.write(self.emit()) with open(data_output_path, 'wb') as f: np.save(f, self.data) return", "sort_keys=True) with open(json_path, 'w') as f: f.write(formatted) class PyWriter(object): '''Dumpt", "import_module(file_name) class_name = get_upper_case(file_name) net = getattr(module, class_name) return net.dump(self.data_output_path,", "self.net = 'TensorFlowNetwork' elif target == 'keras': self.target = target", "def emit(self): # Decompose DAG into chains chains = []", "with open(json_path, 'w') as f: f.write(formatted) class PyWriter(object): '''Dumpt a", "f.write(formatted) class PyWriter(object): '''Dumpt a DL graph into a Python", "os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name) class_name = get_upper_case(file_name) net = getattr(module,", "%s is unsupported!' % self.toolkit) def _is_web_page(self, path): return path.split('.')[-1]", "chain in chains: if chain[-1].name == parent: # Node is", "open(png_path, \"rb\") as f: encoded = base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE>", "%s(%s):' % (name, self.net)) def emit_setup_def(self): return self.statement('def setup(self):') def", "json.dumps(parsed, indent=4, sort_keys=True) with open(json_path, 'w') as f: f.write(formatted) class", "_is_web_page(self, path): return path.split('.')[-1] in ('html', 'htm') def _png_to_html(self, png_path,", "self.graph.node_dict parent = self.graph.get_node(name) args.append(parent.output[idx]) #FIXME: output = [node.output[0]] #", "+ fetch_attr_value(v) + \"'\")) else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\" +", "= node.output for k, v in node.attr: if k ==", "json_txt = json_format.MessageToJson(self.graph_def) parsed = json.loads(json_txt) formatted = json.dumps(parsed, indent=4,", "node.input: input = input.strip().split(':') name = ''.join(input[:-1]) idx = int(input[-1])", "dlconv.%s import %s\\n' % (self.target, self.net)) def emit_class_def(self, name): return", "graph_path else: raise NotImplementedError('Image format or %s is unsupported!' %", "= graph_path else: raise NotImplementedError('Image format or %s is unsupported!'", "= [] for chain in chains: b = '' for", "= [] for input in node.input: input = input.strip().split(':') name", "+ \".png\" html_path = graph_path else: raise NotImplementedError('Image format or", "encoded = base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE> <html> <head> <meta charset=\"utf-8\">", "= '' target = target.lower() if target == 'tensorflow': self.target", "if self.toolkit == 'tensorflow': from dlconv.tensorflow.visualizer import TensorFlowVisualizer if self._is_web_page(graph_path):", "(None, None) if graph_path.endswith('.png'): png_path = graph_path elif self._is_web_page(graph_path): png_path", "= target.lower() if target == 'tensorflow': self.target = target self.net", "as f: f.write(formatted) class PyWriter(object): '''Dumpt a DL graph into", "import KerasVisualizer png_path, html_path = (None, None) if graph_path.endswith('.png'): png_path", "'tensorflow': from dlconv.tensorflow.visualizer import TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise", "class ModelSaver(object): def __init__(self, code_output_path, data_output_path): self.code_output_path = code_output_path self.data_output_path", "+= self.emit_setup_def() self.indent() blocks = [] for chain in chains:", "blocks = [] for chain in chains: b = ''", "charset=\"utf-8\"> <title>Keras</title> </head> <body> <img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\" /> </body>", "source += self.emit_setup_def() self.indent() blocks = [] for chain in", "elif target == 'caffe': self.target = target self.net = 'CaffeNetwork'", "return net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object): def __init__(self, toolkit, meta_path): self.toolkit", "json.loads(json_txt) formatted = json.dumps(parsed, indent=4, sort_keys=True) with open(json_path, 'w') as", "png_path = graph_path + \".png\" html_path = graph_path else: raise", "= graph_path + \".png\" html_path = graph_path else: raise NotImplementedError('Image", "png_path, html_path): with open(png_path, \"rb\") as f: encoded = base64.b64encode(f.read()).decode('utf-8')", "1: parent = get_real_name(node.input[0]) for chain in chains: if chain[-1].name", "raise ConversionError('Target %s is not supported yet.' % target) def", "= get_real_name(node.input[0]) for chain in chains: if chain[-1].name == parent:", "\"'\")) else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\" + node.name + \"'\"))", "= data_output_path def dump(self, model_output_dir): '''Return the file path containing", "s + '\\n' def emit_imports(self): return self.statement('from dlconv.%s import %s\\n'", "= target self.net = 'TensorFlowNetwork' elif target == 'keras': self.target", "== parent: # Node is part of an existing chain.", "+= self.emit_node(node) blocks.append(b[:-1]) source += '\\n\\n'.join(blocks) return source class ModelSaver(object):", "blocks.append(b[:-1]) source += '\\n\\n'.join(blocks) return source class ModelSaver(object): def __init__(self,", "node. attach_to_chain = [] chains.append(attach_to_chain) attach_to_chain.append(node) # Generate Python code", "'\\n\\n'.join(blocks) return source class ModelSaver(object): def __init__(self, code_output_path, data_output_path): self.code_output_path", "sys.path.append(os.path.dirname(self.code_output_path)) file_name = os.path.splitext(os.path.basename(self.code_output_path))[0] module = import_module(file_name) class_name = get_upper_case(file_name)", "is not supported yet.' % target) def indent(self): self.prefix +=", "format or %s is unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path:", "parsed = json.loads(json_txt) formatted = json.dumps(parsed, indent=4, sort_keys=True) with open(json_path,", "net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object): def __init__(self, toolkit, meta_path): self.toolkit =", "data, target): self.graph = graph self.data = data self.tab =", "args.append(parent.output[idx]) #FIXME: output = [node.output[0]] # output = node.output for", "<head> <meta charset=\"utf-8\"> <title>Keras</title> </head> <body> <img alt=\"Model Graph\" src=\"data:image/png;base64,{base64_str}\"", "in chain: b += self.emit_node(node) blocks.append(b[:-1]) source += '\\n\\n'.join(blocks) return", "import get_lower_case, get_upper_case, get_real_name class JsonFormatter(object): '''Dumpt a DL graph", "== 'cell_type': args.append(pair(k, \"'\" + fetch_attr_value(v) + \"'\")) else: args.append(pair(k,", "else: args.append(pair(k, fetch_attr_value(v))) args.append(pair('name', \"'\" + node.name + \"'\")) #", "return self.statement('def setup(self):') def emit_node(self, node): '''Emits the Python source", "self.meta_path = meta_path def dump(self, graph_path): if self.toolkit == 'tensorflow':", "return code_output_path, data_output_path def emit(self): # Decompose DAG into chains", "import json_format from importlib import import_module import json import numpy", "is unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path, html_path) os.remove(png_path)", "import json import numpy as np import os import sys", "+ s + '\\n' def emit_imports(self): return self.statement('from dlconv.%s import", "%s is not supported yet.' % target) def indent(self): self.prefix", "self.statement('from dlconv.%s import %s\\n' % (self.target, self.net)) def emit_class_def(self, name):", "self.emit_node(node) blocks.append(b[:-1]) source += '\\n\\n'.join(blocks) return source class ModelSaver(object): def", "from dlconv.tensorflow.visualizer import TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path) else: raise NotImplementedError('Image", "source = \"\"\"<!DOCTYPE> <html> <head> <meta charset=\"utf-8\"> <title>Keras</title> </head> <body>", "def emit_setup_def(self): return self.statement('def setup(self):') def emit_node(self, node): '''Emits the", "or %s is unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path,", "= chain break if attach_to_chain is None: # Start a", "mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case, get_real_name class JsonFormatter(object): '''Dumpt a DL", "'caffe': self.target = target self.net = 'CaffeNetwork' else: raise ConversionError('Target", "__init__(self, graph, data, target): self.graph = graph self.data = data", "is None: # Start a new chain for this node.", "Node is part of an existing chain. attach_to_chain = chain", "unsupported!' % graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path, html_path) os.remove(png_path) else:", "from mmdnn.conversion.caffe.utils import get_lower_case, get_upper_case, get_real_name class JsonFormatter(object): '''Dumpt a", "# output = node.output for k, v in node.attr: if", "a Python script.''' def __init__(self, graph, data, target): self.graph =", "= [] chains.append(attach_to_chain) attach_to_chain.append(node) # Generate Python code line by", "for this node.''' def pair(key, value): return '%s=%s' % (key,", "% (key, value) args = [] for input in node.input:", "'cell_type': args.append(pair(k, \"'\" + fetch_attr_value(v) + \"'\")) else: args.append(pair(k, fetch_attr_value(v)))", "outdent(self): self.prefix = self.prefix[:-len(self.tab)] def statement(self, s): return self.prefix +", "= [node.output[0]] # output = node.output for k, v in", "(key, value) args = [] for input in node.input: input", "np import os import sys from mmdnn.conversion.caffe.errors import ConversionError from", "k == 'cell_type': args.append(pair(k, \"'\" + fetch_attr_value(v) + \"'\")) else:", "DL graph into a Python script.''' def __init__(self, graph, data,", "# Start a new chain for this node. attach_to_chain =", "code_output_path, data_output_path): self.code_output_path = code_output_path self.data_output_path = data_output_path def dump(self,", "def __init__(self, graph, data, target): self.graph = graph self.data =", "class_name) return net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object): def __init__(self, toolkit, meta_path):", "png_path = graph_path elif self._is_web_page(graph_path): png_path = graph_path + \".png\"", "graph_path) KerasVisualizer(self.meta_path).dump_png(png_path) if html_path: self._png_to_html(png_path, html_path) os.remove(png_path) else: raise NotImplementedError('Visualization", "node): '''Emits the Python source for this node.''' def pair(key,", "= ''.join(input[:-1]) idx = int(input[-1]) assert name in self.graph.node_dict parent", "get_upper_case, get_real_name class JsonFormatter(object): '''Dumpt a DL graph into a", "getattr(module, class_name) return net.dump(self.data_output_path, model_output_dir) class GraphDrawer(object): def __init__(self, toolkit,", "source class ModelSaver(object): def __init__(self, code_output_path, data_output_path): self.code_output_path = code_output_path", "os import sys from mmdnn.conversion.caffe.errors import ConversionError from mmdnn.conversion.caffe.common_graph import", "self.data = data self.tab = ' ' * 4 self.prefix", "'.py') data_output_path = os.path.join(code_output_dir, file_name + '.npy') with open(code_output_path, 'w')", "import numpy as np import os import sys from mmdnn.conversion.caffe.errors", "html_path) os.remove(png_path) else: raise NotImplementedError('Visualization of %s is unsupported!' %", "emit_node(self, node): '''Emits the Python source for this node.''' def", "name = ''.join(input[:-1]) idx = int(input[-1]) assert name in self.graph.node_dict", "file_name + '.npy') with open(code_output_path, 'w') as f: f.write(self.emit()) with", "_png_to_html(self, png_path, html_path): with open(png_path, \"rb\") as f: encoded =", "attach_to_chain = [] chains.append(attach_to_chain) attach_to_chain.append(node) # Generate Python code line", "def emit_imports(self): return self.statement('from dlconv.%s import %s\\n' % (self.target, self.net))", "self.toolkit == 'tensorflow': from dlconv.tensorflow.visualizer import TensorFlowVisualizer if self._is_web_page(graph_path): TensorFlowVisualizer(self.meta_path).dump_html(graph_path)", "import base64 from google.protobuf import json_format from importlib import import_module", "self.data) return code_output_path, data_output_path def emit(self): # Decompose DAG into", "a DL graph into a Json file.''' def __init__(self, graph):", "None if len(node.input) == 1: parent = get_real_name(node.input[0]) for chain", "as f: encoded = base64.b64encode(f.read()).decode('utf-8') source = \"\"\"<!DOCTYPE> <html> <head>", "code_output_dir): if not os.path.exists(code_output_dir): os.makedirs(code_output_dir) file_name = get_lower_case(self.graph.name) code_output_path =", "None: # Start a new chain for this node. attach_to_chain", "+= self.emit_class_def(self.graph.name) self.indent() source += self.emit_setup_def() self.indent() blocks = []", "else: raise NotImplementedError('Visualization of %s is unsupported!' % self.toolkit) def", "by line source = self.emit_imports() source += self.emit_class_def(self.graph.name) self.indent() source", "def emit_node(self, node): '''Emits the Python source for this node.'''", "= '' for node in chain: b += self.emit_node(node) blocks.append(b[:-1])", "= os.path.join(code_output_dir, file_name + '.npy') with open(code_output_path, 'w') as f:", "value): return '%s=%s' % (key, value) args = [] for", "into a Python script.''' def __init__(self, graph, data, target): self.graph", "graph_path) elif self.toolkit == 'keras': from dlconv.keras.visualizer import KerasVisualizer png_path,", "= get_lower_case(self.graph.name) code_output_path = os.path.join(code_output_dir, file_name + '.py') data_output_path =", "\".png\" html_path = graph_path else: raise NotImplementedError('Image format or %s", "chain break if attach_to_chain is None: # Start a new", "graph_path elif self._is_web_page(graph_path): png_path = graph_path + \".png\" html_path =", "= None if len(node.input) == 1: parent = get_real_name(node.input[0]) for", "int(input[-1]) assert name in self.graph.node_dict parent = self.graph.get_node(name) args.append(parent.output[idx]) #FIXME:", "supported yet.' % target) def indent(self): self.prefix += self.tab def", "JsonFormatter(object): '''Dumpt a DL graph into a Json file.''' def", "of %s is unsupported!' % self.toolkit) def _is_web_page(self, path): return", "os.path.join(code_output_dir, file_name + '.py') data_output_path = os.path.join(code_output_dir, file_name + '.npy')", "self.statement('class %s(%s):' % (name, self.net)) def emit_setup_def(self): return self.statement('def setup(self):')" ]
[ "if matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0 res = max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self,", "的二维二进制矩阵, 找出只包含 1 的最大矩形, 并返回其面积。 \"\"\" from typing import List", "window_L + 1) res = max(res, cur_area) ascend_stack.append(i) return res", "ascend_stack = [] for i in range(len(heights)): while ascend_stack and", "from typing import List class Solution: def maximalRectangle(self, matrix: List[List[str]])", "Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: \"\"\" 统计直方图然后单调递增栈 \"\"\"", "and heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1]", "0 heights = [0]*columns for r in range(rows): for c", "\"\"\" rows = len(matrix) if rows == 0: return 0", "1 window_R = i - 1 cur_area = window_L_height_min_height *", "leetcode-85 给定一个仅包含 0 和 1 , 大小为 rows x cols", "for c in range(columns): if matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0 res", ", 大小为 rows x cols 的二维二进制矩阵, 找出只包含 1 的最大矩形, 并返回其面积。", "* (window_R - window_L + 1) res = max(res, cur_area)", "heights = [-1] + heights + [-1] res = 0", "的最大矩形, 并返回其面积。 \"\"\" from typing import List class Solution: def", "+ [-1] res = 0 ascend_stack = [] for i", "= 0 ascend_stack = [] for i in range(len(heights)): while", "for i in range(len(heights)): while ascend_stack and heights[ascend_stack[-1]] > heights[i]:", "res = max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights: List[int]) -> int: #单调递增栈", "> heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1] + 1", "rows x cols 的二维二进制矩阵, 找出只包含 1 的最大矩形, 并返回其面积。 \"\"\" from", "heights[c]=0 res = max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights: List[int]) -> int:", "if rows == 0: return 0 columns = len(matrix[0]) res", "matrix: List[List[str]]) -> int: \"\"\" 统计直方图然后单调递增栈 \"\"\" rows = len(matrix)", "heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1] +", "给定一个仅包含 0 和 1 , 大小为 rows x cols 的二维二进制矩阵,", "i in range(len(heights)): while ascend_stack and heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height", "[] for i in range(len(heights)): while ascend_stack and heights[ascend_stack[-1]] >", "[-1] + heights + [-1] res = 0 ascend_stack =", "= ascend_stack[-1] + 1 window_R = i - 1 cur_area", "- window_L + 1) res = max(res, cur_area) ascend_stack.append(i) return", "== 0: return 0 columns = len(matrix[0]) res = 0", "(window_R - window_L + 1) res = max(res, cur_area) ascend_stack.append(i)", "-> int: #单调递增栈 heights = [-1] + heights + [-1]", "[0]*columns for r in range(rows): for c in range(columns): if", "0 ascend_stack = [] for i in range(len(heights)): while ascend_stack", "1 的最大矩形, 并返回其面积。 \"\"\" from typing import List class Solution:", "0 和 1 , 大小为 rows x cols 的二维二进制矩阵, 找出只包含", "r in range(rows): for c in range(columns): if matrix[r][c]==\"1\": heights[c]+=1", "= i - 1 cur_area = window_L_height_min_height * (window_R -", "heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1] + 1 window_R = i -", "columns = len(matrix[0]) res = 0 heights = [0]*columns for", "heights = [0]*columns for r in range(rows): for c in", "largestRectangleArea(self, heights: List[int]) -> int: #单调递增栈 heights = [-1] +", "in range(columns): if matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0 res = max(res,self.largestRectangleArea(heights))", "List[List[str]]) -> int: \"\"\" 统计直方图然后单调递增栈 \"\"\" rows = len(matrix) if", "= window_L_height_min_height * (window_R - window_L + 1) res =", "= [] for i in range(len(heights)): while ascend_stack and heights[ascend_stack[-1]]", "else: heights[c]=0 res = max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights: List[int]) ->", "List class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: \"\"\"", "window_L_height_min_height * (window_R - window_L + 1) res = max(res,", "len(matrix) if rows == 0: return 0 columns = len(matrix[0])", "res = 0 ascend_stack = [] for i in range(len(heights)):", "+ 1 window_R = i - 1 cur_area = window_L_height_min_height", "while ascend_stack and heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L", "\"\"\" leetcode-85 给定一个仅包含 0 和 1 , 大小为 rows x", "range(len(heights)): while ascend_stack and heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)]", "heights: List[int]) -> int: #单调递增栈 heights = [-1] + heights", "并返回其面积。 \"\"\" from typing import List class Solution: def maximalRectangle(self,", "ascend_stack[-1] + 1 window_R = i - 1 cur_area =", "x cols 的二维二进制矩阵, 找出只包含 1 的最大矩形, 并返回其面积。 \"\"\" from typing", "= max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights: List[int]) -> int: #单调递增栈 heights", "- 1 cur_area = window_L_height_min_height * (window_R - window_L +", "= len(matrix) if rows == 0: return 0 columns =", "for r in range(rows): for c in range(columns): if matrix[r][c]==\"1\":", "int: #单调递增栈 heights = [-1] + heights + [-1] res", "cols 的二维二进制矩阵, 找出只包含 1 的最大矩形, 并返回其面积。 \"\"\" from typing import", "rows == 0: return 0 columns = len(matrix[0]) res =", "res = 0 heights = [0]*columns for r in range(rows):", "和 1 , 大小为 rows x cols 的二维二进制矩阵, 找出只包含 1", "大小为 rows x cols 的二维二进制矩阵, 找出只包含 1 的最大矩形, 并返回其面积。 \"\"\"", "ascend_stack and heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L =", "heights[c]+=1 else: heights[c]=0 res = max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights: List[int])", "[-1] res = 0 ascend_stack = [] for i in", "heights + [-1] res = 0 ascend_stack = [] for", "1 , 大小为 rows x cols 的二维二进制矩阵, 找出只包含 1 的最大矩形,", "= 0 heights = [0]*columns for r in range(rows): for", "window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1] + 1 window_R =", "\"\"\" from typing import List class Solution: def maximalRectangle(self, matrix:", "range(rows): for c in range(columns): if matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0", "window_R = i - 1 cur_area = window_L_height_min_height * (window_R", "def maximalRectangle(self, matrix: List[List[str]]) -> int: \"\"\" 统计直方图然后单调递增栈 \"\"\" rows", "cur_area = window_L_height_min_height * (window_R - window_L + 1) res", "0: return 0 columns = len(matrix[0]) res = 0 heights", "maximalRectangle(self, matrix: List[List[str]]) -> int: \"\"\" 统计直方图然后单调递增栈 \"\"\" rows =", "max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights: List[int]) -> int: #单调递增栈 heights =", "List[int]) -> int: #单调递增栈 heights = [-1] + heights +", "1 cur_area = window_L_height_min_height * (window_R - window_L + 1)", "= [-1] + heights + [-1] res = 0 ascend_stack", "heights[i]: window_L_height_min_height = heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1] + 1 window_R", "c in range(columns): if matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0 res =", "统计直方图然后单调递增栈 \"\"\" rows = len(matrix) if rows == 0: return", "matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0 res = max(res,self.largestRectangleArea(heights)) def largestRectangleArea(self, heights:", "#单调递增栈 heights = [-1] + heights + [-1] res =", "import List class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int:", "return 0 columns = len(matrix[0]) res = 0 heights =", "len(matrix[0]) res = 0 heights = [0]*columns for r in", "+ heights + [-1] res = 0 ascend_stack = []", "<gh_stars>0 \"\"\" leetcode-85 给定一个仅包含 0 和 1 , 大小为 rows", "in range(len(heights)): while ascend_stack and heights[ascend_stack[-1]] > heights[i]: window_L_height_min_height =", "typing import List class Solution: def maximalRectangle(self, matrix: List[List[str]]) ->", "class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: \"\"\" 统计直方图然后单调递增栈", "rows = len(matrix) if rows == 0: return 0 columns", "0 columns = len(matrix[0]) res = 0 heights = [0]*columns", "\"\"\" 统计直方图然后单调递增栈 \"\"\" rows = len(matrix) if rows == 0:", "window_L = ascend_stack[-1] + 1 window_R = i - 1", "def largestRectangleArea(self, heights: List[int]) -> int: #单调递增栈 heights = [-1]", "i - 1 cur_area = window_L_height_min_height * (window_R - window_L", "-> int: \"\"\" 统计直方图然后单调递增栈 \"\"\" rows = len(matrix) if rows", "= len(matrix[0]) res = 0 heights = [0]*columns for r", "in range(rows): for c in range(columns): if matrix[r][c]==\"1\": heights[c]+=1 else:", "= [0]*columns for r in range(rows): for c in range(columns):", "range(columns): if matrix[r][c]==\"1\": heights[c]+=1 else: heights[c]=0 res = max(res,self.largestRectangleArea(heights)) def", "= heights[ascend_stack.pop(-1)] window_L = ascend_stack[-1] + 1 window_R = i", "int: \"\"\" 统计直方图然后单调递增栈 \"\"\" rows = len(matrix) if rows ==", "找出只包含 1 的最大矩形, 并返回其面积。 \"\"\" from typing import List class" ]
[ "pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -100], [-75, -50], [0, 0]])) #", "assert result def test_get_costs(): \"\"\" Testing a very simple network", "pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123,", "from pandapower.optimal_powerflow import OPFNotConverged import pandapower as pp try: import", "test_cost_piecewise_linear_load(): \"\"\" Testing a very simple network for the resulting", "min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net,", "max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876,", "< 1e-3 if __name__ == \"__main__\": # test_cost_piecewise_linear_sgen_very_unsteady_slopes() pytest.main([\"test_costs_pwl.py\", \"-s\"])", "1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a very simple network for", "abs(net.res_cost - net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\"", "(IEE), Kassel. All rights reserved. import numpy as np import", "vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000, controllable=True, max_p_kw=0,", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1, p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0,", "pp.create_load(net, 1, p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0)", "c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150,", "1, p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net,", "690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -300], [0, 0]])) # run", "pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50, -500], [0, 0]])) # run OPF", "net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load(): \"\"\" Testing a", "pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - - net.res_ext_grid.p_kw.values *", "= logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\" Testing a very simple", "logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\" Testing a very", "1.5 vm_min = 0.5 # create net net = pp.create_empty_network()", "import OPFNotConverged import pandapower as pp try: import pplog as", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0,", "[150, 101]])) # run OPF with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert", "result def test_get_costs(): \"\"\" Testing a very simple network for", "pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -100], [-75, -50], [0, 0]])) #", "boundaries: vm_max = 1.5 vm_min = 0.5 # create net", "min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\",", "c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50,", "vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10, max_p_kw=0, min_p_kw=-50,", "1e-3 # check and assert result def test_get_costs(): \"\"\" Testing", "max_p_kw=0, min_p_kw=-50, controllable=True) # pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False)", "import pandapower as pp try: import pplog as logging except", "verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - - net.res_ext_grid.p_kw.values * 10", "logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\" Testing a very simple network", "- net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing", "c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0,", "- net.res_ext_grid.p_kw.values * 10 < 1e-3 # check and assert", "1.5 < 1e-3 def test_cost_piecewise_linear_eg(): \"\"\" Testing a very simple", "690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500, 2],[-750,1 ], [0,2]])) # run", "min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50)", "pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost == 2 * net.res_gen.p_kw.values", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1, p_kw=100,", "net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a", "p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1,", "result def test_cost_piecewise_linear_sgen(): \"\"\" Testing a very simple network for", "vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net,", "verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values / 1.5) <", "net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a", "# and Energy System Technology (IEE), Kassel. All rights reserved.", "a very simple network for the resulting cost value constraints", "vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5,", "< 1e-3 def test_cost_piecewise_linear_eg(): \"\"\" Testing a very simple network", "pytest from pandapower.optimal_powerflow import OPFNotConverged import pandapower as pp try:", "# -*- coding: utf-8 -*- # Copyright (c) 2016-2018 by", "\"ext_grid\", np.array([[-50, -500], [0, 0]])) # run OPF pp.runopp(net, verbose=False)", "min_p_kw=-50, controllable=True) # pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net,", "0, \"gen\", np.array([[-150, -100], [-75, -50], [0, 0]])) # run", "min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50)", "net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a", "Kassel. All rights reserved. import numpy as np import pytest", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1, p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50,", "max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0,", "1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a very simple network for", "\"\"\" # boundaries: vm_max = 1.5 vm_min = 0.5 #", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -200],", "check and assert result def test_get_costs(): \"\"\" Testing a very", "[0, 0]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert", "p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123,", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1,", "c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150,", "assert abs(net.res_cost - net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes():", "coding: utf-8 -*- # Copyright (c) 2016-2018 by University of", "pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876,", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50, -500], [0, 0]]))", "min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True) # pp.create_ext_grid(net, 0)", "Kassel and Fraunhofer Institute for Energy Economics # and Energy", "0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True) #", "(c) 2016-2018 by University of Kassel and Fraunhofer Institute for", "cost value constraints with OPF \"\"\" # boundaries: vm_max =", "net.res_ext_grid.p_kw.values * 10 < 1e-3 # check and assert result", "pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_gen.p_kw.values / 1.5", "name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0,", "1, p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net,", "assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load_uneven_slopes():", "controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20,", "pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] # assert net.res_cost - net.res_sgen.p_kw.values /", "def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a very simple network for the", "net.res_cost - - net.res_ext_grid.p_kw.values * 10 < 1e-3 # check", "], [0,2]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] #", "0.95 # create net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min,", "690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -200], [-75, -50], [0, 0]]))", "pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values / 1.5)", "0, \"load\", np.array([[0, 0], [75, 51], [150, 101]])) # run", "pp.create_gen(net, 1, p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True) # pp.create_ext_grid(net, 0) pp.create_load(net,", "test_cost_piecewise_linear_eg(): \"\"\" Testing a very simple network for the resulting", "run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost == 2", "10 < 1e-3 # check and assert result def test_get_costs():", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -100],", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -100], [-75, -50],", "verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_gen.p_kw.values / 1.5 <", "pp try: import pplog as logging except ImportError: import logging", "Technology (IEE), Kassel. All rights reserved. import numpy as np", "= pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10)", "# run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost ==", "pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net,", "import logging logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\" Testing", "# run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost -", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -200], [-75, -50],", "np import pytest from pandapower.optimal_powerflow import OPFNotConverged import pandapower as", "pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True)", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1,", "= pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4)", "assert net[\"OPF_converged\"] assert net.res_cost - - net.res_ext_grid.p_kw.values * 10 <", "1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690)", "- net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing", "pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1, 50,", "verbose=False) assert net[\"OPF_converged\"] assert net.res_cost == 2 * net.res_gen.p_kw.values #", "value constraints with OPF \"\"\" # boundaries: vm_max = 1.5", "= 1.05 vm_min = 0.95 # create net net =", "net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\"", "1.5 < 1e-3 if __name__ == \"__main__\": # test_cost_piecewise_linear_sgen_very_unsteady_slopes() pytest.main([\"test_costs_pwl.py\",", "\"sgen\", np.array([[-1500, 2],[-750,1 ], [0,2]])) # run OPF pp.runopp(net, verbose=False)", "resulting cost value constraints with OPF \"\"\" # boundaries: vm_max", "-500], [0, 0]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"]", "* 690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50, -500], [0, 0]])) #", "50], [150, 100]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"]", "== 2 * net.res_gen.p_kw.values # check and assert result def", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000,", "System Technology (IEE), Kassel. All rights reserved. import numpy as", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -300],", "pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net,", "assert net[\"OPF_converged\"] assert net.res_cost - net.res_gen.p_kw.values / 1.5 < 1e-3", "2 * net.res_gen.p_kw.values # check and assert result def test_cost_piecewise_linear_sgen():", "0]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost", "max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False)", "Energy Economics # and Energy System Technology (IEE), Kassel. All", "value constraints with OPF \"\"\" # boundaries: vm_max = 1.05", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100,", "constraints with OPF \"\"\" # boundaries: vm_max = 1.5 vm_min", "rights reserved. import numpy as np import pytest from pandapower.optimal_powerflow", "pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net,", "logging except ImportError: import logging logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def", "net.res_gen.p_kw.values # check and assert result def test_cost_piecewise_linear_sgen(): \"\"\" Testing", "for the resulting cost value constraints with OPF \"\"\" #", "-200], [-75, -50], [0, 0]])) # run OPF pp.runopp(net, verbose=False)", "\"load\", np.array([[0, 0], [75, 51], [150, 101]])) # run OPF", "vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1, p_kw=100, controllable=True, max_p_kw=150,", "1.5 < 1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a very simple", "net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min,", "assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values / 1.5) < 1e-3", "University of Kassel and Fraunhofer Institute for Energy Economics #", "controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0, 1,", "vm_max = 1.05 vm_min = 0.95 # create net net", "0, \"ext_grid\", np.array([[-50, -500], [0, 0]])) # run OPF pp.runopp(net,", "np.array([[0, 0], [75, 51], [150, 101]])) # run OPF with", "\"\"\" Testing a very simple network for the resulting cost", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 50],", "[-75, -50], [0, 0]])) # run OPF pp.runopp(net, verbose=False) assert", "the resulting cost value constraints with OPF \"\"\" # boundaries:", "Fraunhofer Institute for Energy Economics # and Energy System Technology", "1.5 < 1e-3 def test_cost_piecewise_linear_load(): \"\"\" Testing a very simple", "pp.create_sgen(net, 1, p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0)", "run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - -", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75,", "def test_cost_piecewise_linear_eg(): \"\"\" Testing a very simple network for the", "r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\",", "Testing a very simple network for the resulting cost value", "OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost == 2 *", "min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000, controllable=True,", "ImportError: import logging logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\"", "np.array([[0, 0], [75, 50], [150, 100]])) # run OPF pp.runopp(net,", "OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] # assert net.res_cost - net.res_sgen.p_kw.values", "Institute for Energy Economics # and Energy System Technology (IEE),", "abs(net.res_cost - net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\"", "0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 *", "np.array([[-150, -100], [-75, -50], [0, 0]])) # run OPF pp.runopp(net,", "check and assert result def test_cost_piecewise_linear_sgen(): \"\"\" Testing a very", "run OPF with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost", "OPFNotConverged import pandapower as pp try: import pplog as logging", "* 10 < 1e-3 # check and assert result def", "import pytest from pandapower.optimal_powerflow import OPFNotConverged import pandapower as pp", "min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1,", "net[\"OPF_converged\"] assert net.res_cost == 2 * net.res_gen.p_kw.values # check and", "assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 if __name__", "-300], [0, 0]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"]", "pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -200], [-75, -50], [0, 0]])) #", "OPF \"\"\" # boundaries: vm_max = 1.05 vm_min = 0.95", "690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 51], [150, 101]]))", "* 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 51], [150,", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0,", "np.array([[-1500, 2],[-750,1 ], [0,2]])) # run OPF pp.runopp(net, verbose=False) assert", "np.array([[-150, -200], [-75, -50], [0, 0]])) # run OPF pp.runopp(net,", "100]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost", "= 0.95 # create net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max,", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -100],", "numpy as np import pytest from pandapower.optimal_powerflow import OPFNotConverged import", "OPF \"\"\" # boundaries: vm_max = 1.5 vm_min = 0.5", "OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - - net.res_ext_grid.p_kw.values", "* 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 50], [150,", "net.res_cost - net.res_gen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_eg(): \"\"\"", "simple network for the resulting cost value constraints with OPF", "min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1, p_kw=100, controllable=True,", "and Fraunhofer Institute for Energy Economics # and Energy System", "* 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -100], [-75, -50], [0,", "min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net,", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500, 2],[-750,1", "* 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -100], [-75, -50], [0,", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500, 2],[-750,1 ], [0,2]]))", "reserved. import numpy as np import pytest from pandapower.optimal_powerflow import", "min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1, p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0)", "vm_min = 0.95 # create net net = pp.create_empty_network() pp.create_bus(net,", "verbose=False) assert net[\"OPF_converged\"] # assert net.res_cost - net.res_sgen.p_kw.values / 1.5", "# pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1,", "0], [75, 50], [150, 100]])) # run OPF pp.runopp(net, verbose=False)", "test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a very simple network for the resulting", "= 1.5 vm_min = 0.5 # create net net =", "net[\"OPF_converged\"] assert net.res_cost - - net.res_ext_grid.p_kw.values * 10 < 1e-3", "1e-3 def test_cost_piecewise_linear_load(): \"\"\" Testing a very simple network for", "net[\"OPF_converged\"] assert net.res_cost - net.res_gen.p_kw.values / 1.5 < 1e-3 def", "net[\"OPF_converged\"] # assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3", "<reponame>mathildebadoual/pandapower # -*- coding: utf-8 -*- # Copyright (c) 2016-2018", "= 0.5 # create net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max,", "assert abs(net.res_cost - net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes():", "test_cost_piecewise_linear_gen(): \"\"\" Testing a very simple network for the resulting", "and Energy System Technology (IEE), Kassel. All rights reserved. import", "try: import pplog as logging except ImportError: import logging logger", "net.res_sgen.p_kw.values / 1.5 < 1e-3 if __name__ == \"__main__\": #", "as pp try: import pplog as logging except ImportError: import", "0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\",", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150,", "0, \"sgen\", np.array([[-150, -100], [-75, -50], [0, 0]])) # run", "690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 50], [150, 100]]))", "# run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost -", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50,", "max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False)", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1,", "\"gen\", np.array([[-150, -300], [0, 0]])) # run OPF pp.runopp(net, verbose=False)", "OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values /", "# boundaries: vm_max = 1.05 vm_min = 0.95 # create", "690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -100], [-75, -50], [0, 0]]))", "assert net[\"OPF_converged\"] assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3", "51], [150, 101]])) # run OPF with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False)", "assert net[\"OPF_converged\"] # assert net.res_cost - net.res_sgen.p_kw.values / 1.5 <", "vn_kv=.4) pp.create_gen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net,", "\"sgen\", np.array([[-150, -200], [-75, -50], [0, 0]])) # run OPF", "0, \"load\", np.array([[0, 0], [75, 50], [150, 100]])) # run", "101]])) # run OPF with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert net[\"OPF_converged\"]", "constraints with OPF \"\"\" # boundaries: vm_max = 1.05 vm_min", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10,", "def test_cost_piecewise_linear_gen(): \"\"\" Testing a very simple network for the", "[150, 100]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert", "np.array([[-150, -300], [0, 0]])) # run OPF pp.runopp(net, verbose=False) assert", "[75, 50], [150, 100]])) # run OPF pp.runopp(net, verbose=False) assert", "assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load():", "< 1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a very simple network", "r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"load\",", "assert net.res_cost - - net.res_ext_grid.p_kw.values * 10 < 1e-3 #", "assert result def test_cost_piecewise_linear_sgen(): \"\"\" Testing a very simple network", "2],[-750,1 ], [0,2]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"]", "-*- # Copyright (c) 2016-2018 by University of Kassel and", "Copyright (c) 2016-2018 by University of Kassel and Fraunhofer Institute", "\"sgen\", np.array([[-150, -100], [-75, -50], [0, 0]])) # run OPF", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50, -500], [0,", "690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50, -500], [0, 0]])) # run", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150,", "0, \"gen\", np.array([[-150, -300], [0, 0]])) # run OPF pp.runopp(net,", "# create net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.)", "-*- coding: utf-8 -*- # Copyright (c) 2016-2018 by University", "import pplog as logging except ImportError: import logging logger =", "/ 1.5 < 1e-3 def test_cost_piecewise_linear_eg(): \"\"\" Testing a very", "-100], [-75, -50], [0, 0]])) # run OPF pp.runopp(net, verbose=False)", "< 1e-3 def test_cost_piecewise_linear_load(): \"\"\" Testing a very simple network", "def test_cost_piecewise_linear_sgen(): \"\"\" Testing a very simple network for the", "pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net,", "[0,2]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] # assert", "pandapower as pp try: import pplog as logging except ImportError:", "# assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 if", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -200], [-75,", "network for the resulting cost value constraints with OPF \"\"\"", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 51],", "max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True) # pp.create_ext_grid(net,", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -100], [-75, -50],", "verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_sgen.p_kw.values / 1.5 <", "/ 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a very", "2016-2018 by University of Kassel and Fraunhofer Institute for Energy", "- net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load(): \"\"\" Testing", "< 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a very simple network", "def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a very simple network for the", "- net.res_gen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_eg(): \"\"\" Testing", "for Energy Economics # and Energy System Technology (IEE), Kassel.", "c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500,", "- net.res_sgen.p_kw.values / 1.5 < 1e-3 if __name__ == \"__main__\":", "0, \"sgen\", np.array([[-150, -200], [-75, -50], [0, 0]])) # run", "as np import pytest from pandapower.optimal_powerflow import OPFNotConverged import pandapower", "with OPF \"\"\" # boundaries: vm_max = 1.05 vm_min =", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_load(net, 1,", "OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_gen.p_kw.values /", "Energy System Technology (IEE), Kassel. All rights reserved. import numpy", "pp.create_gen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0)", "1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a very simple network for", "All rights reserved. import numpy as np import pytest from", "assert net.res_cost == 2 * net.res_gen.p_kw.values # check and assert", "OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_sgen.p_kw.values /", "create net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net,", "np.array([[-50, -500], [0, 0]])) # run OPF pp.runopp(net, verbose=False) assert", "test_cost_piecewise_linear_sgen(): \"\"\" Testing a very simple network for the resulting", "test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a very simple network for the resulting", "with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values", "* net.res_gen.p_kw.values # check and assert result def test_cost_piecewise_linear_sgen(): \"\"\"", "pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 50], [150, 100]])) #", "0], [75, 51], [150, 101]])) # run OPF with pytest.raises(OPFNotConverged):", "min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100, controllable=True,", "net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max,", "# check and assert result def test_get_costs(): \"\"\" Testing a", "pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500, 2],[-750,1 ], [0,2]])) # run OPF", "net.res_gen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_eg(): \"\"\" Testing a", "net[\"OPF_converged\"] assert net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 def", "p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1,", "run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] # assert net.res_cost -", "/ 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a very", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500, 2],[-750,1 ],", "min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50)", "and assert result def test_cost_piecewise_linear_sgen(): \"\"\" Testing a very simple", "pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500,", "[75, 51], [150, 101]])) # run OPF with pytest.raises(OPFNotConverged): pp.runopp(net,", "pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_sgen.p_kw.values / 1.5", "assert net[\"OPF_converged\"] assert net.res_cost == 2 * net.res_gen.p_kw.values # check", "run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_sgen.p_kw.values", "vm_min = 0.5 # create net net = pp.create_empty_network() pp.create_bus(net,", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -300], [0,", "run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values", "import numpy as np import pytest from pandapower.optimal_powerflow import OPFNotConverged", "1.05 vm_min = 0.95 # create net net = pp.create_empty_network()", "except ImportError: import logging logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen():", "- net.res_load.p_kw.values / 1.5) < 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing", "as logging except ImportError: import logging logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\")", "by University of Kassel and Fraunhofer Institute for Energy Economics", "assert net.res_cost - net.res_gen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_eg():", "< 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a very simple network", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1, p_kw=-100,", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-1000, controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50,", "* 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -200], [-75, -50], [0,", "test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a very simple network for the resulting", "vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net,", "# check and assert result def test_cost_piecewise_linear_sgen(): \"\"\" Testing a", "min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0,", "* 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-1500, 2],[-750,1 ], [0,2]])) #", "/ 1.5 < 1e-3 if __name__ == \"__main__\": # test_cost_piecewise_linear_sgen_very_unsteady_slopes()", "r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\",", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -100], [-75,", "# Copyright (c) 2016-2018 by University of Kassel and Fraunhofer", "50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net,", "def test_cost_piecewise_linear_load(): \"\"\" Testing a very simple network for the", "pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values /", "net[\"OPF_converged\"] assert abs(net.res_cost - net.res_load.p_kw.values / 1.5) < 1e-3 def", "0.5 # create net net = pp.create_empty_network() pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min,", "logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\" Testing a very simple network for", "controllable=True) # pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0,", "net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 def test_cost_piecewise_linear_load(): \"\"\"", "690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -100], [-75, -50], [0, 0]]))", "max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0, 1, 50,", "boundaries: vm_max = 1.05 vm_min = 0.95 # create net", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0],", "1, p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True) # pp.create_ext_grid(net, 0) pp.create_load(net, 1,", "# run OPF with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert", "pplog as logging except ImportError: import logging logger = logging.getLogger(__name__)", "vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5,", "p_kw=-10, max_p_kw=0, min_p_kw=-50, controllable=True) # pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20,", "/ 1.5 < 1e-3 def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a very", "- - net.res_ext_grid.p_kw.values * 10 < 1e-3 # check and", "# boundaries: vm_max = 1.5 vm_min = 0.5 # create", "OPF with pytest.raises(OPFNotConverged): pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert abs(net.res_cost -", "logging logger = logging.getLogger(__name__) logger.setLevel(\"DEBUG\") def test_cost_piecewise_linear_gen(): \"\"\" Testing a", "min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net, 1, p_kw=-10, max_p_kw=0,", "pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100", "and assert result def test_get_costs(): \"\"\" Testing a very simple", "1, p_kw=20, controllable=False) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0,", "1.5) < 1e-3 def test_cost_piecewise_linear_sgen_uneven_slopes(): \"\"\" Testing a very simple", "pp.create_sgen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0)", "with OPF \"\"\" # boundaries: vm_max = 1.5 vm_min =", "-50], [0, 0]])) # run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"]", "x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\", np.array([[-150, -100], [-75,", "/ 1.5 < 1e-3 def test_cost_piecewise_linear_load(): \"\"\" Testing a very", "controllable=True, max_p_kw=0, min_p_kw=-1500, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net, 1, p_kw=20,", "min_vm_pu=vm_min, vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1, p_kw=-100, controllable=True,", "max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"ext_grid\", np.array([[-50, -500],", "min_vm_pu=vm_min, vn_kv=.4) pp.create_sgen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50)", "\"\"\" # boundaries: vm_max = 1.05 vm_min = 0.95 #", "1.5) < 1e-3 def test_cost_piecewise_linear_sgen_very_unsteady_slopes(): \"\"\" Testing a very simple", "of Kassel and Fraunhofer Institute for Energy Economics # and", "* 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -300], [0, 0]])) #", "\"load\", np.array([[0, 0], [75, 50], [150, 100]])) # run OPF", "0, \"sgen\", np.array([[-1500, 2],[-750,1 ], [0,2]])) # run OPF pp.runopp(net,", "pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -300], [0, 0]])) # run OPF", "controllable=False) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876,", "0) pp.create_line_from_parameters(net, 0, 1, 50, name=\"line2\", r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876,", "1e-3 def test_cost_piecewise_linear_eg(): \"\"\" Testing a very simple network for", "net.res_cost - net.res_sgen.p_kw.values / 1.5 < 1e-3 if __name__ ==", "1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50, min_q_kvar=-50) pp.create_ext_grid(net, 0) pp.create_load(net,", "test_get_costs(): \"\"\" Testing a very simple network for the resulting", "p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net, 0) pp.create_line_from_parameters(net, 0,", "def test_get_costs(): \"\"\" Testing a very simple network for the", "pp.create_piecewise_linear_cost(net, 0, \"load\", np.array([[0, 0], [75, 51], [150, 101]])) #", "run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] assert net.res_cost - net.res_gen.p_kw.values", "\"gen\", np.array([[-150, -100], [-75, -50], [0, 0]])) # run OPF", "net.res_cost == 2 * net.res_gen.p_kw.values # check and assert result", "pandapower.optimal_powerflow import OPFNotConverged import pandapower as pp try: import pplog", "r_ohm_per_km=0.876, c_nf_per_km=260.0, max_i_ka=0.123, x_ohm_per_km=0.1159876, max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"sgen\",", "very simple network for the resulting cost value constraints with", "max_loading_percent=100 * 690) pp.create_piecewise_linear_cost(net, 0, \"gen\", np.array([[-150, -300], [0, 0]]))", "vn_kv=.4) pp.create_load(net, 1, p_kw=100, controllable=True, max_p_kw=150, min_p_kw=50, max_q_kvar=0, min_q_kvar=0) pp.create_ext_grid(net,", "# run OPF pp.runopp(net, verbose=False) assert net[\"OPF_converged\"] # assert net.res_cost", "vm_max = 1.5 vm_min = 0.5 # create net net", "< 1e-3 # check and assert result def test_get_costs(): \"\"\"", "max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=.4) pp.create_gen(net, 1, p_kw=-100, controllable=True, max_p_kw=-5, min_p_kw=-150, max_q_kvar=50,", "Economics # and Energy System Technology (IEE), Kassel. All rights", "def test_cost_piecewise_linear_load_uneven_slopes(): \"\"\" Testing a very simple network for the", "utf-8 -*- # Copyright (c) 2016-2018 by University of Kassel", "vn_kv=10.) pp.create_bus(net, max_vm_pu=vm_max, min_vm_pu=vm_min, vn_kv=10) pp.create_ext_grid(net, 0, max_p_kw=0, min_p_kw=-50) pp.create_gen(net," ]
[ "while 1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >= config.COOKIE_COUNT: break", "1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1)", "# @CreateTime: 2022-01-20 # @UpdateTime: 2022-01-20 import redis import config", "cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\"", "% len(cookie_list)) def run_cookie_refresh(): cookie_refresh() if __name__ == \"__main__\": run_cookie_refresh()", "cookie_login from cookie_api import app red = redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT,", ">= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def run_cookie_refresh(): cookie_refresh()", "# @UpdateTime: 2022-01-20 import redis import config import cookie_login from", "import app red = redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, )", "db=config.REDIS_DB, decode_responses=True, ) # 刷新cookie数量 def cookie_refresh(): while 1: cookie_list", "break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def run_cookie_refresh(): cookie_refresh() if __name__", "# 刷新cookie数量 def cookie_refresh(): while 1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if", "red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list))", "import cookie_login from cookie_api import app red = redis.Redis( host=config.REDIS_HOST,", "-*- # @Author: GXR # @CreateTime: 2022-01-20 # @UpdateTime: 2022-01-20", "# @Author: GXR # @CreateTime: 2022-01-20 # @UpdateTime: 2022-01-20 import", "redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, ) # 刷新cookie数量 def cookie_refresh():", "app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def run_cookie_refresh(): cookie_refresh() if __name__ == \"__main__\":", "from cookie_api import app red = redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB,", "host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, ) # 刷新cookie数量 def cookie_refresh(): while", "utf-8 -*- # @Author: GXR # @CreateTime: 2022-01-20 # @UpdateTime:", "config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def run_cookie_refresh(): cookie_refresh() if", "if len(cookie_list) >= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def", "@Author: GXR # @CreateTime: 2022-01-20 # @UpdateTime: 2022-01-20 import redis", "= red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" %", "-*- coding: utf-8 -*- # @Author: GXR # @CreateTime: 2022-01-20", "red = redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, ) # 刷新cookie数量", "len(cookie_list) >= config.COOKIE_COUNT: break cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def run_cookie_refresh():", "import config import cookie_login from cookie_api import app red =", "GXR # @CreateTime: 2022-01-20 # @UpdateTime: 2022-01-20 import redis import", "import redis import config import cookie_login from cookie_api import app", "2022-01-20 import redis import config import cookie_login from cookie_api import", "redis import config import cookie_login from cookie_api import app red", "2022-01-20 # @UpdateTime: 2022-01-20 import redis import config import cookie_login", "cookie_refresh(): while 1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >= config.COOKIE_COUNT:", "def cookie_refresh(): while 1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list) >=", "cookie_login.run_cookie_login(1) app.logger.info(\"[cookie数量正常]-[%s]\" % len(cookie_list)) def run_cookie_refresh(): cookie_refresh() if __name__ ==", "@CreateTime: 2022-01-20 # @UpdateTime: 2022-01-20 import redis import config import", "cookie_api import app red = redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True,", ") # 刷新cookie数量 def cookie_refresh(): while 1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE)", "coding: utf-8 -*- # @Author: GXR # @CreateTime: 2022-01-20 #", "app red = redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, ) #", "刷新cookie数量 def cookie_refresh(): while 1: cookie_list = red.smembers(config.REDIS_KEY_COOKIE) if len(cookie_list)", "port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, ) # 刷新cookie数量 def cookie_refresh(): while 1:", "config import cookie_login from cookie_api import app red = redis.Redis(", "# -*- coding: utf-8 -*- # @Author: GXR # @CreateTime:", "decode_responses=True, ) # 刷新cookie数量 def cookie_refresh(): while 1: cookie_list =", "@UpdateTime: 2022-01-20 import redis import config import cookie_login from cookie_api", "= redis.Redis( host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, decode_responses=True, ) # 刷新cookie数量 def" ]
[ "from feemodel.app.transient import TransientOnline from feemodel.app.pools import PoolsOnlineEstimator from feemodel.app.predict", "from feemodel.app.pools import PoolsOnlineEstimator from feemodel.app.predict import Prediction from feemodel.app.simonline", "import PoolsOnlineEstimator from feemodel.app.predict import Prediction from feemodel.app.simonline import SimOnline", "from feemodel.app.predict import Prediction from feemodel.app.simonline import SimOnline __all__ =", "feemodel.app.predict import Prediction from feemodel.app.simonline import SimOnline __all__ = [", "import TransientOnline from feemodel.app.pools import PoolsOnlineEstimator from feemodel.app.predict import Prediction", "TransientOnline from feemodel.app.pools import PoolsOnlineEstimator from feemodel.app.predict import Prediction from", "from feemodel.app.simonline import SimOnline __all__ = [ 'TransientOnline', 'PoolsOnlineEstimator', 'Prediction',", "feemodel.app.simonline import SimOnline __all__ = [ 'TransientOnline', 'PoolsOnlineEstimator', 'Prediction', 'SimOnline'", "import SimOnline __all__ = [ 'TransientOnline', 'PoolsOnlineEstimator', 'Prediction', 'SimOnline' ]", "feemodel.app.transient import TransientOnline from feemodel.app.pools import PoolsOnlineEstimator from feemodel.app.predict import", "PoolsOnlineEstimator from feemodel.app.predict import Prediction from feemodel.app.simonline import SimOnline __all__", "Prediction from feemodel.app.simonline import SimOnline __all__ = [ 'TransientOnline', 'PoolsOnlineEstimator',", "import Prediction from feemodel.app.simonline import SimOnline __all__ = [ 'TransientOnline',", "feemodel.app.pools import PoolsOnlineEstimator from feemodel.app.predict import Prediction from feemodel.app.simonline import" ]
[ "-*- from __future__ import unicode_literals # start tutorial from django.db", "blank=True, null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute = False scope_prefix", "NgFormValidationMixin from djng.styling.bootstrap3.forms import Bootstrap3ModelForm class SubscribeUser(models.Model): full_name = models.CharField(", "form_name = 'my_form' class Meta: model = SubscribeUser fields =", "null=True) permit = models.FileField(\"Permit\", blank=True, null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm):", "'my_form' class Meta: model = SubscribeUser fields = ['full_name', 'avatar',", "= False scope_prefix = 'subscribe_data' form_name = 'my_form' class Meta:", "# -*- coding: utf-8 -*- from __future__ import unicode_literals #", "class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute = False scope_prefix = 'subscribe_data'", "= 'subscribe_data' form_name = 'my_form' class Meta: model = SubscribeUser", "# start tutorial from django.db import models from djng.forms import", "class SubscribeUser(models.Model): full_name = models.CharField( \"<NAME>\", max_length=99) avatar = models.ImageField(\"Avatar\",", "models from djng.forms import NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms import Bootstrap3ModelForm", "models.CharField( \"<NAME>\", max_length=99) avatar = models.ImageField(\"Avatar\", blank=False, null=True) permit =", "\"<NAME>\", max_length=99) avatar = models.ImageField(\"Avatar\", blank=False, null=True) permit = models.FileField(\"Permit\",", "full_name = models.CharField( \"<NAME>\", max_length=99) avatar = models.ImageField(\"Avatar\", blank=False, null=True)", "import models from djng.forms import NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms import", "blank=False, null=True) permit = models.FileField(\"Permit\", blank=True, null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin,", "use_required_attribute = False scope_prefix = 'subscribe_data' form_name = 'my_form' class", "coding: utf-8 -*- from __future__ import unicode_literals # start tutorial", "from django.db import models from djng.forms import NgModelFormMixin, NgFormValidationMixin from", "NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms import Bootstrap3ModelForm class SubscribeUser(models.Model): full_name =", "djng.styling.bootstrap3.forms import Bootstrap3ModelForm class SubscribeUser(models.Model): full_name = models.CharField( \"<NAME>\", max_length=99)", "import unicode_literals # start tutorial from django.db import models from", "max_length=99) avatar = models.ImageField(\"Avatar\", blank=False, null=True) permit = models.FileField(\"Permit\", blank=True,", "avatar = models.ImageField(\"Avatar\", blank=False, null=True) permit = models.FileField(\"Permit\", blank=True, null=True)", "permit = models.FileField(\"Permit\", blank=True, null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute", "SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute = False scope_prefix = 'subscribe_data' form_name", "models.FileField(\"Permit\", blank=True, null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute = False", "from __future__ import unicode_literals # start tutorial from django.db import", "'subscribe_data' form_name = 'my_form' class Meta: model = SubscribeUser fields", "from djng.forms import NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms import Bootstrap3ModelForm class", "= models.CharField( \"<NAME>\", max_length=99) avatar = models.ImageField(\"Avatar\", blank=False, null=True) permit", "-*- coding: utf-8 -*- from __future__ import unicode_literals # start", "Bootstrap3ModelForm): use_required_attribute = False scope_prefix = 'subscribe_data' form_name = 'my_form'", "djng.forms import NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms import Bootstrap3ModelForm class SubscribeUser(models.Model):", "NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute = False scope_prefix = 'subscribe_data' form_name =", "False scope_prefix = 'subscribe_data' form_name = 'my_form' class Meta: model", "= 'my_form' class Meta: model = SubscribeUser fields = ['full_name',", "utf-8 -*- from __future__ import unicode_literals # start tutorial from", "import NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms import Bootstrap3ModelForm class SubscribeUser(models.Model): full_name", "Bootstrap3ModelForm class SubscribeUser(models.Model): full_name = models.CharField( \"<NAME>\", max_length=99) avatar =", "__future__ import unicode_literals # start tutorial from django.db import models", "start tutorial from django.db import models from djng.forms import NgModelFormMixin,", "from djng.styling.bootstrap3.forms import Bootstrap3ModelForm class SubscribeUser(models.Model): full_name = models.CharField( \"<NAME>\",", "models.ImageField(\"Avatar\", blank=False, null=True) permit = models.FileField(\"Permit\", blank=True, null=True) class SubscribeForm(NgModelFormMixin,", "unicode_literals # start tutorial from django.db import models from djng.forms", "django.db import models from djng.forms import NgModelFormMixin, NgFormValidationMixin from djng.styling.bootstrap3.forms", "null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute = False scope_prefix =", "import Bootstrap3ModelForm class SubscribeUser(models.Model): full_name = models.CharField( \"<NAME>\", max_length=99) avatar", "= models.FileField(\"Permit\", blank=True, null=True) class SubscribeForm(NgModelFormMixin, NgFormValidationMixin, Bootstrap3ModelForm): use_required_attribute =", "class Meta: model = SubscribeUser fields = ['full_name', 'avatar', 'permit']", "= models.ImageField(\"Avatar\", blank=False, null=True) permit = models.FileField(\"Permit\", blank=True, null=True) class", "tutorial from django.db import models from djng.forms import NgModelFormMixin, NgFormValidationMixin", "SubscribeUser(models.Model): full_name = models.CharField( \"<NAME>\", max_length=99) avatar = models.ImageField(\"Avatar\", blank=False,", "scope_prefix = 'subscribe_data' form_name = 'my_form' class Meta: model =" ]
[ "OF ANY # KIND, either express or implied. See the", "input_b, output_layout: str, input_a_layout: str, input_b_layout: str, op_name: str, ):", "more contributor license agreements. See the NOTICE file # distributed", "topi\"\"\" return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b): \"\"\"Call the subtract", "return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b): \"\"\"Call the subtract op", "0), index_map=output_transformed_layout) n, h, w, c = s.get_loops(block) h_o, h_i", "Apache Software Foundation (ASF) under one # or more contributor", "[None, 32]) wio, wii = s.split(w_i, [None, 2]) s.reorder(n, h_o,", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "2.0 (the # \"License\"); you may not use this file", "the implementation: 1) The inputs will be multiple of crouton", "s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0),", "return topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m, input_a, input_b, output_layout: str,", "topi from ..utils import get_layout_transform_fn def add_broadcast_compute(input_a, input_b): \"\"\"Call the", "s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout) if input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout =", "s.split(c, [None, 32]) wio, wii = s.split(w_i, [None, 2]) s.reorder(n,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "specific language governing permissions and limitations # under the License.", "Please note the following assumptions made by the implementation: 1)", "under the License is distributed on an # \"AS IS\"", "str, op_name: str, ): \"\"\"Schedule for input and output layout", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "def tir_broadcast_schedule( out_m, input_a, input_b, output_layout: str, input_a_layout: str, input_b_layout:", "s.get_loops(block) h_o, h_i = s.split(h, [None, 8]) w_o, w_i =", "distributed with this work for additional information # regarding copyright", "for the # specific language governing permissions and limitations #", "for input and output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\" func =", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "input_a_layout: str, input_b_layout: str, op_name: str, ): \"\"\"Schedule for input", "The inputs will be multiple of crouton layout except for", "out_m]) s = tir.Schedule(func) block_dict = {\"add\": \"T_add\", \"subtract\": \"T_subtract\",", "file # distributed with this work for additional information #", "input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout)", "w_i = s.split(w, [None, 4]) c_o, c_i = s.split(c, [None,", "= get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout) n, h, w, c", "tvm import topi from ..utils import get_layout_transform_fn def add_broadcast_compute(input_a, input_b):", "h_o, w_o, c_o, h_i, wio, c_i, wii) fused = s.fuse(c_i,", "def add_broadcast_compute(input_a, input_b): \"\"\"Call the add op from topi\"\"\" return", "= s.split(w, [None, 4]) c_o, c_i = s.split(c, [None, 32])", "implied. See the License for the # specific language governing", "to you under the Apache License, Version 2.0 (the #", "s.split(w, [None, 4]) c_o, c_i = s.split(c, [None, 32]) wio,", "and schedule for add, multiply, subtract slice op Please note", "may not use this file except in compliance # with", "= s.get_block(block_dict[op_name]) if input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block,", "..utils import get_layout_transform_fn def add_broadcast_compute(input_a, input_b): \"\"\"Call the add op", "= tir.Schedule(func) block_dict = {\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"}", "the axis that needs broadcasting.\"\"\" from tvm import te from", "output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout) n, h, w,", "# pylint: disable=invalid-name \"\"\"Compute and schedule for add, multiply, subtract", "License, Version 2.0 (the # \"License\"); you may not use", "either express or implied. See the License for the #", "\"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout) if input_b_layout", "assumptions made by the implementation: 1) The inputs will be", "additional information # regarding copyright ownership. The ASF licenses this", "layout except for the axis that needs broadcasting.\"\"\" from tvm", "c = s.get_loops(block) h_o, h_i = s.split(h, [None, 8]) w_o,", "See the NOTICE file # distributed with this work for", "limitations # under the License. # pylint: disable=invalid-name \"\"\"Compute and", "input_b) def tir_broadcast_schedule( out_m, input_a, input_b, output_layout: str, input_a_layout: str,", "c_i = s.split(c, [None, 32]) wio, wii = s.split(w_i, [None,", "input_b, out_m]) s = tir.Schedule(func) block_dict = {\"add\": \"T_add\", \"subtract\":", "Apache License, Version 2.0 (the # \"License\"); you may not", "str, input_b_layout: str, op_name: str, ): \"\"\"Schedule for input and", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "file except in compliance # with the License. You may", "# specific language governing permissions and limitations # under the", "except for the axis that needs broadcasting.\"\"\" from tvm import", "input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout)", "subtract op from topi\"\"\" return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b):", "you may not use this file except in compliance #", "layout nhwc-8h2w32c2w-2d considering broadcast\"\"\" func = te.create_prim_func([input_a, input_b, out_m]) s", "use this file except in compliance # with the License.", "contributor license agreements. See the NOTICE file # distributed with", "schedule for add, multiply, subtract slice op Please note the", "inputs will be multiple of crouton layout except for the", "s.split(w_i, [None, 2]) s.reorder(n, h_o, w_o, c_o, h_i, wio, c_i,", "input_b_layout: str, op_name: str, ): \"\"\"Schedule for input and output", "\"T_multiply\"} block = s.get_block(block_dict[op_name]) if input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout =", "broadcasting.\"\"\" from tvm import te from tvm import tir from", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "subtract slice op Please note the following assumptions made by", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout) if input_b_layout ==", "with this work for additional information # regarding copyright ownership.", "topi\"\"\" return topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m, input_a, input_b, output_layout:", "work for additional information # regarding copyright ownership. The ASF", "op from topi\"\"\" return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b): \"\"\"Call", "\"\"\"Call the add op from topi\"\"\" return topi.add(input_a, input_b) def", "def multiply_broadcast_compute(input_a, input_b): \"\"\"Call the multiply op from topi\"\"\" return", "considering broadcast\"\"\" func = te.create_prim_func([input_a, input_b, out_m]) s = tir.Schedule(func)", "distributed under the License is distributed on an # \"AS", "output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\" func = te.create_prim_func([input_a, input_b, out_m])", "# software distributed under the License is distributed on an", "topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b): \"\"\"Call the subtract op from", "the License. You may obtain a copy of the License", "that needs broadcasting.\"\"\" from tvm import te from tvm import", "under the Apache License, Version 2.0 (the # \"License\"); you", "# under the License. # pylint: disable=invalid-name \"\"\"Compute and schedule", "governing permissions and limitations # under the License. # pylint:", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "regarding copyright ownership. The ASF licenses this file # to", "or agreed to in writing, # software distributed under the", "h_i, wio, c_i, wii) fused = s.fuse(c_i, wii) s.vectorize(fused) return", "h_i = s.split(h, [None, 8]) w_o, w_i = s.split(w, [None,", "the subtract op from topi\"\"\" return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a,", "or more contributor license agreements. See the NOTICE file #", "this work for additional information # regarding copyright ownership. The", "get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout) n, h, w, c =", "permissions and limitations # under the License. # pylint: disable=invalid-name", "the NOTICE file # distributed with this work for additional", "op from topi\"\"\" return topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m, input_a,", "c_o, c_i = s.split(c, [None, 32]) wio, wii = s.split(w_i,", "32]) wio, wii = s.split(w_i, [None, 2]) s.reorder(n, h_o, w_o,", "block = s.get_block(block_dict[op_name]) if input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout)", "= get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block,", "te.create_prim_func([input_a, input_b, out_m]) s = tir.Schedule(func) block_dict = {\"add\": \"T_add\",", "\"\"\"Compute and schedule for add, multiply, subtract slice op Please", "and limitations # under the License. # pylint: disable=invalid-name \"\"\"Compute", "block_dict = {\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"} block =", "index_map=input_a_transformed_layout) if input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\",", "get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout) if input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout", "of crouton layout except for the axis that needs broadcasting.\"\"\"", "8]) w_o, w_i = s.split(w, [None, 4]) c_o, c_i =", "op_name: str, ): \"\"\"Schedule for input and output layout nhwc-8h2w32c2w-2d", "KIND, either express or implied. See the License for the", "slice op Please note the following assumptions made by the", "input and output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\" func = te.create_prim_func([input_a,", "subtract_broadcast_compute(input_a, input_b): \"\"\"Call the subtract op from topi\"\"\" return topi.subtract(input_a,", "buffer=(\"write\", 0), index_map=output_transformed_layout) n, h, w, c = s.get_loops(block) h_o,", "4]) c_o, c_i = s.split(c, [None, 32]) wio, wii =", "0), index_map=input_a_transformed_layout) if input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block,", "or implied. See the License for the # specific language", "express or implied. See the License for the # specific", "input_b): \"\"\"Call the subtract op from topi\"\"\" return topi.subtract(input_a, input_b)", "s.get_block(block_dict[op_name]) if input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\",", "the following assumptions made by the implementation: 1) The inputs", "from ..utils import get_layout_transform_fn def add_broadcast_compute(input_a, input_b): \"\"\"Call the add", "tir from tvm import topi from ..utils import get_layout_transform_fn def", "the # specific language governing permissions and limitations # under", "\"T_subtract\", \"multiply\": \"T_multiply\"} block = s.get_block(block_dict[op_name]) if input_a_layout == \"nhwc-8h2w32c2w-2d\":", "add_broadcast_compute(input_a, input_b): \"\"\"Call the add op from topi\"\"\" return topi.add(input_a,", "may obtain a copy of the License at # #", "needs broadcasting.\"\"\" from tvm import te from tvm import tir", "from tvm import topi from ..utils import get_layout_transform_fn def add_broadcast_compute(input_a,", "The ASF licenses this file # to you under the", "return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b): \"\"\"Call the multiply op", "1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout) n,", "note the following assumptions made by the implementation: 1) The", "the add op from topi\"\"\" return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a,", "# Licensed to the Apache Software Foundation (ASF) under one", "= s.split(w_i, [None, 2]) s.reorder(n, h_o, w_o, c_o, h_i, wio,", "for add, multiply, subtract slice op Please note the following", "\"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout =", "input_b): \"\"\"Call the multiply op from topi\"\"\" return topi.multiply(input_a, input_b)", "law or agreed to in writing, # software distributed under", "Foundation (ASF) under one # or more contributor license agreements.", "from topi\"\"\" return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b): \"\"\"Call the", "\"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"} block = s.get_block(block_dict[op_name]) if input_a_layout", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "input_b) def multiply_broadcast_compute(input_a, input_b): \"\"\"Call the multiply op from topi\"\"\"", "input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout)", "Software Foundation (ASF) under one # or more contributor license", "w_o, w_i = s.split(w, [None, 4]) c_o, c_i = s.split(c,", "import te from tvm import tir from tvm import topi", "# regarding copyright ownership. The ASF licenses this file #", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "str, ): \"\"\"Schedule for input and output layout nhwc-8h2w32c2w-2d considering", "OR CONDITIONS OF ANY # KIND, either express or implied.", "w, c = s.get_loops(block) h_o, h_i = s.split(h, [None, 8])", "multiply, subtract slice op Please note the following assumptions made", "= s.get_loops(block) h_o, h_i = s.split(h, [None, 8]) w_o, w_i", "this file # to you under the Apache License, Version", "topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m, input_a, input_b, output_layout: str, input_a_layout:", "copyright ownership. The ASF licenses this file # to you", "output_layout: str, input_a_layout: str, input_b_layout: str, op_name: str, ): \"\"\"Schedule", "\"\"\"Schedule for input and output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\" func", "in writing, # software distributed under the License is distributed", "the License. # pylint: disable=invalid-name \"\"\"Compute and schedule for add,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout) n, h,", "= s.split(c, [None, 32]) wio, wii = s.split(w_i, [None, 2])", "nhwc-8h2w32c2w-2d considering broadcast\"\"\" func = te.create_prim_func([input_a, input_b, out_m]) s =", "# \"License\"); you may not use this file except in", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\",", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "from topi\"\"\" return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b): \"\"\"Call the", "h, w, c = s.get_loops(block) h_o, h_i = s.split(h, [None,", "[None, 8]) w_o, w_i = s.split(w, [None, 4]) c_o, c_i", "# distributed with this work for additional information # regarding", "writing, # software distributed under the License is distributed on", "buffer=(\"read\", 0), index_map=input_a_transformed_layout) if input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout)", "add op from topi\"\"\" return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b):", "[None, 4]) c_o, c_i = s.split(c, [None, 32]) wio, wii", "CONDITIONS OF ANY # KIND, either express or implied. See", "tvm import te from tvm import tir from tvm import", "be multiple of crouton layout except for the axis that", "for additional information # regarding copyright ownership. The ASF licenses", "axis that needs broadcasting.\"\"\" from tvm import te from tvm", "the Apache Software Foundation (ASF) under one # or more", "h_o, h_i = s.split(h, [None, 8]) w_o, w_i = s.split(w,", "# # Unless required by applicable law or agreed to", "Version 2.0 (the # \"License\"); you may not use this", "if input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0),", "under the License. # pylint: disable=invalid-name \"\"\"Compute and schedule for", "one # or more contributor license agreements. See the NOTICE", "func = te.create_prim_func([input_a, input_b, out_m]) s = tir.Schedule(func) block_dict =", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "from topi\"\"\" return topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m, input_a, input_b,", "for the axis that needs broadcasting.\"\"\" from tvm import te", "multiple of crouton layout except for the axis that needs", "except in compliance # with the License. You may obtain", "input_b): \"\"\"Call the add op from topi\"\"\" return topi.add(input_a, input_b)", "tvm import tir from tvm import topi from ..utils import", "buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout)", "NOTICE file # distributed with this work for additional information", "wii = s.split(w_i, [None, 2]) s.reorder(n, h_o, w_o, c_o, h_i,", "this file except in compliance # with the License. You", "crouton layout except for the axis that needs broadcasting.\"\"\" from", "wio, wii = s.split(w_i, [None, 2]) s.reorder(n, h_o, w_o, c_o,", "def subtract_broadcast_compute(input_a, input_b): \"\"\"Call the subtract op from topi\"\"\" return", "== \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout) if", "license agreements. See the NOTICE file # distributed with this", "tir.Schedule(func) block_dict = {\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"} block", "required by applicable law or agreed to in writing, #", "input_a, input_b, output_layout: str, input_a_layout: str, input_b_layout: str, op_name: str,", "wio, c_i, wii) fused = s.fuse(c_i, wii) s.vectorize(fused) return s", "the License for the # specific language governing permissions and", "ANY # KIND, either express or implied. See the License", "the License is distributed on an # \"AS IS\" BASIS,", "made by the implementation: 1) The inputs will be multiple", "add, multiply, subtract slice op Please note the following assumptions", "import get_layout_transform_fn def add_broadcast_compute(input_a, input_b): \"\"\"Call the add op from", "pylint: disable=invalid-name \"\"\"Compute and schedule for add, multiply, subtract slice", "not use this file except in compliance # with the", "disable=invalid-name \"\"\"Compute and schedule for add, multiply, subtract slice op", "Unless required by applicable law or agreed to in writing,", "(ASF) under one # or more contributor license agreements. See", "w_o, c_o, h_i, wio, c_i, wii) fused = s.fuse(c_i, wii)", "\"multiply\": \"T_multiply\"} block = s.get_block(block_dict[op_name]) if input_a_layout == \"nhwc-8h2w32c2w-2d\": input_a_transformed_layout", "= te.create_prim_func([input_a, input_b, out_m]) s = tir.Schedule(func) block_dict = {\"add\":", "= get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=(\"read\", 0), index_map=input_a_transformed_layout) if input_b_layout == \"nhwc-8h2w32c2w-2d\":", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "will be multiple of crouton layout except for the axis", "): \"\"\"Schedule for input and output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\"", "import topi from ..utils import get_layout_transform_fn def add_broadcast_compute(input_a, input_b): \"\"\"Call", "[None, 2]) s.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii)", "(the # \"License\"); you may not use this file except", "s.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii) fused =", "topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b): \"\"\"Call the multiply op from", "ASF licenses this file # to you under the Apache", "{\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"} block = s.get_block(block_dict[op_name]) if", "2]) s.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii) fused", "te from tvm import tir from tvm import topi from", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "= {\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"} block = s.get_block(block_dict[op_name])", "\"subtract\": \"T_subtract\", \"multiply\": \"T_multiply\"} block = s.get_block(block_dict[op_name]) if input_a_layout ==", "index_map=output_transformed_layout) n, h, w, c = s.get_loops(block) h_o, h_i =", "get_layout_transform_fn def add_broadcast_compute(input_a, input_b): \"\"\"Call the add op from topi\"\"\"", "ownership. The ASF licenses this file # to you under", "the multiply op from topi\"\"\" return topi.multiply(input_a, input_b) def tir_broadcast_schedule(", "c_o, h_i, wio, c_i, wii) fused = s.fuse(c_i, wii) s.vectorize(fused)", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "s = tir.Schedule(func) block_dict = {\"add\": \"T_add\", \"subtract\": \"T_subtract\", \"multiply\":", "multiply_broadcast_compute(input_a, input_b): \"\"\"Call the multiply op from topi\"\"\" return topi.multiply(input_a,", "str, input_a_layout: str, input_b_layout: str, op_name: str, ): \"\"\"Schedule for", "with the License. You may obtain a copy of the", "if input_b_layout == \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1),", "topi\"\"\" return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b): \"\"\"Call the multiply", "applicable law or agreed to in writing, # software distributed", "== \"nhwc-8h2w32c2w-2d\": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=(\"read\", 1), index_map=input_b_transformed_layout) output_transformed_layout", "from tvm import tir from tvm import topi from ..utils", "s.transform_layout(block, buffer=(\"write\", 0), index_map=output_transformed_layout) n, h, w, c = s.get_loops(block)", "by the implementation: 1) The inputs will be multiple of", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "file # to you under the Apache License, Version 2.0", "# with the License. You may obtain a copy of", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "language governing permissions and limitations # under the License. #", "and output layout nhwc-8h2w32c2w-2d considering broadcast\"\"\" func = te.create_prim_func([input_a, input_b,", "1) The inputs will be multiple of crouton layout except", "multiply op from topi\"\"\" return topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m,", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "broadcast\"\"\" func = te.create_prim_func([input_a, input_b, out_m]) s = tir.Schedule(func) block_dict", "from tvm import te from tvm import tir from tvm", "under one # or more contributor license agreements. See the", "License. # pylint: disable=invalid-name \"\"\"Compute and schedule for add, multiply,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "information # regarding copyright ownership. The ASF licenses this file", "the Apache License, Version 2.0 (the # \"License\"); you may", "you under the Apache License, Version 2.0 (the # \"License\");", "following assumptions made by the implementation: 1) The inputs will", "# KIND, either express or implied. See the License for", "op from topi\"\"\" return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b): \"\"\"Call", "s.split(h, [None, 8]) w_o, w_i = s.split(w, [None, 4]) c_o,", "agreements. See the NOTICE file # distributed with this work", "op Please note the following assumptions made by the implementation:", "licenses this file # to you under the Apache License,", "out_m, input_a, input_b, output_layout: str, input_a_layout: str, input_b_layout: str, op_name:", "= s.split(h, [None, 8]) w_o, w_i = s.split(w, [None, 4])", "by applicable law or agreed to in writing, # software", "input_b) def subtract_broadcast_compute(input_a, input_b): \"\"\"Call the subtract op from topi\"\"\"", "# Unless required by applicable law or agreed to in", "implementation: 1) The inputs will be multiple of crouton layout", "\"\"\"Call the subtract op from topi\"\"\" return topi.subtract(input_a, input_b) def", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "License. You may obtain a copy of the License at", "You may obtain a copy of the License at #", "tir_broadcast_schedule( out_m, input_a, input_b, output_layout: str, input_a_layout: str, input_b_layout: str,", "\"\"\"Call the multiply op from topi\"\"\" return topi.multiply(input_a, input_b) def", "n, h, w, c = s.get_loops(block) h_o, h_i = s.split(h,", "compliance # with the License. You may obtain a copy", "import tir from tvm import topi from ..utils import get_layout_transform_fn" ]
[ "image, build_cm=do_nothing, path=None): return super(DagsterDockerImage, cls).__new__( cls, check.str_param(image, \"image\"), check.callable_param(build_cm,", "to the image's path. Defaults to docker/images/<IMAGE NAME> \"\"\" def", "last_updated timestamp for a particular python_version of this image.\"\"\" check.str_param(timestamp,", "custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if python_version: last_updated = self._get_last_updated_for_python_version(python_version)", "base_image.local_image(python_version) else: raise Exception(\"Unrecognized source {}\".format(source)) # Set Dagster version", "image.\"\"\" check.str_param(python_version, \"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as f: last_updated", "check.str_param(python_version, \"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as f: last_updated =", "\"build_cm\"), check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image) ), ) @property", "last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) else: tag =", "# Set Dagster version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return docker_args def", "check.opt_str_param(custom_tag, \"custom_tag\") if python_version: last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version,", "cls, check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\",", "= yaml.safe_load(f.read()) last_updated[python_version] = timestamp with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as", "\"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\") last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version,", "\"\"\"Represents a Dagster image. Properties: image (str): Name of the", "Also, we allow references in the image versions.yaml to another", "raise Exception(\"Unrecognized source {}\".format(source)) # Set Dagster version docker_args[\"DAGSTER_VERSION\"] =", "\"last_updated.yaml\"), \"w\") as f: yaml.dump(last_updated, f, default_flow_style=False) def local_image(self, python_version):", "def aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates the AWS ECR image name,", "ecr_image, get_aws_account_id, get_aws_region from .utils import ( execute_docker_build, execute_docker_push, execute_docker_tag,", "docker_args def build(self, timestamp, dagster_version, python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\")", "python_version_image_tag(python_version, last_updated) else: tag = custom_tag return ecr_image( self.image, tag,", "check.invariant( dagster_version == current_dagster_version, desc=\"Current dagster version ({}) does not", "template assets used here IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def", "from dagster import check from .ecr import ecr_image, get_aws_account_id, get_aws_region", "versions.get(python_version, {}) docker_args = image_info.get(\"docker_args\", {}) if \"base_image\" in image_info:", "here IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def do_nothing(_cwd): yield class", "this image.\"\"\" check.str_param(python_version, \"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as f:", "f: last_updated = yaml.safe_load(f.read()) last_updated[python_version] = timestamp with open(os.path.join(self.path, \"last_updated.yaml\"),", "(e.g. for populating a build cache) path (Optional(str)): The path", "\"dagster\" # Location of the template assets used here IMAGES_PATH", "\"\"\"Retrieve the last_updated timestamp for a particular python_version of this", "the last_updated timestamp for a particular python_version of this image.\"\"\"", ".ecr import ecr_image, get_aws_account_id, get_aws_region from .utils import ( execute_docker_build,", "Default repository prefix used for local images DEFAULT_LOCAL_PREFIX = \"dagster\"", "image to ECR.\"\"\" if custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), )", "a particular python_version of this image.\"\"\" check.str_param(python_version, \"python_version\") with open(os.path.join(self.path,", "check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image)", "get_aws_region from .utils import ( execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag, )", "image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version and custom_tag)) check.opt_str_param(python_version,", "import ( execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag, ) # Default repository", "= os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path): with open(last_updated_path, \"r\") as f:", "\"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif source == \"local\": docker_args[\"BASE_IMAGE\"] =", "check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") last_updated = {} last_updated_path = os.path.join(self.path,", "tag = custom_tag return ecr_image( self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), )", "return ecr_image( self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def _get_docker_args(self, python_version):", "as f: yaml.dump(last_updated, f, default_flow_style=False) def local_image(self, python_version): \"\"\"Generates the", "parent image. \"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions", "last_updated = yaml.safe_load(f.read()) last_updated[python_version] = timestamp with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\")", "docker_args, \"Cannot override an existing BASE_IMAGE\" ) base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"])", "\"custom_tag\") if python_version: last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated)", "_set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update the last_updated timestamp for a particular", ") def _get_docker_args(self, python_version): \"\"\"Retrieve Docker arguments from this image's", ") base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"] if source ==", "= base_image.aws_image(python_version) elif source == \"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else:", "\"timestamp\") check.str_param(python_version, \"python_version\") check.invariant( dagster_version == current_dagster_version, desc=\"Current dagster version", "import namedtuple import yaml from dagster import __version__ as current_dagster_version", "yaml.dump(last_updated, f, default_flow_style=False) def local_image(self, python_version): \"\"\"Generates the local image", "docker_args=self._get_docker_args(python_version), cwd=self.path, ) def push(self, python_version, custom_tag=None): \"\"\"Push this image", "def local_image(self, python_version): \"\"\"Generates the local image name, like: \"dagster/foo:some-tag\"", "\"BASE_IMAGE\" not in docker_args, \"Cannot override an existing BASE_IMAGE\" )", "local image name, like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\") last_updated =", "as f: last_updated = yaml.safe_load(f.read()) last_updated[python_version] = timestamp with open(os.path.join(self.path,", "source = image_info[\"base_image\"][\"source\"] if source == \"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version)", "\"python_version\") last_updated = {} last_updated_path = os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path):", "# Default repository prefix used for local images DEFAULT_LOCAL_PREFIX =", "Properties: image (str): Name of the image build_cm (function): function", "yaml.safe_load(f.read()) image_info = versions.get(python_version, {}) docker_args = image_info.get(\"docker_args\", {}) if", "build (e.g. for populating a build cache) path (Optional(str)): The", "build(self, timestamp, dagster_version, python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") check.invariant( dagster_version", "custom_tag return ecr_image( self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def _get_docker_args(self,", "for this image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions", "if source == \"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif source ==", "in docker_args, \"Cannot override an existing BASE_IMAGE\" ) base_image =", "prefix used for local images DEFAULT_LOCAL_PREFIX = \"dagster\" # Location", "= timestamp with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as f: yaml.dump(last_updated, f,", "== \"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else: raise Exception(\"Unrecognized source {}\".format(source))", "__version__ as current_dagster_version from dagster import check from .ecr import", "provided arg ({})\".format( current_dagster_version, dagster_version ), ) with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp,", "\"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read()) return list(versions.keys()) def", "last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates", "and custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if python_version: last_updated =", "if python_version: last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) else:", "execute_docker_tag, python_version_image_tag, ) # Default repository prefix used for local", "last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update the last_updated timestamp for", "versions = yaml.safe_load(f.read()) image_info = versions.get(python_version, {}) docker_args = image_info.get(\"docker_args\",", "(str): Name of the image build_cm (function): function that is", "({})\".format( current_dagster_version, dagster_version ), ) with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build(", "os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path): with open(last_updated_path, \"r\") as f: last_updated", "with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, ) def", "a base image. If defined, set the BASE_IMAGE Docker arg", "of the image build_cm (function): function that is a context", ") @property def python_versions(self): \"\"\"List of Python versions supported for", "tag = python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def aws_image(self,", "particular python_version of this image.\"\"\" check.str_param(python_version, \"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"),", "import os from collections import namedtuple import yaml from dagster", "to ECR.\"\"\" if custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), ) execute_docker_push(self.aws_image(python_version=None,", "= \"dagster\" # Location of the template assets used here", "image. If defined, set the BASE_IMAGE Docker arg from the", "execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), ) execute_docker_push(self.aws_image(python_version=None, custom_tag=custom_tag)) else: execute_docker_tag(self.local_image(python_version), self.aws_image(python_version))", "def build(self, timestamp, dagster_version, python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") check.invariant(", "class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")): \"\"\"Represents a Dagster image. Properties:", "(function): function that is a context manager for build (e.g.", "for a particular python_version of this image.\"\"\" check.str_param(python_version, \"python_version\") with", "{}) docker_args = image_info.get(\"docker_args\", {}) if \"base_image\" in image_info: check.invariant(", "latest Dagster version. Also, we allow references in the image", "a particular python_version of this image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\")", "existing BASE_IMAGE\" ) base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"] if", "timestamp for a particular python_version of this image.\"\"\" check.str_param(python_version, \"python_version\")", "dagster_version ), ) with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version),", "this image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") last_updated = {} last_updated_path", "docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return docker_args def build(self, timestamp, dagster_version, python_version):", "\"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read()) image_info = versions.get(python_version,", "f: last_updated = yaml.safe_load(f.read()) return last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp, python_version):", "version. Also, we allow references in the image versions.yaml to", "and update with latest Dagster version. Also, we allow references", "used here IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def do_nothing(_cwd): yield", "\"last_updated.yaml\"), \"r\") as f: last_updated = yaml.safe_load(f.read()) return last_updated[python_version] def", "= self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag)", "= image_info.get(\"docker_args\", {}) if \"base_image\" in image_info: check.invariant( \"BASE_IMAGE\" not", "the image versions.yaml to another Dagster image to use as", "<filename>python_modules/automation/automation/docker/dagster_docker.py import contextlib import os from collections import namedtuple import", "docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else: raise Exception(\"Unrecognized source {}\".format(source)) # Set", "namedtuple import yaml from dagster import __version__ as current_dagster_version from", "update with latest Dagster version. Also, we allow references in", "as f: versions = yaml.safe_load(f.read()) image_info = versions.get(python_version, {}) docker_args", "\"image build_cm path\")): \"\"\"Represents a Dagster image. Properties: image (str):", "build_cm=do_nothing, path=None): return super(DagsterDockerImage, cls).__new__( cls, check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"),", "of the parent image. \"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as", "the image build_cm (function): function that is a context manager", "full name of the parent image. \"\"\" with open(os.path.join(self.path, \"versions.yaml\"),", "AWS ECR image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version and", "f: versions = yaml.safe_load(f.read()) image_info = versions.get(python_version, {}) docker_args =", "check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image) ), ) @property def", "of Python versions supported for this image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"),", "open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as f: yaml.dump(last_updated, f, default_flow_style=False) def local_image(self,", "if os.path.exists(last_updated_path): with open(last_updated_path, \"r\") as f: last_updated = yaml.safe_load(f.read())", "base_image.aws_image(python_version) elif source == \"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else: raise", "manager for build (e.g. for populating a build cache) path", "in the image versions.yaml to another Dagster image to use", "path to the image's path. Defaults to docker/images/<IMAGE NAME> \"\"\"", "check.invariant( \"BASE_IMAGE\" not in docker_args, \"Cannot override an existing BASE_IMAGE\"", "else: raise Exception(\"Unrecognized source {}\".format(source)) # Set Dagster version docker_args[\"DAGSTER_VERSION\"]", "last_updated timestamp for a particular python_version of this image.\"\"\" check.str_param(python_version,", "\"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image) ),", "\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read())", "Set Dagster version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return docker_args def build(self,", "dagster version ({}) does not match provided arg ({})\".format( current_dagster_version,", "for local images DEFAULT_LOCAL_PREFIX = \"dagster\" # Location of the", "dagster_version == current_dagster_version, desc=\"Current dagster version ({}) does not match", "assets used here IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def do_nothing(_cwd):", "({}) does not match provided arg ({})\".format( current_dagster_version, dagster_version ),", "image's versions.yaml, and update with latest Dagster version. Also, we", "set the BASE_IMAGE Docker arg from the full name of", "python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") check.invariant( dagster_version == current_dagster_version, desc=\"Current", "DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"] if source == \"aws\": docker_args[\"BASE_IMAGE\"] =", "references in the image versions.yaml to another Dagster image to", "build_cm (function): function that is a context manager for build", "BASE_IMAGE Docker arg from the full name of the parent", "last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image,", "version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return docker_args def build(self, timestamp, dagster_version,", "image build_cm (function): function that is a context manager for", "check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if python_version: last_updated = self._get_last_updated_for_python_version(python_version) tag", "\"timestamp\") check.str_param(python_version, \"python_version\") last_updated = {} last_updated_path = os.path.join(self.path, \"last_updated.yaml\")", "python_version): \"\"\"Retrieve the last_updated timestamp for a particular python_version of", "python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, ) def push(self, python_version, custom_tag=None):", "Defaults to docker/images/<IMAGE NAME> \"\"\" def __new__(cls, image, build_cm=do_nothing, path=None):", "default=os.path.join(os.path.dirname(__file__), \"images\", image) ), ) @property def python_versions(self): \"\"\"List of", "path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image) ), ) @property def python_versions(self):", "name of the parent image. \"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\")", ") def push(self, python_version, custom_tag=None): \"\"\"Push this image to ECR.\"\"\"", "with latest Dagster version. Also, we allow references in the", "return super(DagsterDockerImage, cls).__new__( cls, check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path,", "image's path. Defaults to docker/images/<IMAGE NAME> \"\"\" def __new__(cls, image,", "import ecr_image, get_aws_account_id, get_aws_region from .utils import ( execute_docker_build, execute_docker_push,", "tag) def aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates the AWS ECR image", "context manager for build (e.g. for populating a build cache)", "python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def aws_image(self, python_version=None, custom_tag=None):", "__new__(cls, image, build_cm=do_nothing, path=None): return super(DagsterDockerImage, cls).__new__( cls, check.str_param(image, \"image\"),", "= yaml.safe_load(f.read()) image_info = versions.get(python_version, {}) docker_args = image_info.get(\"docker_args\", {})", "python_version=None, custom_tag=None): \"\"\"Generates the AWS ECR image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\"", "with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as f: yaml.dump(last_updated, f, default_flow_style=False) def", "from .utils import ( execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag, ) #", "else: tag = custom_tag return ecr_image( self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(),", "as a base image. If defined, set the BASE_IMAGE Docker", "image to use as a base image. If defined, set", "Location of the template assets used here IMAGES_PATH = os.path.join(os.path.dirname(__file__),", "_get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the last_updated timestamp for a particular python_version", "self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, ) def push(self, python_version,", "contextlib import os from collections import namedtuple import yaml from", "python_version, custom_tag=None): \"\"\"Push this image to ECR.\"\"\" if custom_tag: execute_docker_tag(", "last_updated = {} last_updated_path = os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path): with", "supported for this image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f:", "def _get_docker_args(self, python_version): \"\"\"Retrieve Docker arguments from this image's versions.yaml,", "list(versions.keys()) def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the last_updated timestamp for a", "yaml.safe_load(f.read()) last_updated[python_version] = timestamp with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as f:", "\"images\") @contextlib.contextmanager def do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")):", "Dagster version. Also, we allow references in the image versions.yaml", "\"last_updated.yaml\") if os.path.exists(last_updated_path): with open(last_updated_path, \"r\") as f: last_updated =", "does not match provided arg ({})\".format( current_dagster_version, dagster_version ), )", "repository prefix used for local images DEFAULT_LOCAL_PREFIX = \"dagster\" #", "version ({}) does not match provided arg ({})\".format( current_dagster_version, dagster_version", "dagster import check from .ecr import ecr_image, get_aws_account_id, get_aws_region from", "elif source == \"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else: raise Exception(\"Unrecognized", "path\")): \"\"\"Represents a Dagster image. Properties: image (str): Name of", "the BASE_IMAGE Docker arg from the full name of the", "\"\"\" def __new__(cls, image, build_cm=do_nothing, path=None): return super(DagsterDockerImage, cls).__new__( cls,", "import contextlib import os from collections import namedtuple import yaml", "check.invariant(not (python_version and custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if python_version:", "\"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as f: last_updated = yaml.safe_load(f.read())", "current_dagster_version, desc=\"Current dagster version ({}) does not match provided arg", "If defined, set the BASE_IMAGE Docker arg from the full", "from the full name of the parent image. \"\"\" with", "source == \"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif source == \"local\":", "we allow references in the image versions.yaml to another Dagster", "{}) if \"base_image\" in image_info: check.invariant( \"BASE_IMAGE\" not in docker_args,", "source {}\".format(source)) # Set Dagster version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return", "\"r\") as f: versions = yaml.safe_load(f.read()) return list(versions.keys()) def _get_last_updated_for_python_version(self,", "as current_dagster_version from dagster import check from .ecr import ecr_image,", "IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\",", "image) ), ) @property def python_versions(self): \"\"\"List of Python versions", "\"\"\"Update the last_updated timestamp for a particular python_version of this", "== \"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif source == \"local\": docker_args[\"BASE_IMAGE\"]", "base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"] if source == \"aws\":", "\"python_version\") last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX,", "= DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"] if source == \"aws\": docker_args[\"BASE_IMAGE\"]", "= {} last_updated_path = os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path): with open(last_updated_path,", "\"\"\"Push this image to ECR.\"\"\" if custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None,", "), ) @property def python_versions(self): \"\"\"List of Python versions supported", "build_cm path\")): \"\"\"Represents a Dagster image. Properties: image (str): Name", "BASE_IMAGE\" ) base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"] if source", ") # Default repository prefix used for local images DEFAULT_LOCAL_PREFIX", "execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag, ) # Default repository prefix used", "use as a base image. If defined, set the BASE_IMAGE", "timestamp, dagster_version, python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") check.invariant( dagster_version ==", "os from collections import namedtuple import yaml from dagster import", "with open(last_updated_path, \"r\") as f: last_updated = yaml.safe_load(f.read()) last_updated[python_version] =", "yaml.safe_load(f.read()) return last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update the last_updated", "docker_args = image_info.get(\"docker_args\", {}) if \"base_image\" in image_info: check.invariant( \"BASE_IMAGE\"", "current_dagster_version from dagster import check from .ecr import ecr_image, get_aws_account_id,", "tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def _get_docker_args(self, python_version): \"\"\"Retrieve Docker arguments", "last_updated[python_version] = timestamp with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as f: yaml.dump(last_updated,", "cwd=self.path, ) def push(self, python_version, custom_tag=None): \"\"\"Push this image to", "yaml from dagster import __version__ as current_dagster_version from dagster import", "open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read()) image_info =", "\"python_version\") check.invariant( dagster_version == current_dagster_version, desc=\"Current dagster version ({}) does", "as f: last_updated = yaml.safe_load(f.read()) return last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp,", "image. \"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions =", "of this image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") last_updated = {}", "yaml.safe_load(f.read()) return list(versions.keys()) def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the last_updated timestamp", "= current_dagster_version return docker_args def build(self, timestamp, dagster_version, python_version): check.str_param(timestamp,", "python_version of this image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") last_updated =", "to docker/images/<IMAGE NAME> \"\"\" def __new__(cls, image, build_cm=do_nothing, path=None): return", "== current_dagster_version, desc=\"Current dagster version ({}) does not match provided", "image_info = versions.get(python_version, {}) docker_args = image_info.get(\"docker_args\", {}) if \"base_image\"", "custom_tag=None): \"\"\"Generates the AWS ECR image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\"", "with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read()) image_info", "check.str_param(python_version, \"python_version\") last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) return", "a Dagster image. Properties: image (str): Name of the image", "\"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates the AWS", "with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read()) return", "the image's path. Defaults to docker/images/<IMAGE NAME> \"\"\" def __new__(cls,", "local_image(self, python_version): \"\"\"Generates the local image name, like: \"dagster/foo:some-tag\" \"\"\"", "def push(self, python_version, custom_tag=None): \"\"\"Push this image to ECR.\"\"\" if", "allow references in the image versions.yaml to another Dagster image", ") with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, )", "base image. If defined, set the BASE_IMAGE Docker arg from", "self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, ) def push(self, python_version, custom_tag=None): \"\"\"Push this", "path=None): return super(DagsterDockerImage, cls).__new__( cls, check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param(", "DEFAULT_LOCAL_PREFIX = \"dagster\" # Location of the template assets used", "last_updated = yaml.safe_load(f.read()) return last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update", "super(DagsterDockerImage, cls).__new__( cls, check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path, \"path\",", "check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") check.invariant( dagster_version == current_dagster_version, desc=\"Current dagster", "path (Optional(str)): The path to the image's path. Defaults to", "of this image.\"\"\" check.str_param(python_version, \"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as", "Dagster image to use as a base image. If defined,", "python_version): \"\"\"Generates the local image name, like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version,", "like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\") last_updated = self._get_last_updated_for_python_version(python_version) tag =", "self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def _get_docker_args(self, python_version): \"\"\"Retrieve Docker", "), ) with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path,", "\"\"\" check.str_param(python_version, \"python_version\") last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated)", "as f: versions = yaml.safe_load(f.read()) return list(versions.keys()) def _get_last_updated_for_python_version(self, python_version):", "def python_versions(self): \"\"\"List of Python versions supported for this image.\"\"\"", "arg from the full name of the parent image. \"\"\"", "NAME> \"\"\" def __new__(cls, image, build_cm=do_nothing, path=None): return super(DagsterDockerImage, cls).__new__(", "@contextlib.contextmanager def do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")): \"\"\"Represents", "\"w\") as f: yaml.dump(last_updated, f, default_flow_style=False) def local_image(self, python_version): \"\"\"Generates", "\"\"\"List of Python versions supported for this image.\"\"\" with open(os.path.join(self.path,", "to use as a base image. If defined, set the", "image. Properties: image (str): Name of the image build_cm (function):", "from .ecr import ecr_image, get_aws_account_id, get_aws_region from .utils import (", "for populating a build cache) path (Optional(str)): The path to", "f: versions = yaml.safe_load(f.read()) return list(versions.keys()) def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve", "for a particular python_version of this image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version,", "python_version): \"\"\"Update the last_updated timestamp for a particular python_version of", "Dagster image. Properties: image (str): Name of the image build_cm", "image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read())", "( execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag, ) # Default repository prefix", "check.str_param(python_version, \"python_version\") check.invariant( dagster_version == current_dagster_version, desc=\"Current dagster version ({})", "with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as f: last_updated = yaml.safe_load(f.read()) return", "cache) path (Optional(str)): The path to the image's path. Defaults", "from dagster import __version__ as current_dagster_version from dagster import check", "dagster import __version__ as current_dagster_version from dagster import check from", "function that is a context manager for build (e.g. for", "versions.yaml to another Dagster image to use as a base", "an existing BASE_IMAGE\" ) base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source = image_info[\"base_image\"][\"source\"]", "# Location of the template assets used here IMAGES_PATH =", "return docker_args def build(self, timestamp, dagster_version, python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version,", "The path to the image's path. Defaults to docker/images/<IMAGE NAME>", "custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), ) execute_docker_push(self.aws_image(python_version=None, custom_tag=custom_tag)) else: execute_docker_tag(self.local_image(python_version),", "import __version__ as current_dagster_version from dagster import check from .ecr", "DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")): \"\"\"Represents a Dagster image. Properties: image", "\"r\") as f: versions = yaml.safe_load(f.read()) image_info = versions.get(python_version, {})", "from collections import namedtuple import yaml from dagster import __version__", "ECR.\"\"\" if custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), ) execute_docker_push(self.aws_image(python_version=None, custom_tag=custom_tag))", "_get_docker_args(self, python_version): \"\"\"Retrieve Docker arguments from this image's versions.yaml, and", "the local image name, like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\") last_updated", "name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version and custom_tag)) check.opt_str_param(python_version, \"python_version\")", "image (str): Name of the image build_cm (function): function that", "\"\"\"Generates the local image name, like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\")", "the full name of the parent image. \"\"\" with open(os.path.join(self.path,", "\"\"\"Retrieve Docker arguments from this image's versions.yaml, and update with", "to another Dagster image to use as a base image.", "defined, set the BASE_IMAGE Docker arg from the full name", "open(os.path.join(self.path, \"last_updated.yaml\"), \"r\") as f: last_updated = yaml.safe_load(f.read()) return last_updated[python_version]", "import check from .ecr import ecr_image, get_aws_account_id, get_aws_region from .utils", "timestamp with open(os.path.join(self.path, \"last_updated.yaml\"), \"w\") as f: yaml.dump(last_updated, f, default_flow_style=False)", "(Optional(str)): The path to the image's path. Defaults to docker/images/<IMAGE", "def __new__(cls, image, build_cm=do_nothing, path=None): return super(DagsterDockerImage, cls).__new__( cls, check.str_param(image,", "open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions = yaml.safe_load(f.read()) return list(versions.keys())", "this image's versions.yaml, and update with latest Dagster version. Also,", "Exception(\"Unrecognized source {}\".format(source)) # Set Dagster version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version", "desc=\"Current dagster version ({}) does not match provided arg ({})\".format(", "image_info: check.invariant( \"BASE_IMAGE\" not in docker_args, \"Cannot override an existing", "check.str_param(python_version, \"python_version\") last_updated = {} last_updated_path = os.path.join(self.path, \"last_updated.yaml\") if", "\"base_image\" in image_info: check.invariant( \"BASE_IMAGE\" not in docker_args, \"Cannot override", "self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), ) execute_docker_push(self.aws_image(python_version=None, custom_tag=custom_tag)) else: execute_docker_tag(self.local_image(python_version), self.aws_image(python_version)) execute_docker_push(self.aws_image(python_version))", "self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) else: tag = custom_tag return", "aws_region=get_aws_region(), ) def _get_docker_args(self, python_version): \"\"\"Retrieve Docker arguments from this", "get_aws_account_id, get_aws_region from .utils import ( execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag,", "build cache) path (Optional(str)): The path to the image's path.", "custom_tag=None): \"\"\"Push this image to ECR.\"\"\" if custom_tag: execute_docker_tag( self.local_image(python_version),", "{}\".format(source)) # Set Dagster version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return docker_args", "\"Cannot override an existing BASE_IMAGE\" ) base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source", "used for local images DEFAULT_LOCAL_PREFIX = \"dagster\" # Location of", "Docker arguments from this image's versions.yaml, and update with latest", "path. Defaults to docker/images/<IMAGE NAME> \"\"\" def __new__(cls, image, build_cm=do_nothing,", "ECR image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version and custom_tag))", "self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, ) def push(self,", "check from .ecr import ecr_image, get_aws_account_id, get_aws_region from .utils import", "aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def _get_docker_args(self, python_version): \"\"\"Retrieve Docker arguments from", "return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates the", "images DEFAULT_LOCAL_PREFIX = \"dagster\" # Location of the template assets", "check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image) ), )", "arg ({})\".format( current_dagster_version, dagster_version ), ) with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version)", "image versions.yaml to another Dagster image to use as a", "timestamp, python_version): \"\"\"Update the last_updated timestamp for a particular python_version", "= image_info[\"base_image\"][\"source\"] if source == \"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif", "def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the last_updated timestamp for a particular", "the parent image. \"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f:", "not in docker_args, \"Cannot override an existing BASE_IMAGE\" ) base_image", "image_info[\"base_image\"][\"source\"] if source == \"aws\": docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif source", "execute_docker_build( self.local_image(python_version), docker_args=self._get_docker_args(python_version), cwd=self.path, ) def push(self, python_version, custom_tag=None): \"\"\"Push", "= python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def aws_image(self, python_version=None,", "= custom_tag return ecr_image( self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def", "for build (e.g. for populating a build cache) path (Optional(str)):", "= versions.get(python_version, {}) docker_args = image_info.get(\"docker_args\", {}) if \"base_image\" in", "particular python_version of this image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") last_updated", "from this image's versions.yaml, and update with latest Dagster version.", "last_updated_path = os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path): with open(last_updated_path, \"r\") as", "local images DEFAULT_LOCAL_PREFIX = \"dagster\" # Location of the template", "def do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")): \"\"\"Represents a", "another Dagster image to use as a base image. If", "arguments from this image's versions.yaml, and update with latest Dagster", "versions = yaml.safe_load(f.read()) return list(versions.keys()) def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the", "in image_info: check.invariant( \"BASE_IMAGE\" not in docker_args, \"Cannot override an", ".utils import ( execute_docker_build, execute_docker_push, execute_docker_tag, python_version_image_tag, ) # Default", "@property def python_versions(self): \"\"\"List of Python versions supported for this", "if custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag), ) execute_docker_push(self.aws_image(python_version=None, custom_tag=custom_tag)) else:", "versions.yaml, and update with latest Dagster version. Also, we allow", "= self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) else: tag = custom_tag", "current_dagster_version return docker_args def build(self, timestamp, dagster_version, python_version): check.str_param(timestamp, \"timestamp\")", "= python_version_image_tag(python_version, last_updated) else: tag = custom_tag return ecr_image( self.image,", "a build cache) path (Optional(str)): The path to the image's", "current_dagster_version, dagster_version ), ) with self.build_cm(self.path): self._set_last_updated_for_python_version(timestamp, python_version) execute_docker_build( self.local_image(python_version),", "return last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update the last_updated timestamp", "import yaml from dagster import __version__ as current_dagster_version from dagster", "aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates the AWS ECR image name, like:", "\"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if python_version: last_updated = self._get_last_updated_for_python_version(python_version) tag =", "f: yaml.dump(last_updated, f, default_flow_style=False) def local_image(self, python_version): \"\"\"Generates the local", "Dagster version docker_args[\"DAGSTER_VERSION\"] = current_dagster_version return docker_args def build(self, timestamp,", "python_version_image_tag, ) # Default repository prefix used for local images", "self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) return \"{}/{}:{}\".format(DEFAULT_LOCAL_PREFIX, self.image, tag) def", "python_version: last_updated = self._get_last_updated_for_python_version(python_version) tag = python_version_image_tag(python_version, last_updated) else: tag", "\"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version and custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\")", "\"r\") as f: last_updated = yaml.safe_load(f.read()) last_updated[python_version] = timestamp with", "default_flow_style=False) def local_image(self, python_version): \"\"\"Generates the local image name, like:", "this image to ECR.\"\"\" if custom_tag: execute_docker_tag( self.local_image(python_version), self.aws_image(python_version=None, custom_tag=custom_tag),", "yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")): \"\"\"Represents a Dagster image.", "= os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image", "execute_docker_push, execute_docker_tag, python_version_image_tag, ) # Default repository prefix used for", "match provided arg ({})\".format( current_dagster_version, dagster_version ), ) with self.build_cm(self.path):", "= base_image.local_image(python_version) else: raise Exception(\"Unrecognized source {}\".format(source)) # Set Dagster", "dagster_version, python_version): check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") check.invariant( dagster_version == current_dagster_version,", "self.image, tag) def aws_image(self, python_version=None, custom_tag=None): \"\"\"Generates the AWS ECR", "the AWS ECR image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version", "a context manager for build (e.g. for populating a build", "populating a build cache) path (Optional(str)): The path to the", "versions supported for this image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as", "do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm path\")): \"\"\"Represents a Dagster", "\"r\") as f: last_updated = yaml.safe_load(f.read()) return last_updated[python_version] def _set_last_updated_for_python_version(self,", "Name of the image build_cm (function): function that is a", "python_version of this image.\"\"\" check.str_param(python_version, \"python_version\") with open(os.path.join(self.path, \"last_updated.yaml\"), \"r\")", "name, like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\") last_updated = self._get_last_updated_for_python_version(python_version) tag", "\"\"\"Generates the AWS ECR image name, like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not", "is a context manager for build (e.g. for populating a", "source == \"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else: raise Exception(\"Unrecognized source", "docker_args[\"BASE_IMAGE\"] = base_image.aws_image(python_version) elif source == \"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version)", "\"path\", default=os.path.join(os.path.dirname(__file__), \"images\", image) ), ) @property def python_versions(self): \"\"\"List", "image name, like: \"dagster/foo:some-tag\" \"\"\" check.str_param(python_version, \"python_version\") last_updated = self._get_last_updated_for_python_version(python_version)", "os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager def do_nothing(_cwd): yield class DagsterDockerImage(namedtuple(\"_DagsterDockerImage\", \"image build_cm", "if \"base_image\" in image_info: check.invariant( \"BASE_IMAGE\" not in docker_args, \"Cannot", "\"\"\" check.invariant(not (python_version and custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if", "python_versions(self): \"\"\"List of Python versions supported for this image.\"\"\" with", "image.\"\"\" check.str_param(timestamp, \"timestamp\") check.str_param(python_version, \"python_version\") last_updated = {} last_updated_path =", "that is a context manager for build (e.g. for populating", "f, default_flow_style=False) def local_image(self, python_version): \"\"\"Generates the local image name,", "image_info.get(\"docker_args\", {}) if \"base_image\" in image_info: check.invariant( \"BASE_IMAGE\" not in", "= yaml.safe_load(f.read()) return list(versions.keys()) def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the last_updated", "python_version): \"\"\"Retrieve Docker arguments from this image's versions.yaml, and update", "docker/images/<IMAGE NAME> \"\"\" def __new__(cls, image, build_cm=do_nothing, path=None): return super(DagsterDockerImage,", "cls).__new__( cls, check.str_param(image, \"image\"), check.callable_param(build_cm, \"build_cm\"), check.opt_str_param( path, \"path\", default=os.path.join(os.path.dirname(__file__),", "collections import namedtuple import yaml from dagster import __version__ as", "Python versions supported for this image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\")", "this image.\"\"\" with open(os.path.join(self.path, \"versions.yaml\"), \"r\") as f: versions =", "of the template assets used here IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\")", "push(self, python_version, custom_tag=None): \"\"\"Push this image to ECR.\"\"\" if custom_tag:", "last_updated) else: tag = custom_tag return ecr_image( self.image, tag, aws_account_id=get_aws_account_id(),", "= yaml.safe_load(f.read()) return last_updated[python_version] def _set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update the", "open(last_updated_path, \"r\") as f: last_updated = yaml.safe_load(f.read()) last_updated[python_version] = timestamp", "\"local\": docker_args[\"BASE_IMAGE\"] = base_image.local_image(python_version) else: raise Exception(\"Unrecognized source {}\".format(source)) #", "{} last_updated_path = os.path.join(self.path, \"last_updated.yaml\") if os.path.exists(last_updated_path): with open(last_updated_path, \"r\")", "Docker arg from the full name of the parent image.", "ecr_image( self.image, tag, aws_account_id=get_aws_account_id(), aws_region=get_aws_region(), ) def _get_docker_args(self, python_version): \"\"\"Retrieve", "override an existing BASE_IMAGE\" ) base_image = DagsterDockerImage(image_info[\"base_image\"][\"name\"]) source =", "the template assets used here IMAGES_PATH = os.path.join(os.path.dirname(__file__), \"images\") @contextlib.contextmanager", "(python_version and custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag, \"custom_tag\") if python_version: last_updated", "tag = python_version_image_tag(python_version, last_updated) else: tag = custom_tag return ecr_image(", "def _set_last_updated_for_python_version(self, timestamp, python_version): \"\"\"Update the last_updated timestamp for a", "not match provided arg ({})\".format( current_dagster_version, dagster_version ), ) with", "timestamp for a particular python_version of this image.\"\"\" check.str_param(timestamp, \"timestamp\")", "return list(versions.keys()) def _get_last_updated_for_python_version(self, python_version): \"\"\"Retrieve the last_updated timestamp for", "os.path.exists(last_updated_path): with open(last_updated_path, \"r\") as f: last_updated = yaml.safe_load(f.read()) last_updated[python_version]", "like: \"1234567890.dkr.ecr.us-west-1.amazonaws.com/foo:some-tag\" \"\"\" check.invariant(not (python_version and custom_tag)) check.opt_str_param(python_version, \"python_version\") check.opt_str_param(custom_tag,", "\"images\", image) ), ) @property def python_versions(self): \"\"\"List of Python" ]
[ "return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript(", "def _AttemptUnlockBadPassword(self, browser): logging.info('Trying a bad password') def ErrorBubbleVisible(): return", "== 'es': return 'es-419' if lang == 'zh': if region", "in ('hk', 'mo'): return 'zh-TW' return 'zh-CN' if lang ==", "= auto_login b = browser_to_create.Create() b.Start() return b def _GetAutotestExtension(self,", "'en-CA', _KML.ISO, 'Canada (hybrid)', ('Canada with hybrid xkb:ca:eng:eng + xkb:ca::fra", "extension instance\"\"\" extension = browser.extensions[self._load_extension] self.assertTrue(extension) return extension def _GetLoginStatus(self,", "'--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self, browser, selectId, value): hasOptionJs =", "as b: extension = self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException):", "the locale matches a language but not the country, fall", "'\"%s\"=\"%s\"' % (key, value)]) # Remove cached files to clear", "'defaulting to English language and keyboard. Used only if there", "_KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics', ('Unified SKU", "for regular and guest user and when logged out\"\"\" with", "not languageFound: fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select', fallback))", "self._IsCryptohomeMounted(), 20) def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui']) # Change VPD", "language and keyboard. Used only if there ' 'needs to", "'Canadian French SKUs. See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO,", "'za'): return 'en-GB' return 'en-US' # No mapping found return", "self._username = '' if self._is_guest else options.browser_options.username self._password = options.browser_options.password", "Region(object): def __init__(self, region_code, keyboard, time_zone, language_code, keyboard_mechanical_layout, description=None, notes=None):", "is governed by a BSD-style license that can be #", "cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts']", "and initial_timezone are not set. vpd = {'initial_locale': region.language_code, 'keyboard_layout':", "'ui']) def _OobeHasOption(self, browser, selectId, value): hasOptionJs = ''' //", "settings. self._SwitchRegion(initial_region) # The Region class and region list will", "notes class Enum(frozenset): def __getattr__(self, name): if name in self:", "xkb:ca:eng:eng + xkb:ca::fra keyboard (ISO), ' 'defaulting to English language", "SKUs for Nordic countries (Sweden, \" \"Norway, and Denmark), or", "Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (multilingual)', (\"Canadian Multilingual keyboard;", "'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO,", "self.region_code = region_code self.keyboard = keyboard self.time_zone = time_zone self.language_code", "localized country if lang == 'es' and region == 'es':", "(French keyboard)', ('Canadian French (ISO) keyboard. The most common configuration", "'en-GB', _KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'), Region('my',", "this if there separate SKUs for Nordic countries (Sweden, \"", "('Canadian French (ISO) keyboard. The most common configuration for '", "self.description = description or region_code self.notes = notes class Enum(frozenset):", "single SKU for all of Canada. See ' 'http://goto/cros-canada')), Region('ca.multix',", "class Enum(frozenset): def __getattr__(self, name): if name in self: return", "= browser_to_create.Create() b.Start() return b def _GetAutotestExtension(self, browser): \"\"\"Returns the", "'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests", "for Sweden, Norway, and Denmark. This defaults ' 'to Swedish", "= Enum(['ANSI', 'ISO', 'JIS', 'ABNT2']) _KML = KeyboardMechanicalLayout REGIONS_LIST =", "'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (French keyboard)', ('Canadian French (ISO)", "'es' and region == 'es': return 'es-419' if lang ==", "\"\"\"Returns True if cryptohome is mounted\"\"\" cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome',", "for region in self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as browser: #", "json import logging import os import unittest from telemetry.core import", "{ var options = document.getElementById(selectId).options; for (var i = 0;", "_KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI, 'Canada (US keyboard)',", "= cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest = options.browser_type == 'cros-chrome-guest' self._username =", "return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds and", "_IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension =", "= self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();')", "def _OobeHasOption(self, browser, selectId, value): hasOptionJs = ''' // Check", "lang, _, region = map(str.lower, locale.partition('-')) if not region: return", "'zh-TW' return 'zh-CN' if lang == 'en': if region in", "'keyboard-select', region.keyboard)) # Test is finished. Restore original region settings.", "AttributeError KeyboardMechanicalLayout = Enum(['ANSI', 'ISO', 'JIS', 'ABNT2']) _KML = KeyboardMechanicalLayout", "= self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select', fallback)) # Find the", "self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\"", "cryptohomeStatus = json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False,", "if (options[i].value == value) { // The option is present.", "// The option is present. Make sure it's selected if", "locale): # If the locale matches a language but not", "initial_region.keyboard, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout']) for region in", "'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur',", "map(str.lower, locale.partition('-')) if not region: return \"\" # Map from", "'', '', '') initial_region.language_code, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale'])", "language ' 'for neutrality. Use if there is a single", "tests. if autotest_ext is True, also loads the autotest extension\"\"\"", "'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI, 'Canada", "that the option is present, and selected if it is", "code is governed by a BSD-style license that can be", "browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self,", "region.language_code, 'keyboard_layout': region.keyboard} for (key, value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s',", "'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO,", "value, 'true')) def _ResolveLanguage(self, locale): # If the locale matches", "self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as", "necessary. return !isDefault || options.selectedIndex == i; } } return", "i++) { if (options[i].value == value) { // The option", "self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else: home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path',", "other countries to a localized country if lang == 'es'", "'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (French keyboard)', ('Canadian French (ISO) keyboard.", "return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); '''", "OOBE\"\"\" # Save the original device localization settings. # To", "self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard)) # Test is finished. Restore original", "force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start',", "region_code self.notes = notes class Enum(frozenset): def __getattr__(self, name): if", "(hybrid)', ('Canada with hybrid xkb:ca:eng:eng + xkb:ca::fra keyboard (ISO), '", "To save time, region and initial_timezone are not set. vpd", "self.time_zone = time_zone self.language_code = language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description", "governed by a BSD-style license that can be # found", "be a single SKU for all of Canada. See '", "if region in ('au', 'ca', 'nz', 'za'): return 'en-GB' return", "Use of this source code is governed by a BSD-style", "with self._CreateBrowser(autotest_ext=True) as b: login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not", "for Nordic countries (Sweden, \" \"Norway, and Denmark), or the", "# Change VPD (requires RW-enabled firmware). # To save time,", "_KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng', 'America/Los_Angeles', 'en-US', _KML.ANSI, 'United States'), ]", "!= 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status =", "countries (Sweden, \" \"Norway, and Denmark), or the device is", "browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\") and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting == 'function'\"))", "'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI, 'Canada (US keyboard)', 'Canada with US", "self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda: not self._IsCryptohomeMounted(),", "vpd = {'initial_locale': region.language_code, 'keyboard_layout': region.keyboard} for (key, value) in", "if necessary. return !isDefault || options.selectedIndex == i; } }", "return \"\" def testOobeLocalization(self): \"\"\"Tests different region configurations at OOBE\"\"\"", "if there separate SKUs for Nordic countries (Sweden, \" \"Norway,", "in self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as browser: # Ensure the", "self.notes = notes class Enum(frozenset): def __getattr__(self, name): if name", "\"Norway, and Denmark), or the device is only shipping to", "Find the language, or an acceptable fallback value. languageFound =", "10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); '''", "can be # found in the LICENSE file. import json", "self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest = options.browser_type == 'cros-chrome-guest' self._username", "also loads the autotest extension\"\"\" options = options_for_unittests.GetCopy() if autotest_ext:", "regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui'])", "US English language ' 'for neutrality. Use if there is", "there separate SKUs for Nordic countries (Sweden, \" \"Norway, and", "value)]) # Remove cached files to clear initial locale info", "if region in ('hk', 'mo'): return 'zh-TW' return 'zh-CN' if", "if there ' 'needs to be a single SKU for", "'-g', 'initial_locale']) initial_region.keyboard, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout']) for", "'guestfs') else: home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs)", "autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self):", "self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as b:", "'cros-chrome-guest' self._username = '' if self._is_guest else options.browser_options.username self._password =", "_OobeHasOption(self, browser, selectId, value): hasOptionJs = ''' // Check that", "the default. (function hasOption(selectId, value, isDefault) { var options =", "util from telemetry.core.backends.chrome import cros_interface from telemetry.unittest import options_for_unittests class", "\" \"If there is a single unified SKU, use 'nordic'", "is_component=True) options.extensions_to_load = [self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe =", "b: extension = self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass", "extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status =", "value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' % (key, value)]) #", "region_code self.keyboard = keyboard self.time_zone = time_zone self.language_code = language_code", "Oobe.authenticateForTesting('%s', '%s'); ''' % (self._username, self._password)) util.WaitFor(lambda: not browser.oobe, 10)", "if not languageFound: fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select',", "a single SKU for all of Canada. See ' 'http://goto/cros-canada')),", "French SKUs. See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO, 'Canada", "extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20) def", "value. languageFound = self._OobeHasOption(browser, 'language-select', region.language_code) if not languageFound: fallback", "\"\"\"Finds and creates a browser for tests. if autotest_ext is", "languageFound: fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select', fallback)) #", "'Canada with US (ANSI) keyboard; see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto',", "return !isDefault || options.selectedIndex == i; } } return false;", "locale. See ui/base/l10n/l10n_util.cc. lang, _, region = map(str.lower, locale.partition('-')) if", "a bad password') def ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''')", "a localized country if lang == 'es' and region ==", "if lang == 'es' and region == 'es': return 'es-419'", "options = options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest = options.browser_type", "mounted\"\"\" cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON) return", "class Region(object): def __init__(self, region_code, keyboard, time_zone, language_code, keyboard_mechanical_layout, description=None,", "value) { // The option is present. Make sure it's", "== 'zh': if region in ('hk', 'mo'): return 'zh-TW' return", "_KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'), Region('my', 'xkb:us::eng',", "not self._IsCryptohomeMounted(), 20) def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui']) # Change", "testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as b: extension = self._GetAutotestExtension(b)", "(key, value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' % (key, value)])", "'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI, 'Canada (US", "'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'),", "Map from other countries to a localized country if lang", "SKU for Sweden, Norway, and Denmark. This defaults ' 'to", "b def _GetAutotestExtension(self, browser): \"\"\"Returns the autotest extension instance\"\"\" extension", "single unified SKU, use 'nordic' instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB',", "cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest = options.browser_type == 'cros-chrome-guest' self._username = ''", "rights reserved. # Use of this source code is governed", "for the lock screen') def ScreenLocked(): return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof", "i < options.length; i++) { if (options[i].value == value) {", "and keyboard. Used only if there ' 'needs to be", "import os import unittest from telemetry.core import browser_finder from telemetry.core", "the country, fall back to # an existing locale. See", "browser, 'keyboard-select', region.keyboard)) # Test is finished. Restore original region", "for (key, value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' % (key,", "chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the lock", "self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof", "value, isDefault) { var options = document.getElementById(selectId).options; for (var i", "language but not the country, fall back to # an", "from telemetry.core import exceptions from telemetry.core import extension_to_load from telemetry.core", "read initial_locale and keyboard_layout. initial_region = self.Region('', '', '', '',", "for ' 'Canadian French SKUs. See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto',", "def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui']) # Change VPD (requires RW-enabled", "extension\"\"\" options = options_for_unittests.GetCopy() if autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext')", "return 'zh-TW' return 'zh-CN' if lang == 'en': if region", "self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s)", "telemetry.core import util from telemetry.core.backends.chrome import cros_interface from telemetry.unittest import", "_ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and", "''') return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self): \"\"\"Verifies cryptohome", "' 'to Swedish keyboard layout, but starts with US English", "English language ' 'for neutrality. Use if there is a", "Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms',", "(function hasOption(selectId, value, isDefault) { var options = document.getElementById(selectId).options; for", "= self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else: home, _", "browser): self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen == 'function'\"))", "region == 'es': return 'es-419' if lang == 'zh': if", "language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description = description or region_code self.notes", "hasOptionJs = ''' // Check that the option is present,", "list will be available in regions.py. class Region(object): def __init__(self,", "= region_code self.keyboard = keyboard self.time_zone = time_zone self.language_code =", "in self: return name raise AttributeError KeyboardMechanicalLayout = Enum(['ANSI', 'ISO',", "keyboard)', ('Canadian French (ISO) keyboard. The most common configuration for", "options = document.getElementById(selectId).options; for (var i = 0; i <", "'for neutrality. Use if there is a single combined SKU", "_KML.ISO, 'Canada (hybrid)', ('Canada with hybrid xkb:ca:eng:eng + xkb:ca::fra keyboard", "Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr',", "region = map(str.lower, locale.partition('-')) if not region: return \"\" #", "_CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds and creates a browser for tests.", "Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US',", "login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked'] def", "mapping found return \"\" def testOobeLocalization(self): \"\"\"Tests different region configurations", "dropdown lists have been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'),", "all of Canada. See ' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA',", "most common configuration for ' 'Canadian French SKUs. See http://goto/cros-canada')),", "Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden', (\"Use this if there", "'sv', _KML.ISO, 'Sweden', (\"Use this if there separate SKUs for", "% (selectId, value, 'true')) def _ResolveLanguage(self, locale): # If the", "self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login = auto_login b = browser_to_create.Create()", "from telemetry.core import util from telemetry.core.backends.chrome import cros_interface from telemetry.unittest", "browser): return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser)", "'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm',", "browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); ''' % (self._username, self._password)) util.WaitFor(lambda: not browser.oobe,", "return 'en-GB' return 'en-US' # No mapping found return \"\"", "})(\"%s\", \"%s\", %s); ''' return browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId, value,", "_KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng',", "_KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng',", "'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London',", "return browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId, value, 'true')) def _ResolveLanguage(self, locale):", "self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self, browser, selectId,", "[ Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto',", "(key, value)]) # Remove cached files to clear initial locale", "the language, or an acceptable fallback value. languageFound = self._OobeHasOption(browser,", "% (key, value)]) # Remove cached files to clear initial", "telemetry.unittest import options_for_unittests class CrOSAutoTest(unittest.TestCase): def setUp(self): options = options_for_unittests.GetCopy()", "'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics', ('Unified SKU for", "= True options.browser_options.auto_login = auto_login b = browser_to_create.Create() b.Start() return", "it's selected if necessary. return !isDefault || options.selectedIndex == i;", "\"\"\"Tests different region configurations at OOBE\"\"\" # Save the original", "LICENSE file. import json import logging import os import unittest", "'-g', 'keyboard_layout']) for region in self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as", "browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as", "Oobe == 'function'\") and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked,", "_KML.ANSI, 'Canada (US keyboard)', 'Canada with US (ANSI) keyboard; see", "self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout']) for region in self.REGIONS_LIST: self._SwitchRegion(region) with", "license that can be # found in the LICENSE file.", "self._OobeHasOption(browser, 'language-select', region.language_code) if not languageFound: fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback", "_ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful')", "SKU, use 'nordic' instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'),", "login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest'])", "'%s'); ''' % (self._username, self._password)) util.WaitFor(lambda: not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser))", "from telemetry.core.backends.chrome import cros_interface from telemetry.unittest import options_for_unittests class CrOSAutoTest(unittest.TestCase):", "__init__(self, region_code, keyboard, time_zone, language_code, keyboard_mechanical_layout, description=None, notes=None): self.region_code =", "options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns True if cryptohome is mounted\"\"\" cryptohomeJSON,", "(options[i].value == value) { // The option is present. Make", "keyboard_mechanical_layout, description=None, notes=None): self.region_code = region_code self.keyboard = keyboard self.time_zone", "import browser_finder from telemetry.core import exceptions from telemetry.core import extension_to_load", "# If the locale matches a language but not the", "True if cryptohome is mounted\"\"\" cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status'])", "login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser): return", "BSD-style license that can be # found in the LICENSE", "if lang == 'en': if region in ('au', 'ca', 'nz',", "'ca', 'nz', 'za'): return 'en-GB' return 'en-US' # No mapping", "= [self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login", "# Use of this source code is governed by a", "configurations at OOBE\"\"\" # Save the original device localization settings.", "== 'es' and region == 'es': return 'es-419' if lang", "an acceptable fallback value. languageFound = self._OobeHasOption(browser, 'language-select', region.language_code) if", "'es': return 'es-419' if lang == 'zh': if region in", "= {'initial_locale': region.language_code, 'keyboard_layout': region.keyboard} for (key, value) in vpd.items():", "# an existing locale. See ui/base/l10n/l10n_util.cc. lang, _, region =", "class and region list will be available in regions.py. class", "10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser): logging.info('Trying a bad password') def", "Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng', 'America/Los_Angeles', 'en-US',", "testOobeLocalization(self): \"\"\"Tests different region configurations at OOBE\"\"\" # Save the", "True, also loads the autotest extension\"\"\" options = options_for_unittests.GetCopy() if", "'nordic' instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng',", "(US keyboard)', 'Canada with US (ANSI) keyboard; see http://goto/cros-canada'), Region('ca.fr',", "extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking screen')", "countries to a localized country if lang == 'es' and", "self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load = [self._load_extension] browser_to_create", "options.cros_ssh_identity) self._is_guest = options.browser_type == 'cros-chrome-guest' self._username = '' if", "(c) 2012 The Chromium Authors. All rights reserved. # Use", "initial_locale and keyboard_layout. initial_region = self.Region('', '', '', '', '')", "user and when logged out\"\"\" with self._CreateBrowser() as b: self.assertEquals(1,", "browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId, value, 'true')) def _ResolveLanguage(self, locale): #", "time, region and initial_timezone are not set. vpd = {'initial_locale':", "== i; } } return false; })(\"%s\", \"%s\", %s); '''", "self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale']) initial_region.keyboard, _ = self._cri.RunCmdOnDevice( ['vpd', '-g',", "'initial_locale']) initial_region.keyboard, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout']) for region", "as browser: # Ensure the dropdown lists have been created.", "finished. Restore original region settings. self._SwitchRegion(initial_region) # The Region class", "def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser)", "not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True)", "= time_zone self.language_code = language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description =", "window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status = s; }); ''')", "(\"Canadian Multilingual keyboard; you probably don't want this. See \"", "extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True)", "if name in self: return name raise AttributeError KeyboardMechanicalLayout =", "{'initial_locale': region.language_code, 'keyboard_layout': region.keyboard} for (key, value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd',", "'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO,", "\"\" def testOobeLocalization(self): \"\"\"Tests different region configurations at OOBE\"\"\" #", "self._is_guest = options.browser_type == 'cros-chrome-guest' self._username = '' if self._is_guest", "selected if it is the default. (function hasOption(selectId, value, isDefault)", "null'), 10) # Find the language, or an acceptable fallback", "browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); ''' % self._username)", "_GetAutotestExtension(self, browser): \"\"\"Returns the autotest extension instance\"\"\" extension = browser.extensions[self._load_extension]", "selected if necessary. return !isDefault || options.selectedIndex == i; }", "= ''' // Check that the option is present, and", "or region_code self.notes = notes class Enum(frozenset): def __getattr__(self, name):", "defaults ' 'to Swedish keyboard layout, but starts with US", "# Remove cached files to clear initial locale info and", "original region settings. self._SwitchRegion(initial_region) # The Region class and region", "(\"Use this if there separate SKUs for Nordic countries (Sweden,", "a BSD-style license that can be # found in the", "have been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'), 10) #", "Test is finished. Restore original region settings. self._SwitchRegion(initial_region) # The", "os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load =", "'keyboard_layout': region.keyboard} for (key, value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"'", "!= null'), 10) # Find the language, or an acceptable", "util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser): logging.info('Trying a bad password')", "are not set. vpd = {'initial_locale': region.language_code, 'keyboard_layout': region.keyboard} for", "self.Region('', '', '', '', '') initial_region.language_code, _ = self._cri.RunCmdOnDevice( ['vpd',", "self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); ''' %", "will be available in regions.py. class Region(object): def __init__(self, region_code,", "the device is only shipping to Sweden. \" \"If there", "(ANSI) keyboard; see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada", "initial_region.language_code, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale']) initial_region.keyboard, _ =", "with US (ANSI) keyboard; see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA',", "and Denmark. This defaults ' 'to Swedish keyboard layout, but", "' 'for neutrality. Use if there is a single combined", "''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); ''' % self._username) util.WaitFor(ErrorBubbleVisible, 10)", "# To save time, region and initial_timezone are not set.", "'fr-CA', _KML.ISO, 'Canada (French keyboard)', ('Canadian French (ISO) keyboard. The", "Nordic countries (Sweden, \" \"Norway, and Denmark), or the device", "sure it's selected if necessary. return !isDefault || options.selectedIndex ==", "self._CreateBrowser(autotest_ext=True) as b: login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest,", "telemetry.core import exceptions from telemetry.core import extension_to_load from telemetry.core import", "b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if", "null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status = s; }); ''') return util.WaitFor(", "= keyboard self.time_zone = time_zone self.language_code = language_code self.keyboard_mechanical_layout =", "if autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path,", "self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description = description or region_code self.notes =", "setUp(self): options = options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest =", "if there is a single combined SKU for Nordic '", "extension = self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda:", "for Nordic ' 'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden',", "browser_to_create.Create() b.Start() return b def _GetAutotestExtension(self, browser): \"\"\"Returns the autotest", "self.assertTrue(extension) return extension def _GetLoginStatus(self, browser): extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript(", "with self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests", "value): hasOptionJs = ''' // Check that the option is", "== 'function'\") and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked, 10)", "def ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s',", "Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser): logging.info('Trying", "option is present. Make sure it's selected if necessary. return", "region and initial_timezone are not set. vpd = {'initial_locale': region.language_code,", "self._is_guest else options.browser_options.username self._password = options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns True", "os import unittest from telemetry.core import browser_finder from telemetry.core import", "else: home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted())", "browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); ''' % self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def", "def __getattr__(self, name): if name in self: return name raise", "} return false; })(\"%s\", \"%s\", %s); ''' return browser.oobe.EvaluateJavaScript( hasOptionJs", "'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (multilingual)', (\"Canadian Multilingual keyboard; you probably", "'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris',", "instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng', 'America/Los_Angeles',", "if self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else: home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user',", "localization settings. # To save time, only read initial_locale and", "fallback value. languageFound = self._OobeHasOption(browser, 'language-select', region.language_code) if not languageFound:", "(cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds and creates", "!isDefault || options.selectedIndex == i; } } return false; })(\"%s\",", "= extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load = [self._load_extension] browser_to_create =", "_KML.ISO, 'Nordics', ('Unified SKU for Sweden, Norway, and Denmark. This", "'/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self,", "is present, and selected if it is the default. (function", "'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI, 'Canada (US keyboard)', 'Canada", "this. See \" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO, 'Germany'),", "http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO, 'Canada (hybrid)', ('Canada with", "self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else: home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username])", "only shipping to Sweden. \" \"If there is a single", "self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked'])", "Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (French keyboard)', ('Canadian French", "# Find the language, or an acceptable fallback value. languageFound", "self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' % (key, value)]) # Remove cached files", "_ResolveLanguage(self, locale): # If the locale matches a language but", "only if there ' 'needs to be a single SKU", "(ISO) keyboard. The most common configuration for ' 'Canadian French", "\"typeof Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser):", "(exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20) def _SwitchRegion(self, region):", "Ensure the dropdown lists have been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\")", "self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\"", "lock screen') def ScreenLocked(): return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe ==", "RW-enabled firmware). # To save time, region and initial_timezone are", "' 'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden', (\"Use this", "'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng', 'America/Los_Angeles', 'en-US', _KML.ANSI,", "'Europe/Berlin', 'de', _KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'),", "cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds and creates a browser", "self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser)", "def __init__(self, region_code, keyboard, time_zone, language_code, keyboard_mechanical_layout, description=None, notes=None): self.region_code", "mount status for regular and guest user and when logged", "'Europe/Paris', 'fr', _KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO, 'UK'),", "and guest user and when logged out\"\"\" with self._CreateBrowser() as", "'de', _KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'), Region('fr',", "at OOBE\"\"\" # Save the original device localization settings. #", "'ms', _KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'), Region('nordic',", "unified SKU, use 'nordic' instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI,", "region.language_code) if not languageFound: fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser,", "cryptohome is mounted\"\"\" cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus =", "path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load = [self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create)", "save time, only read initial_locale and keyboard_layout. initial_region = self.Region('',", "_KML = KeyboardMechanicalLayout REGIONS_LIST = [ Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU',", "'true')) def _ResolveLanguage(self, locale): # If the locale matches a", "to Sweden. \" \"If there is a single unified SKU,", "default. (function hasOption(selectId, value, isDefault) { var options = document.getElementById(selectId).options;", "= browser.extensions[self._load_extension] self.assertTrue(extension) return extension def _GetLoginStatus(self, browser): extension =", "and creates a browser for tests. if autotest_ext is True,", "(selectId, value, 'true')) def _ResolveLanguage(self, locale): # If the locale", "to be a single SKU for all of Canada. See", "'Canada (multilingual)', (\"Canadian Multilingual keyboard; you probably don't want this.", "description=None, notes=None): self.region_code = region_code self.keyboard = keyboard self.time_zone =", "single combined SKU for Nordic ' 'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm',", "is True, also loads the autotest extension\"\"\" options = options_for_unittests.GetCopy()", "logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the lock screen') def ScreenLocked():", "= '' if self._is_guest else options.browser_options.username self._password = options.browser_options.password def", "self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else:", "'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO,", "_UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); ''' % (self._username, self._password))", "True options.browser_options.auto_login = auto_login b = browser_to_create.Create() b.Start() return b", "Region class and region list will be available in regions.py.", "'fi', _KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO, 'France'), Region('gb',", "% self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript('''", "file. import json import logging import os import unittest from", "}); ''') return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self): \"\"\"Verifies", "a browser for tests. if autotest_ext is True, also loads", "The Region class and region list will be available in", "ScreenLocked(): return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\") and browser.oobe.EvaluateJavaScript(", "'', '') initial_region.language_code, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale']) initial_region.keyboard,", "// Check that the option is present, and selected if", "hasOption(selectId, value, isDefault) { var options = document.getElementById(selectId).options; for (var", "util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s');", "initial_timezone are not set. vpd = {'initial_locale': region.language_code, 'keyboard_layout': region.keyboard}", "if cryptohome is mounted\"\"\" cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus", "initial_region = self.Region('', '', '', '', '') initial_region.language_code, _ =", "'ui']) # Change VPD (requires RW-enabled firmware). # To save", "and selected if it is the default. (function hasOption(selectId, value,", "self._OobeHasOption(browser, 'language-select', fallback)) # Find the keyboard layout. self.assertTrue(self._OobeHasOption( browser,", "Use if there is a single combined SKU for Nordic", "logging.info('Waiting for the lock screen') def ScreenLocked(): return (browser.oobe and", "this source code is governed by a BSD-style license that", "the autotest extension instance\"\"\" extension = browser.extensions[self._load_extension] self.assertTrue(extension) return extension", "options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login = auto_login b = browser_to_create.Create() b.Start()", "self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with", "'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin',", "is only shipping to Sweden. \" \"If there is a", "not the country, fall back to # an existing locale.", "self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as browser: # Ensure the dropdown", "'zh-CN' if lang == 'en': if region in ('au', 'ca',", "'Europe/London', 'en-GB', _KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'),", "found in the LICENSE file. import json import logging import", "10) # Find the language, or an acceptable fallback value.", "extension = browser.extensions[self._load_extension] self.assertTrue(extension) return extension def _GetLoginStatus(self, browser): extension", "dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def", "shipping to Sweden. \" \"If there is a single unified", "settings. # To save time, only read initial_locale and keyboard_layout.", "# To save time, only read initial_locale and keyboard_layout. initial_region", "'/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as b: login_status", "def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen", "with hybrid xkb:ca:eng:eng + xkb:ca::fra keyboard (ISO), ' 'defaulting to", "telemetry.core import extension_to_load from telemetry.core import util from telemetry.core.backends.chrome import", "cros_interface from telemetry.unittest import options_for_unittests class CrOSAutoTest(unittest.TestCase): def setUp(self): options", "is present. Make sure it's selected if necessary. return !isDefault", "the LICENSE file. import json import logging import os import", "acceptable fallback value. languageFound = self._OobeHasOption(browser, 'language-select', region.language_code) if not", "''' return browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId, value, 'true')) def _ResolveLanguage(self,", "'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI,", "source code is governed by a BSD-style license that can", "import extension_to_load from telemetry.core import util from telemetry.core.backends.chrome import cros_interface", "Authors. All rights reserved. # Use of this source code", "browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True)", "b.Start() return b def _GetAutotestExtension(self, browser): \"\"\"Returns the autotest extension", "device localization settings. # To save time, only read initial_locale", "= document.getElementById(selectId).options; for (var i = 0; i < options.length;", "name raise AttributeError KeyboardMechanicalLayout = Enum(['ANSI', 'ISO', 'JIS', 'ABNT2']) _KML", "probably don't want this. See \" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin',", "self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username)", "English language and keyboard. Used only if there ' 'needs", "combined SKU for Nordic ' 'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv',", "{ // The option is present. Make sure it's selected", "self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest:", "matches a language but not the country, fall back to", "instance\"\"\" extension = browser.extensions[self._load_extension] self.assertTrue(extension) return extension def _GetLoginStatus(self, browser):", "self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s) {", "_KML.ISO, 'Canada (French keyboard)', ('Canadian French (ISO) keyboard. The most", "is finished. Restore original region settings. self._SwitchRegion(initial_region) # The Region", "(multilingual)', (\"Canadian Multilingual keyboard; you probably don't want this. See", "self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s',", "'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO,", "Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA',", "' 'Canadian French SKUs. See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA',", "'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load = [self._load_extension]", "and self._OobeHasOption(browser, 'language-select', fallback)) # Find the keyboard layout. self.assertTrue(self._OobeHasOption(", "= options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns True if cryptohome is mounted\"\"\"", "locale.partition('-')) if not region: return \"\" # Map from other", "available in regions.py. class Region(object): def __init__(self, region_code, keyboard, time_zone,", "'to Swedish keyboard layout, but starts with US English language", "browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login = auto_login b =", "browser for tests. if autotest_ext is True, also loads the", "self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self):", "save time, region and initial_timezone are not set. vpd =", "selectId, value): hasOptionJs = ''' // Check that the option", "def testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount status for regular and guest", "(browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\") and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting", "import exceptions from telemetry.core import extension_to_load from telemetry.core import util", "_KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra',", "autotest_ext=False, auto_login=True): \"\"\"Finds and creates a browser for tests. if", "locale matches a language but not the country, fall back", "or an acceptable fallback value. languageFound = self._OobeHasOption(browser, 'language-select', region.language_code)", "This defaults ' 'to Swedish keyboard layout, but starts with", "'Sweden', (\"Use this if there separate SKUs for Nordic countries", "''' // Check that the option is present, and selected", "import json import logging import os import unittest from telemetry.core", "'Canada (US keyboard)', 'Canada with US (ANSI) keyboard; see http://goto/cros-canada'),", "def _GetLoginStatus(self, browser): extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\"))", "\"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status", "fallback)) # Find the keyboard layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard))", "be available in regions.py. class Region(object): def __init__(self, region_code, keyboard,", "return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\") and browser.oobe.EvaluateJavaScript( \"typeof", "the option is present, and selected if it is the", "'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden', (\"Use this if there separate", "(Sweden, \" \"Norway, and Denmark), or the device is only", "autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as b: login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status), dict)", "'en': if region in ('au', 'ca', 'nz', 'za'): return 'en-GB'", "# Copyright (c) 2012 The Chromium Authors. All rights reserved.", "chrome.autotestPrivate.loginStatus(function(s) { window.__login_status = s; }); ''') return util.WaitFor( lambda:", "Region('ca.ansi', 'xkb:us::eng', 'America/Toronto', 'en-CA', _KML.ANSI, 'Canada (US keyboard)', 'Canada with", "existing locale. See ui/base/l10n/l10n_util.cc. lang, _, region = map(str.lower, locale.partition('-'))", "and browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\") and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting ==", "of this source code is governed by a BSD-style license", "(self._username, self._password)) util.WaitFor(lambda: not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests", "__getattr__(self, name): if name in self: return name raise AttributeError", "layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard)) # Test is finished. Restore", "'/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self, browser, selectId, value):", "= browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login = auto_login b", "self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as", "region in ('hk', 'mo'): return 'zh-TW' return 'zh-CN' if lang", "self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self,", "def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as b: extension =", "keyboard (ISO), ' 'defaulting to English language and keyboard. Used", "lang == 'en': if region in ('au', 'ca', 'nz', 'za'):", "different region configurations at OOBE\"\"\" # Save the original device", "KeyboardMechanicalLayout REGIONS_LIST = [ Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'),", "{ window.__login_status = s; }); ''') return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'),", "reserved. # Use of this source code is governed by", "return name raise AttributeError KeyboardMechanicalLayout = Enum(['ANSI', 'ISO', 'JIS', 'ABNT2'])", "keyboard layout, but starts with US English language ' 'for", "= 0; i < options.length; i++) { if (options[i].value ==", "'document.getElementById(\"language-select\") != null'), 10) # Find the language, or an", "== 'cros-chrome-guest' self._username = '' if self._is_guest else options.browser_options.username self._password", "and when logged out\"\"\" with self._CreateBrowser() as b: self.assertEquals(1, len(b.tabs))", "'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status = s;", "self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self, browser, selectId, value): hasOptionJs = '''", "and region list will be available in regions.py. class Region(object):", "there is a single unified SKU, use 'nordic' instead.\")), Region('sg',", "or the device is only shipping to Sweden. \" \"If", "Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki', 'fi',", "SKUs. See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO, 'Canada (hybrid)',", "def _GetAutotestExtension(self, browser): \"\"\"Returns the autotest extension instance\"\"\" extension =", "browser.extensions[self._load_extension] self.assertTrue(extension) return extension def _GetLoginStatus(self, browser): extension = self._GetAutotestExtension(browser)", "language, or an acceptable fallback value. languageFound = self._OobeHasOption(browser, 'language-select',", "'ABNT2']) _KML = KeyboardMechanicalLayout REGIONS_LIST = [ Region('au', 'xkb:us::eng', 'Australia/Sydney',", "browser_finder from telemetry.core import exceptions from telemetry.core import extension_to_load from", "\"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as b: login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status),", "firmware). # To save time, region and initial_timezone are not", "configuration for ' 'Canadian French SKUs. See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng',", "the original device localization settings. # To save time, only", "'en-GB' return 'en-US' # No mapping found return \"\" def", "is a single combined SKU for Nordic ' 'countries.')), Region('se',", "layout, but starts with US English language ' 'for neutrality.", "KeyboardMechanicalLayout = Enum(['ANSI', 'ISO', 'JIS', 'ABNT2']) _KML = KeyboardMechanicalLayout REGIONS_LIST", "document.getElementById(selectId).options; for (var i = 0; i < options.length; i++)", "except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20) def _SwitchRegion(self,", "not set. vpd = {'initial_locale': region.language_code, 'keyboard_layout': region.keyboard} for (key,", "testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser)", "US (ANSI) keyboard; see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO,", "present, and selected if it is the default. (function hasOption(selectId,", "options_for_unittests class CrOSAutoTest(unittest.TestCase): def setUp(self): options = options_for_unittests.GetCopy() self._cri =", "ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad');", "home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'),", "\"\"\"Verifies cryptohome mount status for regular and guest user and", "\"%s\", %s); ''' return browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId, value, 'true'))", "starts with US English language ' 'for neutrality. Use if", "var options = document.getElementById(selectId).options; for (var i = 0; i", "common configuration for ' 'Canadian French SKUs. See http://goto/cros-canada')), Region('ca.hybrid',", "'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser): logging.info('Trying a bad", "= map(str.lower, locale.partition('-')) if not region: return \"\" # Map", "= description or region_code self.notes = notes class Enum(frozenset): def", "description or region_code self.notes = notes class Enum(frozenset): def __getattr__(self,", "creates a browser for tests. if autotest_ext is True, also", "'keyboard_layout']) for region in self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as browser:", "_LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen ==", "Find the keyboard layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard)) # Test", "you probably don't want this. See \" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger',", "from telemetry.core import browser_finder from telemetry.core import exceptions from telemetry.core", "autotest extension\"\"\" options = options_for_unittests.GetCopy() if autotest_ext: extension_path = os.path.join(os.path.dirname(__file__),", "but not the country, fall back to # an existing", "return false; })(\"%s\", \"%s\", %s); ''' return browser.oobe.EvaluateJavaScript( hasOptionJs %", "files to clear initial locale info and force regeneration. self._cri.RunCmdOnDevice(['rm',", "false; })(\"%s\", \"%s\", %s); ''' return browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId,", "'Nordics', ('Unified SKU for Sweden, Norway, and Denmark. This defaults", "= json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False, auto_login=True):", "bad password') def ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible())", "(var i = 0; i < options.length; i++) { if", "self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else: home, _ =", "raise AttributeError KeyboardMechanicalLayout = Enum(['ANSI', 'ISO', 'JIS', 'ABNT2']) _KML =", "the keyboard layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard)) # Test is", "options.browser_type == 'cros-chrome-guest' self._username = '' if self._is_guest else options.browser_options.username", "Oobe.authenticateForTesting('%s', 'bad'); ''' % self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self,", "Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB',", "self._CreateBrowser(autotest_ext=True) as b: extension = self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException,", "vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' % (key, value)]) # Remove cached", "'America/Toronto', 'en-CA', _KML.ISO, 'Canada (hybrid)', ('Canada with hybrid xkb:ca:eng:eng +", "self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser): logging.info('Trying a bad password') def ErrorBubbleVisible():", "lang == 'es' and region == 'es': return 'es-419' if", "'ISO', 'JIS', 'ABNT2']) _KML = KeyboardMechanicalLayout REGIONS_LIST = [ Region('au',", "region configurations at OOBE\"\"\" # Save the original device localization", "} } return false; })(\"%s\", \"%s\", %s); ''' return browser.oobe.EvaluateJavaScript(", "clear initial locale info and force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State'])", "don't want this. See \" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de',", "Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics', ('Unified SKU for Sweden,", "French (ISO) keyboard. The most common configuration for ' 'Canadian", "i = 0; i < options.length; i++) { if (options[i].value", "= [ Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi', 'xkb:us::eng',", "'es-419' if lang == 'zh': if region in ('hk', 'mo'):", "notes=None): self.region_code = region_code self.keyboard = keyboard self.time_zone = time_zone", "region.keyboard} for (key, value) in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' %", "util.WaitFor(lambda: not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with", "' 'needs to be a single SKU for all of", "json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds", "telemetry.core import browser_finder from telemetry.core import exceptions from telemetry.core import", "if lang == 'zh': if region in ('hk', 'mo'): return", "'nz', 'za'): return 'en-GB' return 'en-US' # No mapping found", "'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (multilingual)', (\"Canadian Multilingual", "'en-GB', _KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng', 'America/Los_Angeles', 'en-US', _KML.ANSI, 'United States'),", "keyboard, time_zone, language_code, keyboard_mechanical_layout, description=None, notes=None): self.region_code = region_code self.keyboard", "self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self, browser, selectId, value): hasOptionJs", "been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'), 10) # Find", "for (var i = 0; i < options.length; i++) {", "self._password = options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns True if cryptohome is", "to English language and keyboard. Used only if there '", "_KML.ISO, 'Canada (multilingual)', (\"Canadian Multilingual keyboard; you probably don't want", "keyboard self.time_zone = time_zone self.language_code = language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout", "a single combined SKU for Nordic ' 'countries.')), Region('se', 'xkb:se::swe',", "# Save the original device localization settings. # To save", "self._CreateBrowser() as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user')", "return \"\" # Map from other countries to a localized", "back to # an existing locale. See ui/base/l10n/l10n_util.cc. lang, _,", "'zh': if region in ('hk', 'mo'): return 'zh-TW' return 'zh-CN'", "the autotest extension\"\"\" options = options_for_unittests.GetCopy() if autotest_ext: extension_path =", "the lock screen') def ScreenLocked(): return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe", "'' if self._is_guest else options.browser_options.username self._password = options.browser_options.password def _IsCryptohomeMounted(self):", "'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics', ('Unified SKU for Sweden, Norway,", "pass util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20) def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui'])", "('hk', 'mo'): return 'zh-TW' return 'zh-CN' if lang == 'en':", "name): if name in self: return name raise AttributeError KeyboardMechanicalLayout", "is a single unified SKU, use 'nordic' instead.\")), Region('sg', 'xkb:us::eng',", "< options.length; i++) { if (options[i].value == value) { //", "['vpd', '-g', 'initial_locale']) initial_region.keyboard, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout'])", "browser): \"\"\"Returns the autotest extension instance\"\"\" extension = browser.extensions[self._load_extension] self.assertTrue(extension)", "name in self: return name raise AttributeError KeyboardMechanicalLayout = Enum(['ANSI',", "keyboard. The most common configuration for ' 'Canadian French SKUs.", "See http://goto/cros-canada')), Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO, 'Canada (hybrid)', ('Canada", "def setUp(self): options = options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest", "class CrOSAutoTest(unittest.TestCase): def setUp(self): options = options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote,", "== value) { // The option is present. Make sure", "_AttemptUnlockBadPassword(self, browser): logging.info('Trying a bad password') def ErrorBubbleVisible(): return not", "logging import os import unittest from telemetry.core import browser_finder from", "# found in the LICENSE file. import json import logging", "= self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda: not", "keyboard_mechanical_layout self.description = description or region_code self.notes = notes class", "chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True)", "in the LICENSE file. import json import logging import os", "extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount status for regular", "password') def ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript('''", "neutrality. Use if there is a single combined SKU for", "testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount status for regular and guest user", "20) def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui']) # Change VPD (requires", "auto_login b = browser_to_create.Create() b.Start() return b def _GetAutotestExtension(self, browser):", "be # found in the LICENSE file. import json import", "def _CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds and creates a browser for", "self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select', fallback)) # Find the keyboard", "self.language_code = language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description = description or", "and keyboard_layout. initial_region = self.Region('', '', '', '', '') initial_region.language_code,", "= self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout']) for region in self.REGIONS_LIST: self._SwitchRegion(region)", "# Ensure the dropdown lists have been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript(", "'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (multilingual)', (\"Canadian Multilingual keyboard; you", "loads the autotest extension\"\"\" options = options_for_unittests.GetCopy() if autotest_ext: extension_path", "import unittest from telemetry.core import browser_finder from telemetry.core import exceptions", "logging.info('Trying a bad password') def ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden", "Check that the option is present, and selected if it", "# Find the keyboard layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard)) #", "else options.browser_options.username self._password = options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns True if", "autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type,", "\"\"\"Returns the autotest extension instance\"\"\" extension = browser.extensions[self._load_extension] self.assertTrue(extension) return", "with self._CreateBrowser(auto_login=False) as browser: # Ensure the dropdown lists have", "screen') def ScreenLocked(): return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\")", "\"typeof chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the", "Canada. See ' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada", "options.browser_options.auto_login = auto_login b = browser_to_create.Create() b.Start() return b def", "'en-US', _KML.ANSI, 'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'), Region('nl',", "browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login = auto_login", "as b: login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser'])", "regions.py. class Region(object): def __init__(self, region_code, keyboard, time_zone, language_code, keyboard_mechanical_layout,", "exceptions from telemetry.core import extension_to_load from telemetry.core import util from", "'en-CA', _KML.ANSI, 'Canada (US keyboard)', 'Canada with US (ANSI) keyboard;", "options = options_for_unittests.GetCopy() if autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension", "'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI,", "language_code, keyboard_mechanical_layout, description=None, notes=None): self.region_code = region_code self.keyboard = keyboard", "screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the lock screen') def ScreenLocked(): return", "\"\" # Map from other countries to a localized country", "guest user and when logged out\"\"\" with self._CreateBrowser() as b:", "Enum(frozenset): def __getattr__(self, name): if name in self: return name", "region.keyboard)) # Test is finished. Restore original region settings. self._SwitchRegion(initial_region)", "return 'en-US' # No mapping found return \"\" def testOobeLocalization(self):", "\"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin', 'Europe/Helsinki',", "self._SwitchRegion(initial_region) # The Region class and region list will be", "locale info and force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed'])", "extension.ExecuteJavaScript(''' window.__login_status = null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status = s; });", "return extension def _GetLoginStatus(self, browser): extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate')", "= self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status = null;", "= options_for_unittests.GetCopy() if autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension =", "If the locale matches a language but not the country,", "= self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale']) initial_region.keyboard, _ = self._cri.RunCmdOnDevice( ['vpd',", "[self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True options.browser_options.auto_login =", "time_zone self.language_code = language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description = description", "it is the default. (function hasOption(selectId, value, isDefault) { var", "hybrid xkb:ca:eng:eng + xkb:ca::fra keyboard (ISO), ' 'defaulting to English", "with self._CreateBrowser(autotest_ext=True) as b: extension = self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except", "isDefault) { var options = document.getElementById(selectId).options; for (var i =", "'fr-CA', _KML.ISO, 'Canada (multilingual)', (\"Canadian Multilingual keyboard; you probably don't", "keyboard layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select', region.keyboard)) # Test is finished.", "Change VPD (requires RW-enabled firmware). # To save time, region", "Used only if there ' 'needs to be a single", "_GetLoginStatus(self, browser): extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript('''", "lang == 'zh': if region in ('hk', 'mo'): return 'zh-TW'", "lists have been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'), 10)", "= null; chrome.autotestPrivate.loginStatus(function(s) { window.__login_status = s; }); ''') return", "options.length; i++) { if (options[i].value == value) { // The", "= KeyboardMechanicalLayout REGIONS_LIST = [ Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI,", "not browser.oobe.EvaluateJavaScript(''' document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); ''' %", "for all of Canada. See ' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto',", "10) def testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount status for regular and", "self.keyboard = keyboard self.time_zone = time_zone self.language_code = language_code self.keyboard_mechanical_layout", "= notes class Enum(frozenset): def __getattr__(self, name): if name in", "extension def _GetLoginStatus(self, browser): extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') !=", "extension_to_load from telemetry.core import util from telemetry.core.backends.chrome import cros_interface from", "= language_code self.keyboard_mechanical_layout = keyboard_mechanical_layout self.description = description or region_code", "http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (French keyboard)', ('Canadian", "len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs,", "b = browser_to_create.Create() b.Start() return b def _GetAutotestExtension(self, browser): \"\"\"Returns", "ui/base/l10n/l10n_util.cc. lang, _, region = map(str.lower, locale.partition('-')) if not region:", "% (self._username, self._password)) util.WaitFor(lambda: not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self):", "'') initial_region.language_code, _ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale']) initial_region.keyboard, _", "_KML.ISO, 'Sweden', (\"Use this if there separate SKUs for Nordic", "_IsCryptohomeMounted(self): \"\"\"Returns True if cryptohome is mounted\"\"\" cryptohomeJSON, _ =", "== 'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def _AttemptUnlockBadPassword(self, browser): logging.info('Trying a", "Region('ca.hybrid', 'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO, 'Canada (hybrid)', ('Canada with hybrid", "Denmark), or the device is only shipping to Sweden. \"", "self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser))", "options.selectedIndex == i; } } return false; })(\"%s\", \"%s\", %s);", "from telemetry.unittest import options_for_unittests class CrOSAutoTest(unittest.TestCase): def setUp(self): options =", "present. Make sure it's selected if necessary. return !isDefault ||", "from telemetry.core import extension_to_load from telemetry.core import util from telemetry.core.backends.chrome", "self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as browser: # Ensure the dropdown lists", "testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as b: login_status = self._GetLoginStatus(b)", "keyboard; see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (French", "# Map from other countries to a localized country if", "only read initial_locale and keyboard_layout. initial_region = self.Region('', '', '',", "there ' 'needs to be a single SKU for all", "Nordic ' 'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden', (\"Use", "'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta',", "cryptohome mount status for regular and guest user and when", "in vpd.items(): self._cri.RunCmdOnDevice(['vpd', '-s', '\"%s\"=\"%s\"' % (key, value)]) # Remove", "there is a single combined SKU for Nordic ' 'countries.')),", "in ('au', 'ca', 'nz', 'za'): return 'en-GB' return 'en-US' #", "Remove cached files to clear initial locale info and force", "See ' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (multilingual)',", "self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser):", "'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the lock screen') def", "'Asia/Calcutta', 'en-US', _KML.ANSI, 'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'),", "by a BSD-style license that can be # found in", "s; }); ''') return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self):", "10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as browser:", "' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (multilingual)', (\"Canadian", "'xkb:ca:eng:eng', 'America/Toronto', 'en-CA', _KML.ISO, 'Canada (hybrid)', ('Canada with hybrid xkb:ca:eng:eng", "= options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest = options.browser_type ==", "self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs, 'guestfs')", "'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam',", "initial locale info and force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm',", "self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); ''' % self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser))", "fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select', fallback)) # Find", "if not region: return \"\" # Map from other countries", "self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting", "0; i < options.length; i++) { if (options[i].value == value)", "# No mapping found return \"\" def testOobeLocalization(self): \"\"\"Tests different", "Denmark. This defaults ' 'to Swedish keyboard layout, but starts", "self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as b:", "The most common configuration for ' 'Canadian French SKUs. See", "autotest_ext is True, also loads the autotest extension\"\"\" options =", "def _IsCryptohomeMounted(self): \"\"\"Returns True if cryptohome is mounted\"\"\" cryptohomeJSON, _", "'function'\") and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser))", "'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'), Region('in', 'xkb:us::eng', 'Asia/Calcutta', 'en-US', _KML.ANSI,", "not region: return \"\" # Map from other countries to", "The Chromium Authors. All rights reserved. # Use of this", "= self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted'])", "an existing locale. See ui/base/l10n/l10n_util.cc. lang, _, region = map(str.lower,", "created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'), 10) # Find the", "with US English language ' 'for neutrality. Use if there", "Make sure it's selected if necessary. return !isDefault || options.selectedIndex", "def _ResolveLanguage(self, locale): # If the locale matches a language", "'language-select', fallback)) # Find the keyboard layout. self.assertTrue(self._OobeHasOption( browser, 'keyboard-select',", "SKU for Nordic ' 'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO,", "is the default. (function hasOption(selectId, value, isDefault) { var options", "self.assertFalse(self._IsScreenLocked(browser)) extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking", "2012 The Chromium Authors. All rights reserved. # Use of", "to a localized country if lang == 'es' and region", "country, fall back to # an existing locale. See ui/base/l10n/l10n_util.cc.", "' 'defaulting to English language and keyboard. Used only if", "'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics',", "device is only shipping to Sweden. \" \"If there is", "'en-US' # No mapping found return \"\" def testOobeLocalization(self): \"\"\"Tests", "country if lang == 'es' and region == 'es': return", "== 'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the lock screen')", "options_for_unittests.GetCopy() if autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad(", "'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'), Region('us', 'xkb:us::eng', 'America/Los_Angeles', 'en-US', _KML.ANSI, 'United", "(requires RW-enabled firmware). # To save time, region and initial_timezone", "def _IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser): self.assertFalse(self._IsScreenLocked(browser)) extension", "_KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng',", "'JIS', 'ABNT2']) _KML = KeyboardMechanicalLayout REGIONS_LIST = [ Region('au', 'xkb:us::eng',", "window.__login_status = s; }); ''') return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10)", "See ui/base/l10n/l10n_util.cc. lang, _, region = map(str.lower, locale.partition('-')) if not", "keyboard; you probably don't want this. See \" \"http://goto/cros-canada\")), Region('de',", "options.extensions_to_load = [self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe = True", "+ xkb:ca::fra keyboard (ISO), ' 'defaulting to English language and", "import cros_interface from telemetry.unittest import options_for_unittests class CrOSAutoTest(unittest.TestCase): def setUp(self):", "try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();') except (exceptions.BrowserConnectionGoneException, exceptions.BrowserGoneException): pass util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20)", "that can be # found in the LICENSE file. import", "'mo'): return 'zh-TW' return 'zh-CN' if lang == 'en': if", "browser): logging.info('Trying a bad password') def ErrorBubbleVisible(): return not browser.oobe.EvaluateJavaScript('''", "exceptions.BrowserGoneException): pass util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20) def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop',", "_KML.ANSI, 'India'), Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng',", "= os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load", "= self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()), chronos_fs) self.assertFalse(self._IsCryptohomeMounted()) self.assertEquals(self._cri.FilesystemMountedAt('/home/chronos/user'), '/dev/mapper/encstateful') def", "''' % (self._username, self._password)) util.WaitFor(lambda: not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def", "self._CreateBrowser(auto_login=False) as browser: # Ensure the dropdown lists have been", "region list will be available in regions.py. class Region(object): def", "options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity) self._is_guest = options.browser_type == 'cros-chrome-guest'", "|| options.selectedIndex == i; } } return false; })(\"%s\", \"%s\",", "and Denmark), or the device is only shipping to Sweden.", "self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def", "keyboard. Used only if there ' 'needs to be a", "All rights reserved. # Use of this source code is", "i; } } return false; })(\"%s\", \"%s\", %s); ''' return", "return b def _GetAutotestExtension(self, browser): \"\"\"Returns the autotest extension instance\"\"\"", "import options_for_unittests class CrOSAutoTest(unittest.TestCase): def setUp(self): options = options_for_unittests.GetCopy() self._cri", "Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB',", "info and force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log',", "in regions.py. class Region(object): def __init__(self, region_code, keyboard, time_zone, language_code,", "when logged out\"\"\" with self._CreateBrowser() as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url)", "set. vpd = {'initial_locale': region.language_code, 'keyboard_layout': region.keyboard} for (key, value)", "original device localization settings. # To save time, only read", "VPD (requires RW-enabled firmware). # To save time, region and", "for tests. if autotest_ext is True, also loads the autotest", "def testOobeLocalization(self): \"\"\"Tests different region configurations at OOBE\"\"\" # Save", "'-s', '\"%s\"=\"%s\"' % (key, value)]) # Remove cached files to", "lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount status for", "'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics', ('Unified SKU for Sweden, Norway, and", "Restore original region settings. self._SwitchRegion(initial_region) # The Region class and", "and browser.oobe.EvaluateJavaScript( \"typeof Oobe.authenticateForTesting == 'function'\")) util.WaitFor(ScreenLocked, 10) self.assertTrue(self._IsScreenLocked(browser)) def", "== 'en': if region in ('au', 'ca', 'nz', 'za'): return", "= self.Region('', '', '', '', '') initial_region.language_code, _ = self._cri.RunCmdOnDevice(", "fall back to # an existing locale. See ui/base/l10n/l10n_util.cc. lang,", "languageFound = self._OobeHasOption(browser, 'language-select', region.language_code) if not languageFound: fallback =", "see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra', 'America/Toronto', 'fr-CA', _KML.ISO, 'Canada (French keyboard)',", "xkb:ca::fra keyboard (ISO), ' 'defaulting to English language and keyboard.", "# Test is finished. Restore original region settings. self._SwitchRegion(initial_region) #", "('Canada with hybrid xkb:ca:eng:eng + xkb:ca::fra keyboard (ISO), ' 'defaulting", "import util from telemetry.core.backends.chrome import cros_interface from telemetry.unittest import options_for_unittests", "Copyright (c) 2012 The Chromium Authors. All rights reserved. #", "as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs)", "from other countries to a localized country if lang ==", "'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI,", "\"\"\"Tests autotestPrivate.screenLock\"\"\" with self._CreateBrowser(autotest_ext=True) as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def", "browser, selectId, value): hasOptionJs = ''' // Check that the", "as browser: self._LockScreen(browser) self._AttemptUnlockBadPassword(browser) self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with", "return 'zh-CN' if lang == 'en': if region in ('au',", "util.WaitFor(lambda: not self._IsCryptohomeMounted(), 20) def _SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui']) #", "a language but not the country, fall back to #", "{ if (options[i].value == value) { // The option is", "telemetry.core.backends.chrome import cros_interface from telemetry.unittest import options_for_unittests class CrOSAutoTest(unittest.TestCase): def", "'', '', '', '') initial_region.language_code, _ = self._cri.RunCmdOnDevice( ['vpd', '-g',", "('au', 'ca', 'nz', 'za'): return 'en-GB' return 'en-US' # No", "unittest from telemetry.core import browser_finder from telemetry.core import exceptions from", "want this. See \" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO,", "'language-select', region.language_code) if not languageFound: fallback = self._ResolveLanguage(region.language_code) self.assertTrue(fallback and", "auto_login=True): \"\"\"Finds and creates a browser for tests. if autotest_ext", "a single unified SKU, use 'nordic' instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore',", "options.browser_options.username self._password = options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns True if cryptohome", "regular and guest user and when logged out\"\"\" with self._CreateBrowser()", "%s); ''' return browser.oobe.EvaluateJavaScript( hasOptionJs % (selectId, value, 'true')) def", "\" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO, 'Germany'), Region('fi', 'xkb:fi::fin',", "browser): extension = self._GetAutotestExtension(browser) self.assertTrue(extension.EvaluateJavaScript( \"typeof('chrome.autotestPrivate') != 'undefined'\")) extension.ExecuteJavaScript(''' window.__login_status", "extension_to_load.ExtensionToLoad( path=extension_path, browser_type=options.browser_type, is_component=True) options.extensions_to_load = [self._load_extension] browser_to_create = browser_finder.FindBrowser(options)", "'Canada (French keyboard)', ('Canadian French (ISO) keyboard. The most common", "CrOSAutoTest(unittest.TestCase): def setUp(self): options = options_for_unittests.GetCopy() self._cri = cros_interface.CrOSInterface(options.cros_remote, options.cros_ssh_identity)", "= self._OobeHasOption(browser, 'language-select', region.language_code) if not languageFound: fallback = self._ResolveLanguage(region.language_code)", "Save the original device localization settings. # To save time,", "document.getElementById('bubble').hidden ''') self.assertFalse(ErrorBubbleVisible()) browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', 'bad'); ''' % self._username) util.WaitFor(ErrorBubbleVisible,", "util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'), 10) # Find the language,", "to # an existing locale. See ui/base/l10n/l10n_util.cc. lang, _, region", "region_code, keyboard, time_zone, language_code, keyboard_mechanical_layout, description=None, notes=None): self.region_code = region_code", "def testLoginStatus(self): \"\"\"Tests autotestPrivate.loginStatus\"\"\" with self._CreateBrowser(autotest_ext=True) as b: login_status =", "def ScreenLocked(): return (browser.oobe and browser.oobe.EvaluateJavaScript(\"typeof Oobe == 'function'\") and", "of Canada. See ' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra', 'America/Toronto', 'fr-CA', _KML.ISO,", "autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as b: extension = self._GetAutotestExtension(b) try: extension.ExecuteJavaScript('chrome.autotestPrivate.logout();')", "separate SKUs for Nordic countries (Sweden, \" \"Norway, and Denmark),", "is mounted\"\"\" cryptohomeJSON, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON)", "Enum(['ANSI', 'ISO', 'JIS', 'ABNT2']) _KML = KeyboardMechanicalLayout REGIONS_LIST = [", "time, only read initial_locale and keyboard_layout. initial_region = self.Region('', '',", "= s; }); ''') return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def", "keyboard)', 'Canada with US (ANSI) keyboard; see http://goto/cros-canada'), Region('ca.fr', 'xkb:ca::fra',", "'fr', _KML.ISO, 'France'), Region('gb', 'xkb:gb:extd:eng', 'Europe/London', 'en-GB', _KML.ISO, 'UK'), Region('ie',", "\" \"Norway, and Denmark), or the device is only shipping", "_ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'keyboard_layout']) for region in self.REGIONS_LIST:", "region): self._cri.RunCmdOnDevice(['stop', 'ui']) # Change VPD (requires RW-enabled firmware). #", "use 'nordic' instead.\")), Region('sg', 'xkb:us::eng', 'Asia/Singapore', 'en-GB', _KML.ANSI, 'Singapore'), Region('us',", "region in ('au', 'ca', 'nz', 'za'): return 'en-GB' return 'en-US'", "_, region = map(str.lower, locale.partition('-')) if not region: return \"\"", "self.assertTrue(extension.EvaluateJavaScript( \"typeof chrome.autotestPrivate.lockScreen == 'function'\")) logging.info('Locking screen') extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for", "option is present, and selected if it is the default.", "browser: # Ensure the dropdown lists have been created. util.WaitFor(lambda:", "'needs to be a single SKU for all of Canada.", "No mapping found return \"\" def testOobeLocalization(self): \"\"\"Tests different region", "'--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self,", "Chromium Authors. All rights reserved. # Use of this source", "# The Region class and region list will be available", "self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self,", "and cryptohomeStatus['mounts'][0]['mounted']) def _CreateBrowser(self, autotest_ext=False, auto_login=True): \"\"\"Finds and creates a", "self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome', '--action=status']) cryptohomeStatus = json.loads(cryptohomeJSON) return (cryptohomeStatus['mounts'] and cryptohomeStatus['mounts'][0]['mounted']) def", "chronos_fs = self._cri.FilesystemMountedAt('/home/chronos/user') self.assertTrue(chronos_fs) if self._is_guest: self.assertEquals(chronos_fs, 'guestfs') else: home,", "Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US',", "status for regular and guest user and when logged out\"\"\"", "keyboard_layout. initial_region = self.Region('', '', '', '', '') initial_region.language_code, _", "\"If there is a single unified SKU, use 'nordic' instead.\")),", "if autotest_ext is True, also loads the autotest extension\"\"\" options", "if it is the default. (function hasOption(selectId, value, isDefault) {", "and region == 'es': return 'es-419' if lang == 'zh':", "region settings. self._SwitchRegion(initial_region) # The Region class and region list", "SKU for all of Canada. See ' 'http://goto/cros-canada')), Region('ca.multix', 'xkb:ca:multix:fra',", "and force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\ State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force'])", "(ISO), ' 'defaulting to English language and keyboard. Used only", "_KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe',", "Region('my', 'xkb:us::eng', 'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl',", "Norway, and Denmark. This defaults ' 'to Swedish keyboard layout,", "\"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as b: extension = self._GetAutotestExtension(b) try:", "'countries.')), Region('se', 'xkb:se::swe', 'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden', (\"Use this if", "but starts with US English language ' 'for neutrality. Use", "'bad'); ''' % self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser):", "found return \"\" def testOobeLocalization(self): \"\"\"Tests different region configurations at", "To save time, only read initial_locale and keyboard_layout. initial_region =", "Sweden. \" \"If there is a single unified SKU, use", "['vpd', '-g', 'keyboard_layout']) for region in self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False)", "the dropdown lists have been created. util.WaitFor(lambda: browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") !=", "= keyboard_mechanical_layout self.description = description or region_code self.notes = notes", "self.assertTrue(fallback and self._OobeHasOption(browser, 'language-select', fallback)) # Find the keyboard layout.", "self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked']", "self._UnlockScreen(browser) def testLogout(self): \"\"\"Tests autotestPrivate.logout\"\"\" with self._CreateBrowser(autotest_ext=True) as b: extension", "return util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount", "self._cri.RunCmdOnDevice(['stop', 'ui']) # Change VPD (requires RW-enabled firmware). # To", "return 'es-419' if lang == 'zh': if region in ('hk',", "browser.oobe.EvaluateJavaScript( 'document.getElementById(\"language-select\") != null'), 10) # Find the language, or", "= options.browser_type == 'cros-chrome-guest' self._username = '' if self._is_guest else", "The option is present. Make sure it's selected if necessary.", "logged out\"\"\" with self._CreateBrowser() as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted())", "def _UnlockScreen(self, browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); ''' % (self._username,", "'Asia/Kuala_Lumpur', 'ms', _KML.ANSI, 'Malaysia'), Region('nl', 'xkb:us:intl:eng', 'Europe/Amsterdam', 'nl', _KML.ANSI, 'Netherlands'),", "self._password)) util.WaitFor(lambda: not browser.oobe, 10) self.assertFalse(self._IsScreenLocked(browser)) def testScreenLock(self): \"\"\"Tests autotestPrivate.screenLock\"\"\"", "b: login_status = self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest,", "browser_type=options.browser_type, is_component=True) options.extensions_to_load = [self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) options.browser_options.create_browser_with_oobe", "logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); ''' % (self._username, self._password)) util.WaitFor(lambda: not", "_SwitchRegion(self, region): self._cri.RunCmdOnDevice(['stop', 'ui']) # Change VPD (requires RW-enabled firmware).", "'America/Toronto', 'en-CA', _KML.ANSI, 'Canada (US keyboard)', 'Canada with US (ANSI)", "browser): logging.info('Unlocking') browser.oobe.ExecuteJavaScript(''' Oobe.authenticateForTesting('%s', '%s'); ''' % (self._username, self._password)) util.WaitFor(lambda:", "self.assertEquals(chronos_fs, 'guestfs') else: home, _ = self._cri.RunCmdOnDevice(['/usr/sbin/cryptohome-path', 'user', self._username]) self.assertEquals(self._cri.FilesystemMountedAt(home.rstrip()),", "= self._GetLoginStatus(b) self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'],", "time_zone, language_code, keyboard_mechanical_layout, description=None, notes=None): self.region_code = region_code self.keyboard =", "'Canada (hybrid)', ('Canada with hybrid xkb:ca:eng:eng + xkb:ca::fra keyboard (ISO),", "hasOptionJs % (selectId, value, 'true')) def _ResolveLanguage(self, locale): # If", "'Europe/Helsinki', 'fi', _KML.ISO, 'Finland'), Region('fr', 'xkb:fr::fra', 'Europe/Paris', 'fr', _KML.ISO, 'France'),", "region in self.REGIONS_LIST: self._SwitchRegion(region) with self._CreateBrowser(auto_login=False) as browser: # Ensure", "REGIONS_LIST = [ Region('au', 'xkb:us::eng', 'Australia/Sydney', 'en-AU', _KML.ANSI, 'Australia'), Region('ca.ansi',", "Multilingual keyboard; you probably don't want this. See \" \"http://goto/cros-canada\")),", "Swedish keyboard layout, but starts with US English language '", "'Europe/Stockholm', 'sv', _KML.ISO, 'Sweden', (\"Use this if there separate SKUs", "self: return name raise AttributeError KeyboardMechanicalLayout = Enum(['ANSI', 'ISO', 'JIS',", "_ = self._cri.RunCmdOnDevice( ['vpd', '-g', 'initial_locale']) initial_region.keyboard, _ = self._cri.RunCmdOnDevice(", "''' % self._username) util.WaitFor(ErrorBubbleVisible, 10) self.assertTrue(self._IsScreenLocked(browser)) def _UnlockScreen(self, browser): logging.info('Unlocking')", "region: return \"\" # Map from other countries to a", "'en-US', _KML.ISO, 'Nordics', ('Unified SKU for Sweden, Norway, and Denmark.", "out\"\"\" with self._CreateBrowser() as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs", "import logging import os import unittest from telemetry.core import browser_finder", "extension.ExecuteJavaScript('chrome.autotestPrivate.lockScreen();') logging.info('Waiting for the lock screen') def ScreenLocked(): return (browser.oobe", "to clear initial locale info and force regeneration. self._cri.RunCmdOnDevice(['rm', '/home/chronos/Local\\", "'en-GB', _KML.ISO, 'UK'), Region('ie', 'xkb:gb:extd:eng', 'Europe/Dublin', 'en-GB', _KML.ISO, 'Ireland'), Region('in',", "with self._CreateBrowser() as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) chronos_fs =", "('Unified SKU for Sweden, Norway, and Denmark. This defaults '", "cached files to clear initial locale info and force regeneration.", "'nl', _KML.ANSI, 'Netherlands'), Region('nordic', 'xkb:se::swe', 'Europe/Stockholm', 'en-US', _KML.ISO, 'Nordics', ('Unified", "State']) self._cri.RunCmdOnDevice(['rm', '/home/chronos/.oobe_completed']) self._cri.RunCmdOnDevice(['dump_vpd_log', '--force']) self._cri.RunCmdOnDevice(['start', 'ui']) def _OobeHasOption(self, browser,", "See \" \"http://goto/cros-canada\")), Region('de', 'xkb:de::ger', 'Europe/Berlin', 'de', _KML.ISO, 'Germany'), Region('fi',", "if self._is_guest else options.browser_options.username self._password = options.browser_options.password def _IsCryptohomeMounted(self): \"\"\"Returns", "self._username) self.assertFalse(login_status['isScreenLocked']) def _IsScreenLocked(self, browser): return self._GetLoginStatus(browser)['isScreenLocked'] def _LockScreen(self, browser):", "autotest extension instance\"\"\" extension = browser.extensions[self._load_extension] self.assertTrue(extension) return extension def", "util.WaitFor( lambda: extension.EvaluateJavaScript('window.__login_status'), 10) def testCryptohomeMounted(self): \"\"\"Verifies cryptohome mount status", "Sweden, Norway, and Denmark. This defaults ' 'to Swedish keyboard" ]