code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
__updated__ = '2019-12-02' __version_info__ = (19, 8, 0) __version__ = '.'.join(map(str, __version_info__)) # Import system type stuff # Import PyMh files from Modules.Core.Utilities import extract_tools from Modules.Core.Utilities.debug_tools import PrettyFormatAny from Modules.Core import logging_pyh as Logger LOG = Logger.getLogger('PyHouse.Hvac ') class HvacInformation: """ DeviceType = 'Hvac' ==> PyHouse.House.Hvac.xxx as in the def below """ def __init__(self): self.Thermostats = {} # ThermostatData() Sub = 1 class lightingUtilityHvac: """ """ class MqttActions: """ """ def __init__(self, p_pyhouse_obj): self.m_pyhouse_obj = p_pyhouse_obj def _decode_thermostat(self, p_msg): """ """ p_msg.LogMessage += '\tThermostat: {}\n'.format(extract_tools.get_mqtt_field(p_msg.Payload, 'Name')) def decode(self, p_msg): """ Decode the Mqtt message ==> pyhouse/<house name>/house/hvac/<type>/<Name>/... <type> = thermostat, ... """ l_topic = p_msg.UnprocessedTopic p_msg.UnprocessedTopic = p_msg.UnprocessedTopic[1:] p_msg.LogMessage += '\tHVAC:\n' if l_topic[0] == 'thermostat': self._decode_thermostat(p_msg) else: p_msg.Topic += '\tUnknown sub-topic {}'.format(PrettyFormatAny.form(p_msg.Payload, 'Message', 160)) return p_msg.Topic def _decode_hvac(self, p_logmsg, _p_topic, p_message): p_logmsg += '\tThermostat:\n' # p_logmsg += '\tName: {}'.p_msg.LogMessageelf.m_name) p_logmsg += '\tRoom: {}\n'.format(self.m_room_name) p_logmsg += '\tTemp: {}'.format(extract_tools.get_mqtt_field(p_message, 'CurrentTemperature')) return p_logmsg class Api(lightingUtilityHvac): m_pyhouse_obj = None def __init__(self, p_pyhouse_obj): self.m_pyhouse_obj = p_pyhouse_obj self.m_pyhouse_obj.House.Hvac = HvacInformation() LOG.info("Initialized.") def LoadConfig(self): """ Load the HVAC config info. """ def Start(self): LOG.info("Started.") def Stop(self): LOG.info("Stopped.") def SaveConfig(self): # hvacXML.write_hvac_xml() LOG.info("Saved Hvac XML.") # ## END DBK
Project/src/Modules/House/Hvac/hvac.py
__updated__ = '2019-12-02' __version_info__ = (19, 8, 0) __version__ = '.'.join(map(str, __version_info__)) # Import system type stuff # Import PyMh files from Modules.Core.Utilities import extract_tools from Modules.Core.Utilities.debug_tools import PrettyFormatAny from Modules.Core import logging_pyh as Logger LOG = Logger.getLogger('PyHouse.Hvac ') class HvacInformation: """ DeviceType = 'Hvac' ==> PyHouse.House.Hvac.xxx as in the def below """ def __init__(self): self.Thermostats = {} # ThermostatData() Sub = 1 class lightingUtilityHvac: """ """ class MqttActions: """ """ def __init__(self, p_pyhouse_obj): self.m_pyhouse_obj = p_pyhouse_obj def _decode_thermostat(self, p_msg): """ """ p_msg.LogMessage += '\tThermostat: {}\n'.format(extract_tools.get_mqtt_field(p_msg.Payload, 'Name')) def decode(self, p_msg): """ Decode the Mqtt message ==> pyhouse/<house name>/house/hvac/<type>/<Name>/... <type> = thermostat, ... """ l_topic = p_msg.UnprocessedTopic p_msg.UnprocessedTopic = p_msg.UnprocessedTopic[1:] p_msg.LogMessage += '\tHVAC:\n' if l_topic[0] == 'thermostat': self._decode_thermostat(p_msg) else: p_msg.Topic += '\tUnknown sub-topic {}'.format(PrettyFormatAny.form(p_msg.Payload, 'Message', 160)) return p_msg.Topic def _decode_hvac(self, p_logmsg, _p_topic, p_message): p_logmsg += '\tThermostat:\n' # p_logmsg += '\tName: {}'.p_msg.LogMessageelf.m_name) p_logmsg += '\tRoom: {}\n'.format(self.m_room_name) p_logmsg += '\tTemp: {}'.format(extract_tools.get_mqtt_field(p_message, 'CurrentTemperature')) return p_logmsg class Api(lightingUtilityHvac): m_pyhouse_obj = None def __init__(self, p_pyhouse_obj): self.m_pyhouse_obj = p_pyhouse_obj self.m_pyhouse_obj.House.Hvac = HvacInformation() LOG.info("Initialized.") def LoadConfig(self): """ Load the HVAC config info. """ def Start(self): LOG.info("Started.") def Stop(self): LOG.info("Stopped.") def SaveConfig(self): # hvacXML.write_hvac_xml() LOG.info("Saved Hvac XML.") # ## END DBK
0.422147
0.105441
from django.views.generic.simple import direct_to_template from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest import flickrapi import flickrapi.shorturl import simplejson import bueda import logging def demo(request): flickr_conn = flickrapi.FlickrAPI(settings.FLICKR_API_KEY, settings.FLICKR_API_SECRET) username = request.GET.get('username', '') # If username is specified in the request if username: try: response = flickr_conn.people_findByUsername( username=request.GET.get('username', '')) # If username is not found on flickr except flickrapi.exceptions.FlickrError: return direct_to_template( request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'error_message':'The given username does not exist. Please be sure to enter the username and not user alias'} ) user_id = response.find('user').attrib['id'] response = flickr_conn.people_getPublicPhotos(user_id=user_id) public_photos = response.find('photos').findall('photo')[0:5] if not public_photos: return direct_to_template( request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'error_message':'The user does not have any public photos'} ) enriched_photos = [] for photo in public_photos: photo_id = photo.attrib['id'] short_url = "http://flic.kr/p/%s" % flickrapi.shorturl.encode( photo_id) response = flickr_conn.tags_getListPhoto(photo_id=photo_id) xml_tags = response.find('photo').find('tags').findall('tag') tags = [] for xml_tag in xml_tags: tags.append(xml_tag.attrib['raw']) enriched_tags = bueda.enrich(tags) img_url = "http://farm%s.static.flickr.com/%s/%s_%s_m.jpg" % ( photo.attrib['farm'], photo.attrib['server'], photo_id, photo.attrib['secret']) output_tags = enriched_tags.canonical output_tags.extend(map(lambda c: c.name, enriched_tags.categories)) for concept in enriched_tags.semantic: output_tags.extend(concept.types) output_tags = set(output_tags) enriched_photos.append(dict(img_url=img_url, page_url=short_url, original_tags=tags, tags=output_tags)) if 'application/json' in request.META.get('HTTP_ACCEPT', ''): return HttpResponse(simplejson.dumps(enriched_photos), mimetype='application/json') else: return direct_to_template(request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'photos': enriched_photos}) else: if 'application/json' in request.META.get('HTTP_ACCEPT', ''): return HttpResponseBadRequest(mimetype='application/json') else: return direct_to_template(request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'error_message':'Please enter the username'})
bueda_flickr_mashup/views.py
from django.views.generic.simple import direct_to_template from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest import flickrapi import flickrapi.shorturl import simplejson import bueda import logging def demo(request): flickr_conn = flickrapi.FlickrAPI(settings.FLICKR_API_KEY, settings.FLICKR_API_SECRET) username = request.GET.get('username', '') # If username is specified in the request if username: try: response = flickr_conn.people_findByUsername( username=request.GET.get('username', '')) # If username is not found on flickr except flickrapi.exceptions.FlickrError: return direct_to_template( request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'error_message':'The given username does not exist. Please be sure to enter the username and not user alias'} ) user_id = response.find('user').attrib['id'] response = flickr_conn.people_getPublicPhotos(user_id=user_id) public_photos = response.find('photos').findall('photo')[0:5] if not public_photos: return direct_to_template( request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'error_message':'The user does not have any public photos'} ) enriched_photos = [] for photo in public_photos: photo_id = photo.attrib['id'] short_url = "http://flic.kr/p/%s" % flickrapi.shorturl.encode( photo_id) response = flickr_conn.tags_getListPhoto(photo_id=photo_id) xml_tags = response.find('photo').find('tags').findall('tag') tags = [] for xml_tag in xml_tags: tags.append(xml_tag.attrib['raw']) enriched_tags = bueda.enrich(tags) img_url = "http://farm%s.static.flickr.com/%s/%s_%s_m.jpg" % ( photo.attrib['farm'], photo.attrib['server'], photo_id, photo.attrib['secret']) output_tags = enriched_tags.canonical output_tags.extend(map(lambda c: c.name, enriched_tags.categories)) for concept in enriched_tags.semantic: output_tags.extend(concept.types) output_tags = set(output_tags) enriched_photos.append(dict(img_url=img_url, page_url=short_url, original_tags=tags, tags=output_tags)) if 'application/json' in request.META.get('HTTP_ACCEPT', ''): return HttpResponse(simplejson.dumps(enriched_photos), mimetype='application/json') else: return direct_to_template(request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'photos': enriched_photos}) else: if 'application/json' in request.META.get('HTTP_ACCEPT', ''): return HttpResponseBadRequest(mimetype='application/json') else: return direct_to_template(request, 'bueda_flickr_mashup/templates/bueda_flickr_mashup/demo.html', {'error_message':'Please enter the username'})
0.218419
0.051439
from custom_dataset import Multimodal_Data_Generator from sentence_cnn import SentenceCNN from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.applications.resnet import ResNet50 from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, ReduceLROnPlateau from tensorflow.keras.layers import Input from tensorflow.keras.layers import Dropout, Dense, BatchNormalization, concatenate, Activation, GlobalAveragePooling1D, Layer, MultiHeadAttention, LayerNormalization, Embedding, AveragePooling2D, Flatten from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam import numpy as np import pandas as pd import pickle import sys import tensorflow as tf class TransformerBlock(Layer): def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1): super(TransformerBlock, self).__init__() self.att = MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim) self.ffn = tf.keras.Sequential( [Dense(ff_dim, activation="relu"), Dense(embed_dim),] ) self.layernorm1 = LayerNormalization(epsilon=1e-6) self.layernorm2 = LayerNormalization(epsilon=1e-6) self.dropout1 = Dropout(rate) self.dropout2 = Dropout(rate) def call(self, inputs, training): attn_output = self.att(inputs, inputs) attn_output = self.dropout1(attn_output, training=training) out1 = self.layernorm1(inputs + attn_output) ffn_output = self.ffn(out1) ffn_output = self.dropout2(ffn_output, training=training) return self.layernorm2(out1 + ffn_output) def get_config(self): config = super().get_config().copy() config.update({ 'att': self.att, 'ffn': self.ffn, 'layernorm1': self.layernorm1, 'layernorm2': self.layernorm2, 'dropout1': self.dropout1, 'dropout2': self.dropout2 }) return config class TokenAndPositionEmbedding(Layer): def __init__(self, maxlen, vocab_size, embed_dim): super(TokenAndPositionEmbedding, self).__init__() self.token_emb = Embedding(input_dim=vocab_size, output_dim=embed_dim) self.pos_emb = Embedding(input_dim=maxlen, output_dim=embed_dim) def call(self, x): maxlen = tf.shape(x)[-1] positions = tf.range(start=0, limit=maxlen, delta=1) positions = self.pos_emb(positions) x = self.token_emb(x) return x + positions def get_config(self): config = super().get_config().copy() config.update({ 'token_emb': self.token_emb, 'pos_emb': self.pos_emb }) return config if __name__ == "__main__": TASK = "humanitarian" # "humanitarian" or "informative" SEED = 2021 # Seed to be used for reproducability print("\nLoading in training and validation datasets...") # Specify location of csv files containing training and validation data train_filepath = f"../../data/interim/task_{TASK}_train_preprocessed_text.csv" val_filepath = f"../../data/interim/task_{TASK}_val_preprocessed_text.csv" # Load in csv files containing training and validation data train_df = pd.read_csv(train_filepath) val_df = pd.read_csv(val_filepath) # NOTE: we're not going to load the actual datasets here. Too many OOM errors. # Instead, we're going to load the data into memory during training using data generators. train_data_gen = Multimodal_Data_Generator(train_df, batch_size=2) val_data_gen = Multimodal_Data_Generator(val_df, batch_size=2) # Get the number of classes num_classes = len(train_df["int_label"].unique()) print("\nLoading in word_index and embedding_matrix for text model...") # Load in word_index word_index = pickle.load(open(f"../../data/interim/{TASK}_word_index.pickle", "rb")) vocab_size = 20000 print("vocab_size =", vocab_size) # Load in embedding matrix embedding_matrix = np.load(f"../../data/interim/{TASK}_embedding_matrix.npy") embed_dim = embedding_matrix.shape[1] # Embedding size for each token print("embed_dim =", embed_dim) maxlen = 25 print("maxlen =", maxlen) num_heads = 2 # Number of attention heads ff_dim = 32 # Hidden layer size in feed forward network inside transformer # NOTE: Can kill the word_index and embedding_matrix variables after passing them # into the text model to free up some space? print("\nCreating text model...") text_inputs = Input(shape=(maxlen,)) embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim) x_text = embedding_layer(text_inputs) transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim) x_text = transformer_block(x_text) x_text = GlobalAveragePooling1D()(x_text) # x_text = Dropout(0.2)(x_text) x_text = Dense(500, activation="relu")(x_text) batchnorm_text = BatchNormalization()(x_text) # x = Dropout(0.2)(x) # outputs = Dense(num_classes, activation="softmax")(x) # text_model = Model(inputs=text_inputs, outputs=outputs) # # Create CNN for sentence classification # text_inputs = Input(shape=(25,)) # conv_layers = SentenceCNN(text_inputs, word_index, embedding_matrix) # activation_0 = Activation("relu")(conv_layers) # dropout_0 = Dropout(0.02)(activation_0) # dense_0_text = Dense(2000, activation="relu")(dropout_0) # dense_1_text = Dense(1000, activation="relu")(dense_0_text) # batchnorm_text = BatchNormalization()(dense_1_text) print("\nCreating image mode...") image_base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224,224,3)) image_output_layer = image_base_model.output image_output_layer = AveragePooling2D(pool_size=(7, 7))(image_output_layer) image_output_layer = Flatten(name="flatten")(image_output_layer) image_output_layer = Dense(500, activation="relu")(image_output_layer) batchnorm_image = BatchNormalization()(image_output_layer) # image_output_layer = Dropout(0.5)(image_output_layer) # image_output_layer = Dense(num_classes, activation="softmax")(image_output_layer) # Freeze layers of image base model for layer in image_base_model.layers: layer.trainable = False # # Create VGG16 model # vgg16_model = VGG16(weights="imagenet") # fc2 = vgg16_model.get_layer("fc2").output # dense_image = Dense(1000, activation="relu")(fc2) # batchnorm_image = BatchNormalization()(dense_image) print("\nCreating text and image merged model...") # Concatenate last layers of both models concat_multimodal = concatenate([batchnorm_image, batchnorm_text]) batchnorm_multimodal = BatchNormalization()(concat_multimodal) dropout_0_multimodal = Dropout(0.4)(batchnorm_multimodal) dense_0_multimodal = Dense(500, activation="relu")(dropout_0_multimodal) dropout_1_multimodal = Dropout(0.2)(dense_0_multimodal) dense_1_multimodal = Dense(100, activation="relu")(dropout_1_multimodal) dropout_2_multimodal = Dropout(0.02)(dense_1_multimodal) output_layer = Dense(num_classes, activation="softmax")(dropout_2_multimodal) model = Model(inputs=[image_base_model.input, text_inputs], outputs=output_layer) print(model.summary()) # sys.exit() # Initialize Adam optimizer adam = Adam(learning_rate=0.0001) # NOTE: not specified in paper # Config model with losses and metrics model.compile(optimizer=adam, loss="categorical_crossentropy", metrics=["accuracy"]) # Initialize learning rate reducer lr_reducer = ReduceLROnPlateau(monitor="val_accuracy", factor=0.1, patience=5, verbose=1, mode="max") # Set early-stopping criterion based on the accuracy on the development set with the patience of 10 early_stopping = EarlyStopping(monitor="val_accuracy", patience=10, verbose=1, mode="max") # Initialize TensorBoard to visualize learning tensorboard = TensorBoard(log_dir=f"../../models-improved/multimodal/{TASK}", write_images=True) # Create model checkpoints checkpoint_filepath = f"../../models-improved/multimodal/{TASK}/{TASK}_checkpoint" checkpoint = ModelCheckpoint(filepath=checkpoint_filepath, monitor="val_accuracy", save_best_only=True, save_weights_only=True, mode="max") # Train and validate model history = model.fit(x=train_data_gen, epochs=50, validation_data=val_data_gen, callbacks=[lr_reducer, early_stopping, tensorboard, checkpoint]) # Load model with best weights model.load_weights(checkpoint_filepath) # Save trained model with best weights model.save(f"../../models-improved/multimodal/{TASK}/{TASK}.hdf5")
src/models/train_multimodal_model_2.py
from custom_dataset import Multimodal_Data_Generator from sentence_cnn import SentenceCNN from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.applications.resnet import ResNet50 from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, ReduceLROnPlateau from tensorflow.keras.layers import Input from tensorflow.keras.layers import Dropout, Dense, BatchNormalization, concatenate, Activation, GlobalAveragePooling1D, Layer, MultiHeadAttention, LayerNormalization, Embedding, AveragePooling2D, Flatten from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam import numpy as np import pandas as pd import pickle import sys import tensorflow as tf class TransformerBlock(Layer): def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1): super(TransformerBlock, self).__init__() self.att = MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim) self.ffn = tf.keras.Sequential( [Dense(ff_dim, activation="relu"), Dense(embed_dim),] ) self.layernorm1 = LayerNormalization(epsilon=1e-6) self.layernorm2 = LayerNormalization(epsilon=1e-6) self.dropout1 = Dropout(rate) self.dropout2 = Dropout(rate) def call(self, inputs, training): attn_output = self.att(inputs, inputs) attn_output = self.dropout1(attn_output, training=training) out1 = self.layernorm1(inputs + attn_output) ffn_output = self.ffn(out1) ffn_output = self.dropout2(ffn_output, training=training) return self.layernorm2(out1 + ffn_output) def get_config(self): config = super().get_config().copy() config.update({ 'att': self.att, 'ffn': self.ffn, 'layernorm1': self.layernorm1, 'layernorm2': self.layernorm2, 'dropout1': self.dropout1, 'dropout2': self.dropout2 }) return config class TokenAndPositionEmbedding(Layer): def __init__(self, maxlen, vocab_size, embed_dim): super(TokenAndPositionEmbedding, self).__init__() self.token_emb = Embedding(input_dim=vocab_size, output_dim=embed_dim) self.pos_emb = Embedding(input_dim=maxlen, output_dim=embed_dim) def call(self, x): maxlen = tf.shape(x)[-1] positions = tf.range(start=0, limit=maxlen, delta=1) positions = self.pos_emb(positions) x = self.token_emb(x) return x + positions def get_config(self): config = super().get_config().copy() config.update({ 'token_emb': self.token_emb, 'pos_emb': self.pos_emb }) return config if __name__ == "__main__": TASK = "humanitarian" # "humanitarian" or "informative" SEED = 2021 # Seed to be used for reproducability print("\nLoading in training and validation datasets...") # Specify location of csv files containing training and validation data train_filepath = f"../../data/interim/task_{TASK}_train_preprocessed_text.csv" val_filepath = f"../../data/interim/task_{TASK}_val_preprocessed_text.csv" # Load in csv files containing training and validation data train_df = pd.read_csv(train_filepath) val_df = pd.read_csv(val_filepath) # NOTE: we're not going to load the actual datasets here. Too many OOM errors. # Instead, we're going to load the data into memory during training using data generators. train_data_gen = Multimodal_Data_Generator(train_df, batch_size=2) val_data_gen = Multimodal_Data_Generator(val_df, batch_size=2) # Get the number of classes num_classes = len(train_df["int_label"].unique()) print("\nLoading in word_index and embedding_matrix for text model...") # Load in word_index word_index = pickle.load(open(f"../../data/interim/{TASK}_word_index.pickle", "rb")) vocab_size = 20000 print("vocab_size =", vocab_size) # Load in embedding matrix embedding_matrix = np.load(f"../../data/interim/{TASK}_embedding_matrix.npy") embed_dim = embedding_matrix.shape[1] # Embedding size for each token print("embed_dim =", embed_dim) maxlen = 25 print("maxlen =", maxlen) num_heads = 2 # Number of attention heads ff_dim = 32 # Hidden layer size in feed forward network inside transformer # NOTE: Can kill the word_index and embedding_matrix variables after passing them # into the text model to free up some space? print("\nCreating text model...") text_inputs = Input(shape=(maxlen,)) embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim) x_text = embedding_layer(text_inputs) transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim) x_text = transformer_block(x_text) x_text = GlobalAveragePooling1D()(x_text) # x_text = Dropout(0.2)(x_text) x_text = Dense(500, activation="relu")(x_text) batchnorm_text = BatchNormalization()(x_text) # x = Dropout(0.2)(x) # outputs = Dense(num_classes, activation="softmax")(x) # text_model = Model(inputs=text_inputs, outputs=outputs) # # Create CNN for sentence classification # text_inputs = Input(shape=(25,)) # conv_layers = SentenceCNN(text_inputs, word_index, embedding_matrix) # activation_0 = Activation("relu")(conv_layers) # dropout_0 = Dropout(0.02)(activation_0) # dense_0_text = Dense(2000, activation="relu")(dropout_0) # dense_1_text = Dense(1000, activation="relu")(dense_0_text) # batchnorm_text = BatchNormalization()(dense_1_text) print("\nCreating image mode...") image_base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224,224,3)) image_output_layer = image_base_model.output image_output_layer = AveragePooling2D(pool_size=(7, 7))(image_output_layer) image_output_layer = Flatten(name="flatten")(image_output_layer) image_output_layer = Dense(500, activation="relu")(image_output_layer) batchnorm_image = BatchNormalization()(image_output_layer) # image_output_layer = Dropout(0.5)(image_output_layer) # image_output_layer = Dense(num_classes, activation="softmax")(image_output_layer) # Freeze layers of image base model for layer in image_base_model.layers: layer.trainable = False # # Create VGG16 model # vgg16_model = VGG16(weights="imagenet") # fc2 = vgg16_model.get_layer("fc2").output # dense_image = Dense(1000, activation="relu")(fc2) # batchnorm_image = BatchNormalization()(dense_image) print("\nCreating text and image merged model...") # Concatenate last layers of both models concat_multimodal = concatenate([batchnorm_image, batchnorm_text]) batchnorm_multimodal = BatchNormalization()(concat_multimodal) dropout_0_multimodal = Dropout(0.4)(batchnorm_multimodal) dense_0_multimodal = Dense(500, activation="relu")(dropout_0_multimodal) dropout_1_multimodal = Dropout(0.2)(dense_0_multimodal) dense_1_multimodal = Dense(100, activation="relu")(dropout_1_multimodal) dropout_2_multimodal = Dropout(0.02)(dense_1_multimodal) output_layer = Dense(num_classes, activation="softmax")(dropout_2_multimodal) model = Model(inputs=[image_base_model.input, text_inputs], outputs=output_layer) print(model.summary()) # sys.exit() # Initialize Adam optimizer adam = Adam(learning_rate=0.0001) # NOTE: not specified in paper # Config model with losses and metrics model.compile(optimizer=adam, loss="categorical_crossentropy", metrics=["accuracy"]) # Initialize learning rate reducer lr_reducer = ReduceLROnPlateau(monitor="val_accuracy", factor=0.1, patience=5, verbose=1, mode="max") # Set early-stopping criterion based on the accuracy on the development set with the patience of 10 early_stopping = EarlyStopping(monitor="val_accuracy", patience=10, verbose=1, mode="max") # Initialize TensorBoard to visualize learning tensorboard = TensorBoard(log_dir=f"../../models-improved/multimodal/{TASK}", write_images=True) # Create model checkpoints checkpoint_filepath = f"../../models-improved/multimodal/{TASK}/{TASK}_checkpoint" checkpoint = ModelCheckpoint(filepath=checkpoint_filepath, monitor="val_accuracy", save_best_only=True, save_weights_only=True, mode="max") # Train and validate model history = model.fit(x=train_data_gen, epochs=50, validation_data=val_data_gen, callbacks=[lr_reducer, early_stopping, tensorboard, checkpoint]) # Load model with best weights model.load_weights(checkpoint_filepath) # Save trained model with best weights model.save(f"../../models-improved/multimodal/{TASK}/{TASK}.hdf5")
0.798776
0.351673
import datetime from django.test import TestCase from django.utils import timezone from .models import Article from infinite_scroll_pagination.paginator import SeekPaginator from infinite_scroll_pagination import paginator as inf_paginator class Paginator2FieldsTest(TestCase): def setUp(self): date = timezone.now() for i in range(25): seconds = datetime.timedelta(seconds=i) Article.objects.create( title="%s" % i, date=date, date_unique=date + seconds) def test_next_desc(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_is_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_asc_desc(self): articles = Article.objects.all().order_by('is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc(self): articles = Article.objects.all().order_by('-is_pinned', "date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_asc_desc(self): articles = Article.objects.all().order_by('is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc(self): articles = Article.objects.all().order_by('-is_pinned', "date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_desc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_non_unique_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_non_unique_is_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_asc_desc_non_unique(self): articles = Article.objects.all().order_by('is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "date", "pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_asc_desc_non_unique(self): articles = Article.objects.all().order_by('is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "date", "pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) class Paginator3FieldsTest(TestCase): def setUp(self): date = timezone.now() for i in range(25): seconds = datetime.timedelta(seconds=i) Article.objects.create( title="%s" % i, date=date, date_unique=date + seconds) def test_next_desc(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_desc_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", "-pk") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10]))
tests/test_multi_fields.py
import datetime from django.test import TestCase from django.utils import timezone from .models import Article from infinite_scroll_pagination.paginator import SeekPaginator from infinite_scroll_pagination import paginator as inf_paginator class Paginator2FieldsTest(TestCase): def setUp(self): date = timezone.now() for i in range(25): seconds = datetime.timedelta(seconds=i) Article.objects.create( title="%s" % i, date=date, date_unique=date + seconds) def test_next_desc(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_is_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_asc_desc(self): articles = Article.objects.all().order_by('is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc(self): articles = Article.objects.all().order_by('-is_pinned', "date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_asc_desc(self): articles = Article.objects.all().order_by('is_pinned', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc(self): articles = Article.objects.all().order_by('-is_pinned', "date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date_unique')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_desc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_non_unique_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_non_unique_is_pinned(self): articles = Article.objects.all().order_by('-is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_asc_desc_non_unique(self): articles = Article.objects.all().order_by('is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "date", "pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_asc_desc_non_unique(self): articles = Article.objects.all().order_by('is_pinned', "-date", "-pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('is_pinned', '-date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc_non_unique(self): articles = Article.objects.all().order_by('-is_pinned', "date", "pk") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'date')) page_2 = paginator.page( value=(list(articles)[20].is_pinned, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=(page_2[0].is_pinned, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) class Paginator3FieldsTest(TestCase): def setUp(self): date = timezone.now() for i in range(25): seconds = datetime.timedelta(seconds=i) Article.objects.create( title="%s" % i, date=date, date_unique=date + seconds) def test_next_desc(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date_unique')) page_1 = paginator.page(value=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date_unique)) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date_unique)) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc_sticky_pinned(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date_unique") for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date_unique')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date_unique), move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_next_desc_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", "-pk") paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_next_desc_asc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date')) page_1 = paginator.page(value=None, pk=None) self.assertListEqual(list(page_1), list(articles[:10])) page_2 = paginator.page( value=(page_1[-1].is_pinned, page_1[-1].is_sticky, page_1[-1].date), pk=page_1[-1].pk) self.assertListEqual(list(page_2), list(articles[10:20])) page_3 = paginator.page( value=(page_2[-1].is_pinned, page_2[-1].is_sticky, page_2[-1].date), pk=page_2[-1].pk) self.assertListEqual(list(page_3), list(articles[20:])) def test_prev_desc_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', '-is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', '-is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10])) def test_prev_desc_asc_sticky_pinned_non_unique(self): articles = Article.objects.all().order_by( '-is_pinned', 'is_sticky', "-date", '-pk') for a in articles[:5]: a.is_pinned = True a.save() for a in articles[10:15]: a.is_pinned = True a.is_sticky = True a.save() for a in articles[20:]: a.is_pinned = True a.is_sticky = True a.save() paginator = SeekPaginator( Article.objects.all(), per_page=10, lookup_field=('-is_pinned', 'is_sticky', '-date')) page_2 = paginator.page( value=( list(articles)[20].is_pinned, list(articles)[20].is_sticky, list(articles)[20].date), pk=list(articles)[20].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_2), list(articles[10:20])) page_1 = paginator.page( value=( page_2[0].is_pinned, page_2[0].is_sticky, page_2[0].date), pk=page_2[0].pk, move_to=inf_paginator.PREV_PAGE) self.assertListEqual(list(page_1), list(articles[:10]))
0.438545
0.383872
from __future__ import absolute_import, division, print_function, unicode_literals from pkg_resources import resource_filename import bioutils.sequences import ometa.runtime import parsley import hgvs.edit import hgvs.hgvsposition import hgvs.location import hgvs.posedit import hgvs.variant class Parser(object): """Provides comprehensive parsing of HGVS varaint strings (*i.e.*, variants represented according to the Human Genome Variation Society recommendations) into Python representations. The class wraps a Parsing Expression Grammar, exposing rules of that grammar as methods (prefixed with `parse_`) that parse an input string according to the rule. The class exposes all rules, so that it's possible to parse both full variant representations as well as components, like so: >>> hp = Parser() >>> v = hp.parse_hgvs_variant("NM_01234.5:c.22+1A>T") >>> v SequenceVariant(ac=NM_01234.5, type=c, posedit=22+1A>T) >>> v.posedit.pos Interval(start=22+1, end=22+1, uncertain=False) >>> i = hp.parse_c_interval('22+1') >>> i Interval(start=22+1, end=22+1, uncertain=False) The `parse_hgvs_variant` and `parse_c_interval` methods correspond to the `hgvs_variant` and `c_interval rules` in the grammar, respectively. Because the methods are generated on-the-fly and depend on the grammar that is loaded at runtime, a full list of methods is not available in the documentation. However, the list of rules/methods is available via the `rules` instance variable. A few notable methods are listed below: `parse_hgvs_variant()` parses any valid HGVS string supported by the grammar. >>> hp.parse_hgvs_variant("NM_01234.5:c.22+1A>T") SequenceVariant(ac=NM_01234.5, type=c, posedit=22+1A>T) >>> hp.parse_hgvs_variant('NP_012345.6:p.Ala22Trp') SequenceVariant(ac=NP_012345.6, type=p, posedit=Ala22Trp) The `hgvs_variant` rule iteratively attempts parsing using the major classes of HGVS variants. For slight improvements in efficiency, those rules may be invoked directly: >>> hp.parse_p_variant('NP_012345.6:p.Ala22Trp') SequenceVariant(ac=NP_012345.6, type=p, posedit=Ala22Trp) Similarly, components of the underlying structure may be parsed directly as well: >>> hp.parse_c_posedit('22+1A>T') PosEdit(pos=22+1, edit=A>T, uncertain=False) >>> hp.parse_c_interval('22+1') Interval(start=22+1, end=22+1, uncertain=False) """ __default_grammar_fn = resource_filename(__name__, '_data/hgvs.pymeta') def __init__(self,grammar_fn=__default_grammar_fn): self._grammar_fn = grammar_fn self._grammar = parsley.makeGrammar(open(grammar_fn,'r').read(),{'hgvs': hgvs, 'bioutils': bioutils}) # define function attributes for each grammar rule, prefixed with 'parse_' # e.g., Parser.parse_c_interval('26+2_57-3') -> Interval(...) #TODO: exclude built-in rules self.rules = [ m.replace('rule_','') for m in dir(self._grammar._grammarClass) if m.startswith('rule_') ] for rule_name in self.rules: att_name = 'parse_' + rule_name rule_fxn = self.__make_parse_rule_function(rule_name) self.__setattr__(att_name,rule_fxn) def __make_parse_rule_function(self,rule_name): # http://docs.python.org/2/reference/datamodel.html#object.__getattr__ """ This function returns a function that takes a string and returns the parsing result. """ def rule_fxn(s): try: return self._grammar(s).__getattr__(rule_name)() except ometa.runtime.ParseError as exc: raise hgvs.exceptions.HGVSParseError, hgvs.exceptions.HGVSParseError("{s}: char {exc.position}: {reason}".format(s=s, exc=exc, reason=exc.formatReason())) rule_fxn.func_doc = "parse string s using `%s' rule" % rule_name return rule_fxn ## <LICENSE> ## Copyright 2014 HGVS Contributors (https://bitbucket.org/hgvs/hgvs) ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## </LICENSE>
hgvs/parser.py
from __future__ import absolute_import, division, print_function, unicode_literals from pkg_resources import resource_filename import bioutils.sequences import ometa.runtime import parsley import hgvs.edit import hgvs.hgvsposition import hgvs.location import hgvs.posedit import hgvs.variant class Parser(object): """Provides comprehensive parsing of HGVS varaint strings (*i.e.*, variants represented according to the Human Genome Variation Society recommendations) into Python representations. The class wraps a Parsing Expression Grammar, exposing rules of that grammar as methods (prefixed with `parse_`) that parse an input string according to the rule. The class exposes all rules, so that it's possible to parse both full variant representations as well as components, like so: >>> hp = Parser() >>> v = hp.parse_hgvs_variant("NM_01234.5:c.22+1A>T") >>> v SequenceVariant(ac=NM_01234.5, type=c, posedit=22+1A>T) >>> v.posedit.pos Interval(start=22+1, end=22+1, uncertain=False) >>> i = hp.parse_c_interval('22+1') >>> i Interval(start=22+1, end=22+1, uncertain=False) The `parse_hgvs_variant` and `parse_c_interval` methods correspond to the `hgvs_variant` and `c_interval rules` in the grammar, respectively. Because the methods are generated on-the-fly and depend on the grammar that is loaded at runtime, a full list of methods is not available in the documentation. However, the list of rules/methods is available via the `rules` instance variable. A few notable methods are listed below: `parse_hgvs_variant()` parses any valid HGVS string supported by the grammar. >>> hp.parse_hgvs_variant("NM_01234.5:c.22+1A>T") SequenceVariant(ac=NM_01234.5, type=c, posedit=22+1A>T) >>> hp.parse_hgvs_variant('NP_012345.6:p.Ala22Trp') SequenceVariant(ac=NP_012345.6, type=p, posedit=Ala22Trp) The `hgvs_variant` rule iteratively attempts parsing using the major classes of HGVS variants. For slight improvements in efficiency, those rules may be invoked directly: >>> hp.parse_p_variant('NP_012345.6:p.Ala22Trp') SequenceVariant(ac=NP_012345.6, type=p, posedit=Ala22Trp) Similarly, components of the underlying structure may be parsed directly as well: >>> hp.parse_c_posedit('22+1A>T') PosEdit(pos=22+1, edit=A>T, uncertain=False) >>> hp.parse_c_interval('22+1') Interval(start=22+1, end=22+1, uncertain=False) """ __default_grammar_fn = resource_filename(__name__, '_data/hgvs.pymeta') def __init__(self,grammar_fn=__default_grammar_fn): self._grammar_fn = grammar_fn self._grammar = parsley.makeGrammar(open(grammar_fn,'r').read(),{'hgvs': hgvs, 'bioutils': bioutils}) # define function attributes for each grammar rule, prefixed with 'parse_' # e.g., Parser.parse_c_interval('26+2_57-3') -> Interval(...) #TODO: exclude built-in rules self.rules = [ m.replace('rule_','') for m in dir(self._grammar._grammarClass) if m.startswith('rule_') ] for rule_name in self.rules: att_name = 'parse_' + rule_name rule_fxn = self.__make_parse_rule_function(rule_name) self.__setattr__(att_name,rule_fxn) def __make_parse_rule_function(self,rule_name): # http://docs.python.org/2/reference/datamodel.html#object.__getattr__ """ This function returns a function that takes a string and returns the parsing result. """ def rule_fxn(s): try: return self._grammar(s).__getattr__(rule_name)() except ometa.runtime.ParseError as exc: raise hgvs.exceptions.HGVSParseError, hgvs.exceptions.HGVSParseError("{s}: char {exc.position}: {reason}".format(s=s, exc=exc, reason=exc.formatReason())) rule_fxn.func_doc = "parse string s using `%s' rule" % rule_name return rule_fxn ## <LICENSE> ## Copyright 2014 HGVS Contributors (https://bitbucket.org/hgvs/hgvs) ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## </LICENSE>
0.725162
0.380327
from numpy import floor, meshgrid, multiply, divide, square, sqrt, pi, arange, log, pad, exp from numpy.fft import fftshift, ifftshift, fft2, ifft2 def Paganin(image, fresnel, beta_delta, zero_compensation = 0.01): """ This function makes the phase retrieval with Paganin method. Refer to the book: <NAME> - Biomedical imaging - 2017 for references Parameters __________ image : float32 2D image beta_delta: int absorption divided by refraction (decrements). Normally small, for ex. 0.08 fresnel : int Fresnel Number - can be calculated as fresnelN = pixelsize**2/(wavelength*object_detector_distance) zero_compensation: int just a parameter, should be small, for ex. 0.01 """ # set fourier coordinate system Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) k2 = (4*pi*fresnel)*beta_delta # formulate the equation nominator = 1 / (ifftshift(square(Qx)+square(Qy)) + k2) dvd = ifft2(multiply(fft2(image), nominator)).real phi_r = (1/(2 * beta_delta)) * log(k2 * dvd) return phi_r def MBA(image, fresnel, beta_delta, zero_compensation = 0.01): """ This function makes the phase retrieval with Modified Bronnikov Algorithm. Refer to the book: <NAME> - Biomedical imaging - 2017 for references Parameters __________ image : float32 2D image beta_delta: int absorption divided by refraction (decrements). Normally small, for ex. 0.08 fresnel : int Fresnel Number - can be calculated as fresnelN = pixelsize**2/(wavelength*object_detector_distance) zero_compensation: int just a parameter, should be small, for ex. 0.01 """ # set fourier coordinate system Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) k2 = (4*pi*fresnel)*beta_delta # formulate Modified Bronnikov formula nominator = 1 / (ifftshift(square(Qx)+square(Qy)) + k2) dvd = 2*pi*fresnel * ifft2(multiply(fft2(image-1), nominator)).real return dvd def BAC (image, fresnelNumber, alpha, gamma, zero_compensation = 0.01): """ This function makes the Bronnikov aided correction Please refer to the book of <NAME> "Biomedical imaging", 2017, ISBN = 978-3-11-042668-7, ISBN (PDF)= 978-3-11-0426694 equation 6.144 Parameters __________ image : float32 2D image beta_delta: int absorption divided by refraction (decrements). Normally small, for ex. 0.08 fresnel Number: int can be calculated as fresnelN = pixelsize**2/(wavelength*object_detector_distance) zero_compensation: int just a parameter, should be small, for ex. 0.01 """ gamma = gamma/fresnelNumber phi_r = MBA(image, fresnelNumber, alpha, zero_compensation) denominator = 1 - gamma * laplacian(phi_r) I0 = (divide(image, denominator)) return I0 def circle(x,y,r): """ This function creates a mask - 2D array with zeros outside a circular region and ones inside the circle. x is the xaxis of the coordinate system, y is the y axis. The third argument is the radius of the circle. Parameters __________ x : 1D array x axis y : 1D array y axis r: int radius of the mask circle """ X,Y = meshgrid(x,y) c = sqrt(square(X)+square(Y)) c[c<=r]=1 c[c>r]=0 return c def laplacian(image, Npad = None): """ This is Laplacian in fourier space Parameters __________ image: 2D arrat Npad: int number to pad the image """ if not Npad: Npad = [int(image.shape[0]/2), int(image.shape[1]/2)] # padding with border values image = pad(image, ((Npad[0], Npad[0]),(Npad[1], Npad[1])), 'edge') # coordinate system in fourier space Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) # fourier representation of laplacian filt = -fftshift(square(Qx)+square(Qy)) #filter itself out = ifft2(multiply(fft2(image),filt)) #undo padding and return result result = out[Npad[0]:(out.shape[0]-Npad[0]), Npad[1]:(out.shape[1]-Npad[1])].real return result def anka_filter(image, sigma, stabilizer, Npad = None): """ unsharp filter from ankaphase programm - called "image_restoration" there Parameters __________ image: 2D arrat sigma: float width of the gaussian kernel stabilizer: float small number Npad: int, optional number to pad the image """ if not Npad: Npad = [int(image.shape[0]/2), int(image.shape[1]/2)] # ============================================================================= # # padding with border values # image = pad(image, ((Npad[0], Npad[0]),(Npad[1], Npad[1])), 'edge') # ============================================================================= #set coordinate grid Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) #filtering nomin = 1 + stabilizer denomin = stabilizer + exp((-pi)*(sigma**2)*ifftshift(square(Qx)+square(Qy))) out = ifft2(multiply(fft2(image), divide(nomin, denomin))) #undo padding and return result #result = out[Npad[0]:(out.shape[0]-Npad[0]), Npad[1]:(out.shape[1]-Npad[1])].real result = out.real return result
maximus48/sidi_phare.py
from numpy import floor, meshgrid, multiply, divide, square, sqrt, pi, arange, log, pad, exp from numpy.fft import fftshift, ifftshift, fft2, ifft2 def Paganin(image, fresnel, beta_delta, zero_compensation = 0.01): """ This function makes the phase retrieval with Paganin method. Refer to the book: <NAME> - Biomedical imaging - 2017 for references Parameters __________ image : float32 2D image beta_delta: int absorption divided by refraction (decrements). Normally small, for ex. 0.08 fresnel : int Fresnel Number - can be calculated as fresnelN = pixelsize**2/(wavelength*object_detector_distance) zero_compensation: int just a parameter, should be small, for ex. 0.01 """ # set fourier coordinate system Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) k2 = (4*pi*fresnel)*beta_delta # formulate the equation nominator = 1 / (ifftshift(square(Qx)+square(Qy)) + k2) dvd = ifft2(multiply(fft2(image), nominator)).real phi_r = (1/(2 * beta_delta)) * log(k2 * dvd) return phi_r def MBA(image, fresnel, beta_delta, zero_compensation = 0.01): """ This function makes the phase retrieval with Modified Bronnikov Algorithm. Refer to the book: <NAME> - Biomedical imaging - 2017 for references Parameters __________ image : float32 2D image beta_delta: int absorption divided by refraction (decrements). Normally small, for ex. 0.08 fresnel : int Fresnel Number - can be calculated as fresnelN = pixelsize**2/(wavelength*object_detector_distance) zero_compensation: int just a parameter, should be small, for ex. 0.01 """ # set fourier coordinate system Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) k2 = (4*pi*fresnel)*beta_delta # formulate Modified Bronnikov formula nominator = 1 / (ifftshift(square(Qx)+square(Qy)) + k2) dvd = 2*pi*fresnel * ifft2(multiply(fft2(image-1), nominator)).real return dvd def BAC (image, fresnelNumber, alpha, gamma, zero_compensation = 0.01): """ This function makes the Bronnikov aided correction Please refer to the book of <NAME> "Biomedical imaging", 2017, ISBN = 978-3-11-042668-7, ISBN (PDF)= 978-3-11-0426694 equation 6.144 Parameters __________ image : float32 2D image beta_delta: int absorption divided by refraction (decrements). Normally small, for ex. 0.08 fresnel Number: int can be calculated as fresnelN = pixelsize**2/(wavelength*object_detector_distance) zero_compensation: int just a parameter, should be small, for ex. 0.01 """ gamma = gamma/fresnelNumber phi_r = MBA(image, fresnelNumber, alpha, zero_compensation) denominator = 1 - gamma * laplacian(phi_r) I0 = (divide(image, denominator)) return I0 def circle(x,y,r): """ This function creates a mask - 2D array with zeros outside a circular region and ones inside the circle. x is the xaxis of the coordinate system, y is the y axis. The third argument is the radius of the circle. Parameters __________ x : 1D array x axis y : 1D array y axis r: int radius of the mask circle """ X,Y = meshgrid(x,y) c = sqrt(square(X)+square(Y)) c[c<=r]=1 c[c>r]=0 return c def laplacian(image, Npad = None): """ This is Laplacian in fourier space Parameters __________ image: 2D arrat Npad: int number to pad the image """ if not Npad: Npad = [int(image.shape[0]/2), int(image.shape[1]/2)] # padding with border values image = pad(image, ((Npad[0], Npad[0]),(Npad[1], Npad[1])), 'edge') # coordinate system in fourier space Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) # fourier representation of laplacian filt = -fftshift(square(Qx)+square(Qy)) #filter itself out = ifft2(multiply(fft2(image),filt)) #undo padding and return result result = out[Npad[0]:(out.shape[0]-Npad[0]), Npad[1]:(out.shape[1]-Npad[1])].real return result def anka_filter(image, sigma, stabilizer, Npad = None): """ unsharp filter from ankaphase programm - called "image_restoration" there Parameters __________ image: 2D arrat sigma: float width of the gaussian kernel stabilizer: float small number Npad: int, optional number to pad the image """ if not Npad: Npad = [int(image.shape[0]/2), int(image.shape[1]/2)] # ============================================================================= # # padding with border values # image = pad(image, ((Npad[0], Npad[0]),(Npad[1], Npad[1])), 'edge') # ============================================================================= #set coordinate grid Ny = image.shape[0] Nx = image.shape[1] dqx = 2*pi/Nx dqy = 2*pi/Ny xx = arange(1,Nx+1)-floor(Nx/2)-1 yy = arange(1,Ny+1)-floor(Ny/2)-1 Qx, Qy = meshgrid(xx*dqx, yy*dqy) #filtering nomin = 1 + stabilizer denomin = stabilizer + exp((-pi)*(sigma**2)*ifftshift(square(Qx)+square(Qy))) out = ifft2(multiply(fft2(image), divide(nomin, denomin))) #undo padding and return result #result = out[Npad[0]:(out.shape[0]-Npad[0]), Npad[1]:(out.shape[1]-Npad[1])].real result = out.real return result
0.644225
0.574216
from typing import Dict import os from collections import OrderedDict from argparse import ArgumentParser, Namespace from multiprocessing import cpu_count import torch import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import pytorch_lightning.metrics.functional as plm from sagemaker_defect_detection import Classification, NEUCLS, get_transform from sagemaker_defect_detection.utils import load_checkpoint, freeze def metrics(name: str, out: torch.Tensor, target: torch.Tensor) -> Dict[str, torch.Tensor]: pred = torch.argmax(out, 1).detach() target = target.detach() metrics = {} metrics[name + "_acc"] = plm.accuracy(pred, target) metrics[name + "_prec"] = plm.precision(pred, target) metrics[name + "_recall"] = plm.recall(pred, target) metrics[name + "_f1_score"] = plm.recall(pred, target) return metrics class DDNClassification(pl.LightningModule): def __init__( self, data_path: str, backbone: str, freeze_backbone: bool, num_classes: int, learning_rate: float, batch_size: int, momentum: float, weight_decay: float, seed: int, **kwargs ) -> None: super().__init__() self.data_path = data_path self.backbone = backbone self.freeze_backbone = freeze_backbone self.num_classes = num_classes self.learning_rate = learning_rate self.batch_size = batch_size self.momentum = momentum self.weight_decay = weight_decay self.seed = seed self.train_dataset = NEUCLS(self.data_path, split="train", transform=get_transform("train"), seed=self.seed) self.val_dataset = NEUCLS(self.data_path, split="val", transform=get_transform("val"), seed=self.seed) self.test_dataset = NEUCLS(self.data_path, split="test", transform=get_transform("test"), seed=self.seed) self.model = Classification(self.backbone, self.num_classes) if self.freeze_backbone: for param in self.model.mfn.backbone.parameters(): param.requires_grad = False def forward(self, x): # ignore return self.model(x) def training_step(self, batch, batch_idx): images, target = batch output = self(images) loss_val = F.cross_entropy(output, target) metrics_dict = metrics("train", output, target) tqdm_dict = {"train_loss": loss_val, **metrics_dict} output = OrderedDict({"loss": loss_val, "progress_bar": tqdm_dict, "log": tqdm_dict}) return output def validation_step(self, batch, batch_idx): images, target = batch output = self(images) loss_val = F.cross_entropy(output, target) metrics_dict = metrics("val", output, target) output = OrderedDict({"val_loss": loss_val, **metrics_dict}) return output def validation_epoch_end(self, outputs): log_dict = {} for metric_name in outputs[0]: log_dict[metric_name] = torch.stack([x[metric_name] for x in outputs]).mean() return {"log": log_dict, "progress_bar": log_dict, **log_dict} def test_step(self, batch, batch_idx): images, target = batch output = self(images) loss_val = F.cross_entropy(output, target) metrics_dict = metrics("test", output, target) output = OrderedDict({"test_loss": loss_val, **metrics_dict}) return output def test_epoch_end(self, outputs): log_dict = {} for metric_name in outputs[0]: log_dict[metric_name] = torch.stack([x[metric_name] for x in outputs]).mean() return {"log": log_dict, "progress_bar": log_dict, **log_dict} def configure_optimizers(self): optimizer = optim.SGD( self.parameters(), lr=self.learning_rate, momentum=self.momentum, weight_decay=self.weight_decay ) return optimizer def train_dataloader(self): train_loader = DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=cpu_count(), ) return train_loader def val_dataloader(self): val_loader = DataLoader( self.val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=cpu_count() // 2, ) return val_loader def test_dataloader(self): test_loader = DataLoader( self.test_dataset, batch_size=self.batch_size, shuffle=False, num_workers=cpu_count(), ) return test_loader @staticmethod def add_model_specific_args(parent_parser): # pragma: no-cover parser = ArgumentParser(parents=[parent_parser], add_help=False) aa = parser.add_argument aa( "--data-path", metavar="DIR", type=str, default=os.getenv("SM_CHANNEL_TRAINING", ""), ) aa( "--backbone", default="resnet34", ) aa( "--freeze-backbone", action="store_true", ) aa( "--num-classes", default=6, type=int, metavar="N", ) aa( "-b", "--batch-size", default=64, type=int, metavar="N", ) aa( "--lr", "--learning-rate", default=1e-3, type=float, metavar="LR", dest="learning_rate", ) aa("--momentum", default=0.9, type=float, metavar="M", help="momentum") aa( "--wd", "--weight-decay", default=1e-4, type=float, metavar="W", dest="weight_decay", ) aa( "--seed", type=int, default=42, ) return parser def get_args() -> Namespace: parent_parser = ArgumentParser(add_help=False) aa = parent_parser.add_argument aa("--epochs", type=int, default=100, help="number of training epochs") aa("--save-path", metavar="DIR", default=os.getenv("SM_MODEL_DIR", ""), type=str, help="path to save output") aa("--gpus", type=int, default=os.getenv("SM_NUM_GPUS", 1), help="how many gpus") aa( "--distributed-backend", type=str, default="", choices=("dp", "ddp", "ddp2"), help="supports three options dp, ddp, ddp2", ) aa("--use-16bit", dest="use_16bit", action="store_true", help="if true uses 16 bit precision") parser = DDNClassification.add_model_specific_args(parent_parser) return parser.parse_args() def model_fn(model_dir): # TODO: `model_fn` doesn't get more args # see: https://github.com/aws/sagemaker-inference-toolkit/issues/65 backbone = "resnet34" num_classes = 6 model = load_checkpoint(Classification(backbone, num_classes), model_dir, prefix="model") model = model.eval() freeze(model) return model def main(args: Namespace) -> None: model = DDNClassification(**vars(args)) if args.seed is not None: pl.seed_everything(args.seed) if torch.cuda.device_count() > 1: torch.cuda.manual_seed_all(args.seed) # TODO: add deterministic training # torch.backends.cudnn.deterministic = True checkpoint_callback = ModelCheckpoint( filepath=os.path.join(args.save_path, "{epoch}-{val_loss:.3f}-{val_acc:.3f}"), save_top_k=1, verbose=True, monitor="val_acc", mode="max", ) early_stop_callback = EarlyStopping("val_loss", patience=10) trainer = pl.Trainer( default_root_dir=args.save_path, gpus=args.gpus, max_epochs=args.epochs, early_stop_callback=early_stop_callback, checkpoint_callback=checkpoint_callback, gradient_clip_val=10, num_sanity_val_steps=0, distributed_backend=args.distributed_backend or None, # precision=16 if args.use_16bit else 32, # TODO: amp apex support ) trainer.fit(model) trainer.test() return if __name__ == "__main__": main(get_args())
src/sagemaker_defect_detection/classifier.py
from typing import Dict import os from collections import OrderedDict from argparse import ArgumentParser, Namespace from multiprocessing import cpu_count import torch import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import pytorch_lightning.metrics.functional as plm from sagemaker_defect_detection import Classification, NEUCLS, get_transform from sagemaker_defect_detection.utils import load_checkpoint, freeze def metrics(name: str, out: torch.Tensor, target: torch.Tensor) -> Dict[str, torch.Tensor]: pred = torch.argmax(out, 1).detach() target = target.detach() metrics = {} metrics[name + "_acc"] = plm.accuracy(pred, target) metrics[name + "_prec"] = plm.precision(pred, target) metrics[name + "_recall"] = plm.recall(pred, target) metrics[name + "_f1_score"] = plm.recall(pred, target) return metrics class DDNClassification(pl.LightningModule): def __init__( self, data_path: str, backbone: str, freeze_backbone: bool, num_classes: int, learning_rate: float, batch_size: int, momentum: float, weight_decay: float, seed: int, **kwargs ) -> None: super().__init__() self.data_path = data_path self.backbone = backbone self.freeze_backbone = freeze_backbone self.num_classes = num_classes self.learning_rate = learning_rate self.batch_size = batch_size self.momentum = momentum self.weight_decay = weight_decay self.seed = seed self.train_dataset = NEUCLS(self.data_path, split="train", transform=get_transform("train"), seed=self.seed) self.val_dataset = NEUCLS(self.data_path, split="val", transform=get_transform("val"), seed=self.seed) self.test_dataset = NEUCLS(self.data_path, split="test", transform=get_transform("test"), seed=self.seed) self.model = Classification(self.backbone, self.num_classes) if self.freeze_backbone: for param in self.model.mfn.backbone.parameters(): param.requires_grad = False def forward(self, x): # ignore return self.model(x) def training_step(self, batch, batch_idx): images, target = batch output = self(images) loss_val = F.cross_entropy(output, target) metrics_dict = metrics("train", output, target) tqdm_dict = {"train_loss": loss_val, **metrics_dict} output = OrderedDict({"loss": loss_val, "progress_bar": tqdm_dict, "log": tqdm_dict}) return output def validation_step(self, batch, batch_idx): images, target = batch output = self(images) loss_val = F.cross_entropy(output, target) metrics_dict = metrics("val", output, target) output = OrderedDict({"val_loss": loss_val, **metrics_dict}) return output def validation_epoch_end(self, outputs): log_dict = {} for metric_name in outputs[0]: log_dict[metric_name] = torch.stack([x[metric_name] for x in outputs]).mean() return {"log": log_dict, "progress_bar": log_dict, **log_dict} def test_step(self, batch, batch_idx): images, target = batch output = self(images) loss_val = F.cross_entropy(output, target) metrics_dict = metrics("test", output, target) output = OrderedDict({"test_loss": loss_val, **metrics_dict}) return output def test_epoch_end(self, outputs): log_dict = {} for metric_name in outputs[0]: log_dict[metric_name] = torch.stack([x[metric_name] for x in outputs]).mean() return {"log": log_dict, "progress_bar": log_dict, **log_dict} def configure_optimizers(self): optimizer = optim.SGD( self.parameters(), lr=self.learning_rate, momentum=self.momentum, weight_decay=self.weight_decay ) return optimizer def train_dataloader(self): train_loader = DataLoader( dataset=self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=cpu_count(), ) return train_loader def val_dataloader(self): val_loader = DataLoader( self.val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=cpu_count() // 2, ) return val_loader def test_dataloader(self): test_loader = DataLoader( self.test_dataset, batch_size=self.batch_size, shuffle=False, num_workers=cpu_count(), ) return test_loader @staticmethod def add_model_specific_args(parent_parser): # pragma: no-cover parser = ArgumentParser(parents=[parent_parser], add_help=False) aa = parser.add_argument aa( "--data-path", metavar="DIR", type=str, default=os.getenv("SM_CHANNEL_TRAINING", ""), ) aa( "--backbone", default="resnet34", ) aa( "--freeze-backbone", action="store_true", ) aa( "--num-classes", default=6, type=int, metavar="N", ) aa( "-b", "--batch-size", default=64, type=int, metavar="N", ) aa( "--lr", "--learning-rate", default=1e-3, type=float, metavar="LR", dest="learning_rate", ) aa("--momentum", default=0.9, type=float, metavar="M", help="momentum") aa( "--wd", "--weight-decay", default=1e-4, type=float, metavar="W", dest="weight_decay", ) aa( "--seed", type=int, default=42, ) return parser def get_args() -> Namespace: parent_parser = ArgumentParser(add_help=False) aa = parent_parser.add_argument aa("--epochs", type=int, default=100, help="number of training epochs") aa("--save-path", metavar="DIR", default=os.getenv("SM_MODEL_DIR", ""), type=str, help="path to save output") aa("--gpus", type=int, default=os.getenv("SM_NUM_GPUS", 1), help="how many gpus") aa( "--distributed-backend", type=str, default="", choices=("dp", "ddp", "ddp2"), help="supports three options dp, ddp, ddp2", ) aa("--use-16bit", dest="use_16bit", action="store_true", help="if true uses 16 bit precision") parser = DDNClassification.add_model_specific_args(parent_parser) return parser.parse_args() def model_fn(model_dir): # TODO: `model_fn` doesn't get more args # see: https://github.com/aws/sagemaker-inference-toolkit/issues/65 backbone = "resnet34" num_classes = 6 model = load_checkpoint(Classification(backbone, num_classes), model_dir, prefix="model") model = model.eval() freeze(model) return model def main(args: Namespace) -> None: model = DDNClassification(**vars(args)) if args.seed is not None: pl.seed_everything(args.seed) if torch.cuda.device_count() > 1: torch.cuda.manual_seed_all(args.seed) # TODO: add deterministic training # torch.backends.cudnn.deterministic = True checkpoint_callback = ModelCheckpoint( filepath=os.path.join(args.save_path, "{epoch}-{val_loss:.3f}-{val_acc:.3f}"), save_top_k=1, verbose=True, monitor="val_acc", mode="max", ) early_stop_callback = EarlyStopping("val_loss", patience=10) trainer = pl.Trainer( default_root_dir=args.save_path, gpus=args.gpus, max_epochs=args.epochs, early_stop_callback=early_stop_callback, checkpoint_callback=checkpoint_callback, gradient_clip_val=10, num_sanity_val_steps=0, distributed_backend=args.distributed_backend or None, # precision=16 if args.use_16bit else 32, # TODO: amp apex support ) trainer.fit(model) trainer.test() return if __name__ == "__main__": main(get_args())
0.924266
0.368008
import turtle import scoreboard import players import balls import time GAME_SCREEN_WIDTH = 800 GAME_SCREEN_HEIGHT = 600 game_screen = turtle.Screen() game_screen.setup(width=GAME_SCREEN_WIDTH, height=GAME_SCREEN_HEIGHT) game_screen.bgcolor("black") game_screen.title("PONG") game_screen.tracer(0) divider = turtle.Turtle() divider.up() divider.goto(0, int(GAME_SCREEN_HEIGHT / 2)) divider.down() divider.ht() divider.color("grey") divider.width(3) divider.setheading(270) for i in range(1, GAME_SCREEN_HEIGHT, 10): if divider.isdown(): divider.up() else: divider.down() divider.forward(10) left_score = scoreboard.Scoreboard((-40, int(GAME_SCREEN_HEIGHT/2) - 60)) right_score = scoreboard.Scoreboard((40, int(GAME_SCREEN_HEIGHT/2) - 60)) left_player = players.Player((-int(GAME_SCREEN_WIDTH/2) + 50, 0)) right_player = players.Player((int(GAME_SCREEN_WIDTH/2) - 50, 0)) max_score = int(game_screen.textinput("SCORE TO WIN", "Put maximum score to win the game: ")) game_screen.onkey(left_player.move_up, "w") game_screen.onkey(left_player.move_down, "s") game_screen.onkey(right_player.move_up, "Up") game_screen.onkey(right_player.move_down, "Down") game_screen.listen() game_ball = balls.Ball() game_screen.update() is_game_restart = False while True: if game_ball.ycor() >= 290 or game_ball.ycor() <= - 290: """When ball hit upper and lower wall""" game_ball.bounce_y() if game_ball.distance(right_player) < 50 and game_ball.xcor() > 320 or game_ball.distance(left_player) < 50 and game_ball.xcor() < -320: """When ball hit player's paddle""" game_ball.bounce_x() game_ball.increase_speed() if game_ball.xcor() > int(GAME_SCREEN_WIDTH/2): """When right player failed to bounce the ball""" left_score.score += 1 left_score.write_score() is_game_restart = True if game_ball.xcor() < -int(GAME_SCREEN_WIDTH/2): """When left player failed to bounce the ball""" right_score.score += 1 right_score.write_score() is_game_restart = True if is_game_restart: if left_score.score >= max_score or right_score.score >= max_score: break is_game_restart = False game_ball.bounce_x() game_ball.reset() time.sleep(1) continue game_ball.move() game_screen.update() time.sleep(game_ball.move_speed) winner_player = "left" if right_score.score == max_score: winner_player = "right" winner = turtle.Turtle() winner.color("white") winner.ht() winner.up() winner.write(f"{winner_player.upper()} WIN!", align="center", font=("Courier", 45, "normal")) game_screen.exitonclick()
day_22/main.py
import turtle import scoreboard import players import balls import time GAME_SCREEN_WIDTH = 800 GAME_SCREEN_HEIGHT = 600 game_screen = turtle.Screen() game_screen.setup(width=GAME_SCREEN_WIDTH, height=GAME_SCREEN_HEIGHT) game_screen.bgcolor("black") game_screen.title("PONG") game_screen.tracer(0) divider = turtle.Turtle() divider.up() divider.goto(0, int(GAME_SCREEN_HEIGHT / 2)) divider.down() divider.ht() divider.color("grey") divider.width(3) divider.setheading(270) for i in range(1, GAME_SCREEN_HEIGHT, 10): if divider.isdown(): divider.up() else: divider.down() divider.forward(10) left_score = scoreboard.Scoreboard((-40, int(GAME_SCREEN_HEIGHT/2) - 60)) right_score = scoreboard.Scoreboard((40, int(GAME_SCREEN_HEIGHT/2) - 60)) left_player = players.Player((-int(GAME_SCREEN_WIDTH/2) + 50, 0)) right_player = players.Player((int(GAME_SCREEN_WIDTH/2) - 50, 0)) max_score = int(game_screen.textinput("SCORE TO WIN", "Put maximum score to win the game: ")) game_screen.onkey(left_player.move_up, "w") game_screen.onkey(left_player.move_down, "s") game_screen.onkey(right_player.move_up, "Up") game_screen.onkey(right_player.move_down, "Down") game_screen.listen() game_ball = balls.Ball() game_screen.update() is_game_restart = False while True: if game_ball.ycor() >= 290 or game_ball.ycor() <= - 290: """When ball hit upper and lower wall""" game_ball.bounce_y() if game_ball.distance(right_player) < 50 and game_ball.xcor() > 320 or game_ball.distance(left_player) < 50 and game_ball.xcor() < -320: """When ball hit player's paddle""" game_ball.bounce_x() game_ball.increase_speed() if game_ball.xcor() > int(GAME_SCREEN_WIDTH/2): """When right player failed to bounce the ball""" left_score.score += 1 left_score.write_score() is_game_restart = True if game_ball.xcor() < -int(GAME_SCREEN_WIDTH/2): """When left player failed to bounce the ball""" right_score.score += 1 right_score.write_score() is_game_restart = True if is_game_restart: if left_score.score >= max_score or right_score.score >= max_score: break is_game_restart = False game_ball.bounce_x() game_ball.reset() time.sleep(1) continue game_ball.move() game_screen.update() time.sleep(game_ball.move_speed) winner_player = "left" if right_score.score == max_score: winner_player = "right" winner = turtle.Turtle() winner.color("white") winner.ht() winner.up() winner.write(f"{winner_player.upper()} WIN!", align="center", font=("Courier", 45, "normal")) game_screen.exitonclick()
0.33231
0.072637
import os import numpy as np import pandas as pd from joblib import Parallel, delayed import tensorflow as tf import sklearn from functools import partial from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer, Dense from rdkit import Chem from rdkit.Chem import AllChem def ranks_to_acc(found_at_rank, fid=None): def fprint(txt): # print(txt) if fid is not None: fid.write(txt + '\n') tot = float(len(found_at_rank)) fprint('{:>8} \t {:>8}'.format('top-n', 'accuracy')) accs = [] for n in [1, 3, 5, 10, 20, 50]: accs.append(sum([r <= n for r in found_at_rank]) / tot) fprint('{:>8} \t {:>8}'.format(n, accs[-1])) return accs def average_recalls(recalls,fid=None): average_recalls={} for k in [1, 5, 10, 25, 50, 100]: tmp=0 for recall in recalls: tmp+=recall[k] tmp/=len(recalls) average_recalls[k]=tmp if fid is not None: fid.write(str(average_recalls)) return average_recalls def topk_appl_recall(applicable, k=[1, 5, 10, 25, 50, 100]): recall = {} for kval in k: recall[kval]=sum(applicable[:kval])/kval return recall def loop_over_temps(template, rct): from rdchiral.main import rdchiralRun, rdchiralReaction, rdchiralReactants rct = rdchiralReactants(rct) try: rxn = rdchiralReaction(template) outcomes = rdchiralRun(rxn, rct, combine_enantiomers=False) except Exception as e: outcomes = [] return outcomes def get_rank_precursor_multi(prob_list,smi,prec_goal,templates,n_cpus): sorted_idx=list(np.argsort(prob_list)[::-1]) ranks=[9999] rank=9999 applicable=[] num_prev_prec = 0 known_prec=set() outcomes_all = Parallel(n_jobs=n_cpus, verbose=0)(delayed(loop_over_temps)(templates[idx],smi) for idx in sorted_idx[:100]) for r,idx in enumerate(sorted_idx[:100]): outcomes=outcomes_all[r] num_duplicates=sum([item in known_prec for item in outcomes]) if prec_goal in outcomes: ranks = [num_prev_prec+1+i for i in range(len(outcomes)-num_duplicates)] rank=r+1 break num_prev_prec += len(outcomes)-num_duplicates known_prec.update(outcomes) for r,idx in enumerate(sorted_idx[:100]): outcomes=outcomes_all[r] if len(outcomes)!=0: applicable.append(1) else: applicable.append(0) recall=topk_appl_recall(applicable) return ranks,rank,recall def get_multi_accs(found_at_ranks, fid=None): summed_up_accs=np.zeros((6)) for item in found_at_ranks: accs=ranks_to_acc(item) summed_up_accs+=np.array(accs) accs=summed_up_accs/len(found_at_ranks) if fid is not None: fid.write(str(accs)) return accs def smiles_to_fingerprint(smi, length=2048, radius=2, useFeatures=False, useChirality=True): mol = Chem.MolFromSmiles(smi) if not mol: raise ValueError('Cannot parse {}'.format(smi)) fp_bit = AllChem.GetMorganFingerprintAsBitVect( mol=mol, radius=radius, nBits = length, useFeatures=useFeatures, useChirality=useChirality ) return np.array(fp_bit) def fingerprint_training_dataset( smiles, labels, batch_size=256, train=True, fp_length=2048, fp_radius=2, fp_use_features=False, fp_use_chirality=True, sparse_labels=False, shuffle_buffer=1024, nproc=8, cache=True, precompute=False ): smiles_ds = fingerprint_dataset_from_smiles(smiles, fp_length, fp_radius, fp_use_features, fp_use_chirality, nproc, precompute) labels_ds = labels_dataset(labels, sparse_labels) ds = tf.data.Dataset.zip((smiles_ds, labels_ds)) ds = ds.shuffle(shuffle_buffer).batch(batch_size) if train: ds = ds.repeat() if cache: ds = ds.cache() ds = ds.prefetch(buffer_size=batch_size*3) return ds def fingerprint_dataset_from_smiles(smiles, length, radius, useFeatures, useChirality, nproc=8, precompute=False): def smiles_tensor_to_fp(smi, length, radius, useFeatures, useChirality): smi = smi.numpy().decode('utf-8') length = int(length.numpy()) radius = int(radius.numpy()) useFeatures = bool(useFeatures.numpy()) useChirality = bool(useChirality.numpy()) fp_bit = smiles_to_fingerprint(smi, length, radius, useFeatures, useChirality) return np.array(fp_bit) def parse_smiles(smi): output = tf.py_function( smiles_tensor_to_fp, inp=[smi, length, radius, useFeatures, useChirality], Tout=tf.float32 ) output.set_shape((length,)) return output if not precompute: ds = tf.data.Dataset.from_tensor_slices(smiles) ds = ds.map(map_func=parse_smiles, num_parallel_calls=nproc) else: if nproc!=0: fps = Parallel(n_jobs=nproc, verbose=1)( delayed(smiles_to_fingerprint)(smi, length, radius, useFeatures, useChirality) for smi in smiles ) else: fps = [smiles_to_fingerprint(smi, length, radius, useFeatures, useChirality) for smi in smiles] fps = np.array(fps) ds = tf.data.Dataset.from_tensor_slices(fps) return ds def labels_dataset(labels, sparse=False): if not sparse: return tf.data.Dataset.from_tensor_slices(labels) coo = labels.tocoo() indices = np.array([coo.row, coo.col]).T labels = tf.SparseTensor(indices, coo.data, coo.shape) labels_ds = tf.data.Dataset.from_tensor_slices(labels) labels_ds = labels_ds.map(map_func=tf.sparse.to_dense) return labels_ds def sparse_categorical_crossentropy_from_logits(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) def top_k(k=1): partial_fn = partial(tf.keras.metrics.sparse_top_k_categorical_accuracy, k=k) partial_fn.__name__ = 'top_{}'.format(k) return partial_fn def build_model( input_shape, output_shape, num_hidden, hidden_size, activation='relu', output_activation=None, dropout=0.0, clipnorm=None, optimizer=None, learning_rate=0.001, compile_model=True, loss=None, metrics=None ): model = tf.keras.models.Sequential() model.add(tf.keras.layers.Input(input_shape)) for _ in range(num_hidden): model.add(tf.keras.layers.Dense(hidden_size, activation=activation)) if dropout: model.add(tf.keras.layers.Dropout(dropout)) model.add(tf.keras.layers.Dense(output_shape, activation=output_activation)) if optimizer is None or optimizer == 'adam': optimizer = tf.keras.optimizers.Adam(learning_rate) if clipnorm is not None: optimizer.clipnorm = clipnorm if compile_model: model.compile( optimizer=optimizer, loss=loss, metrics=metrics ) return model def relevance(**kwargs): loss = sparse_categorical_crossentropy_from_logits metrics = [ top_k(k=1), top_k(k=3), top_k(k=5), top_k(k=10), top_k(k=20), top_k(k=50), ] options = { 'loss': loss, 'metrics': metrics } options.update(kwargs) return build_model(**options) def shuffle_arrays(a, b): p = np.random.permutation(len(a)) return a[p], b[p] def train_model(num_classes,train_smiles,train_labels,valid_smiles,valid_labels,test_smiles,test_labels,model_name1, model_name2,n_cpus): #Hyperparameters: fp_length=2048 fp_radius=2 weight_classes=True num_hidden=1 hidden_size=2048 dropout=0.2 learning_rate=0.001 activation='relu' batch_size=512 clipnorm=None epochs=25 early_stopping=3 nproc=n_cpus precompute_fps=True train_smiles, train_labels = shuffle_arrays(train_smiles, train_labels) valid_smiles, valid_labels = shuffle_arrays(valid_smiles, valid_labels) train_ds = fingerprint_training_dataset( train_smiles, train_labels, batch_size=batch_size, train=True, fp_length=fp_length, fp_radius=fp_radius, nproc=nproc, precompute=precompute_fps ) train_steps = np.ceil(len(train_smiles)/batch_size).astype(int) valid_ds = fingerprint_training_dataset( valid_smiles, valid_labels, batch_size=batch_size, train=False, fp_length=fp_length, fp_radius=fp_radius, nproc=nproc, precompute=precompute_fps ) valid_steps = np.ceil(len(valid_smiles)/batch_size).astype(int) #Setup model details model = relevance( input_shape=(fp_length,), output_shape=num_classes, num_hidden=num_hidden, hidden_size=hidden_size, dropout=dropout, learning_rate=learning_rate, activation=activation, clipnorm=clipnorm ) if not os.path.exists('models/ml-fixed/training_'+model_name1): os.makedirs('models/ml-fixed/training_'+model_name1) model_output = 'models/ml-fixed/training_'+model_name1+'/'+model_name2+'-weights.hdf5' history_output = 'models/ml-fixed/training_'+model_name1+'/'+model_name2+'-history.json' callbacks = [] if early_stopping: callbacks.append( tf.keras.callbacks.EarlyStopping( patience=early_stopping, restore_best_weights=True ) ) callbacks.append( tf.keras.callbacks.ModelCheckpoint( model_output, monitor='val_loss', save_weights_only=True ) ) if weight_classes: class_weight = sklearn.utils.class_weight.compute_class_weight( 'balanced', np.unique(train_labels), train_labels ) else: class_weight = sklearn.utils.class_weight.compute_class_weight( None, np.unique(train_labels), train_labels ) if nproc !=0 : multiproc = True nproc = nproc else: multiproc = False nproc = None length = len(np.unique(train_labels)) class_weight_dict = {i : class_weight[i] for i in range(length)} #Train neural network history = model.fit( train_ds, epochs=epochs, steps_per_epoch=train_steps, validation_data=valid_ds, validation_steps=valid_steps, callbacks=callbacks, class_weight=class_weight_dict, use_multiprocessing=multiproc, workers=nproc ) pd.DataFrame(history.history).to_json(history_output) #Predict on test set: if nproc!=0: test_fps = Parallel(n_jobs=nproc, verbose=1)( delayed(smiles_to_fingerprint)(smi, length=fp_length, radius=fp_radius) for smi in test_smiles ) else: test_fps = [smiles_to_fingerprint(smi, length=fp_length, radius=fp_radius) for smi in test_smiles] test_fps = np.array(test_fps) acc = model.evaluate(test_fps, test_labels, batch_size=batch_size) print(model.metrics_names[1:]) print(acc[1:]) with open('models/ml-fixed/evaluation_'+model_name1+'/'+model_name2+'_accuracy_t.out','w') as f: print(model.metrics_names[1:],file=f) print(acc[1:],file=f) return model,batch_size,test_fps def ml_fixed_model(system,n_cpus=20): for name in ["","canonical_","corrected_","canonical_corrected_"]: print("###",name) if not os.path.exists('models/ml-fixed/evaluation_'+name+system): os.makedirs('models/ml-fixed/evaluation_'+name+system) if name in ["","canonical_"]: choices= ["default","r0","r1","r2","r3"] else: choices=["default","r1","r2","r3"] #Reverse for i in choices: num_classes = int(np.load("data/"+system+"num_classes_"+name+"template_"+i+".npy")) print("Training model ("+i+" templates, retro) with",num_classes,"classes:") data_train=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_train.csv") data_val=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_val.csv") data_test=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_test.csv") train_smiles=data_train['prod_smiles'].values train_labels=data_train[name+"template_"+i+"_id"].values valid_smiles=data_val['prod_smiles'].values valid_labels=data_val[name+"template_"+i+"_id"].values test_smiles=data_test['prod_smiles'].values test_labels=data_test[name+"template_"+i+"_id"].values model,batch_size,test_fps = train_model(num_classes,train_smiles,train_labels,valid_smiles,valid_labels,test_smiles,test_labels,name+system,i+"_retro",n_cpus) #Check precursor evaluation: data_test=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_test.csv") forward_test_smiles=data_test['reac_smiles'].values templates=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_unique_templates.txt",header=None)[0].values preds=model.predict(test_fps,batch_size=batch_size) #Calculate ranks found_at_rank = [] found_at_ranks = [] recalls=[] for j in range(len(test_labels)): print(j, end='\r') found_ranks,found_rank,recall=get_rank_precursor_multi(preds[j],test_smiles[j],forward_test_smiles[j],templates, n_cpus) found_at_rank.append(found_rank) found_at_ranks.append(found_ranks) recalls.append(recall) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p.out','w') as fid: accs=ranks_to_acc(found_at_rank,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p_multi.out','w') as fid: accs_multi=get_multi_accs(found_at_ranks,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/appl__retro_template_'+i+'.out','w') as fid: mean_recall=average_recalls(recalls,fid=fid) print("Via precursor:") print(accs) print(mean_recall) print("Via precursor (multi):") print(accs_multi) #Forward for i in choices: num_classes = int(np.load("data/"+system+"num_classes_forward_"+name+"template_"+i+".npy")) print("Training model ("+i+" templates, forward) with",num_classes,"classes:") data_train=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_train.csv") data_val=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_val.csv") data_test=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_test.csv") train_smiles=data_train['reac_smiles'].values train_labels=data_train['forward_'+name+"template_"+i+"_id"].values valid_smiles=data_val['reac_smiles'].values valid_labels=data_val['forward_'+name+"template_"+i+"_id"].values test_smiles=data_test['reac_smiles'].values test_labels=data_test['forward_'+name+"template_"+i+"_id"].values model,batch_size,test_fps = train_model(num_classes,train_smiles,train_labels,valid_smiles,valid_labels,test_smiles,test_labels,name+system,i+"_forward", n_cpus) #Check precursor evaluation: data_test=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_test.csv") forward_test_smiles=data_test['prod_smiles'].values templates=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_unique_templates.txt",header=None)[0].values preds=model.predict(test_fps,batch_size=batch_size) #Calculate ranks found_at_rank = [] found_at_ranks = [] recalls=[] for j in range(len(test_labels)): print(j, end='\r') found_ranks,found_rank,recall=get_rank_precursor_multi(preds[j],test_smiles[j],forward_test_smiles[j],templates, n_cpus) found_at_rank.append(found_rank) found_at_ranks.append(found_ranks) recalls.append(recall) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p.out','w') as fid: accs=ranks_to_acc(found_at_rank,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p_multi.out','w') as fid: accs_multi=get_multi_accs(found_at_ranks,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/appl__retro_template_'+i+'.out','w') as fid: mean_recall=average_recalls(recalls,fid=fid) print("Via precursor:") print(accs) print(mean_recall) print("Via precursor (multi):") print(accs_multi) if __name__ == '__main__': ml_fixed_model('uspto_50k') #ml_fixed_model('uspto_460k')
scripts/04_ml_fixed_model.py
import os import numpy as np import pandas as pd from joblib import Parallel, delayed import tensorflow as tf import sklearn from functools import partial from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer, Dense from rdkit import Chem from rdkit.Chem import AllChem def ranks_to_acc(found_at_rank, fid=None): def fprint(txt): # print(txt) if fid is not None: fid.write(txt + '\n') tot = float(len(found_at_rank)) fprint('{:>8} \t {:>8}'.format('top-n', 'accuracy')) accs = [] for n in [1, 3, 5, 10, 20, 50]: accs.append(sum([r <= n for r in found_at_rank]) / tot) fprint('{:>8} \t {:>8}'.format(n, accs[-1])) return accs def average_recalls(recalls,fid=None): average_recalls={} for k in [1, 5, 10, 25, 50, 100]: tmp=0 for recall in recalls: tmp+=recall[k] tmp/=len(recalls) average_recalls[k]=tmp if fid is not None: fid.write(str(average_recalls)) return average_recalls def topk_appl_recall(applicable, k=[1, 5, 10, 25, 50, 100]): recall = {} for kval in k: recall[kval]=sum(applicable[:kval])/kval return recall def loop_over_temps(template, rct): from rdchiral.main import rdchiralRun, rdchiralReaction, rdchiralReactants rct = rdchiralReactants(rct) try: rxn = rdchiralReaction(template) outcomes = rdchiralRun(rxn, rct, combine_enantiomers=False) except Exception as e: outcomes = [] return outcomes def get_rank_precursor_multi(prob_list,smi,prec_goal,templates,n_cpus): sorted_idx=list(np.argsort(prob_list)[::-1]) ranks=[9999] rank=9999 applicable=[] num_prev_prec = 0 known_prec=set() outcomes_all = Parallel(n_jobs=n_cpus, verbose=0)(delayed(loop_over_temps)(templates[idx],smi) for idx in sorted_idx[:100]) for r,idx in enumerate(sorted_idx[:100]): outcomes=outcomes_all[r] num_duplicates=sum([item in known_prec for item in outcomes]) if prec_goal in outcomes: ranks = [num_prev_prec+1+i for i in range(len(outcomes)-num_duplicates)] rank=r+1 break num_prev_prec += len(outcomes)-num_duplicates known_prec.update(outcomes) for r,idx in enumerate(sorted_idx[:100]): outcomes=outcomes_all[r] if len(outcomes)!=0: applicable.append(1) else: applicable.append(0) recall=topk_appl_recall(applicable) return ranks,rank,recall def get_multi_accs(found_at_ranks, fid=None): summed_up_accs=np.zeros((6)) for item in found_at_ranks: accs=ranks_to_acc(item) summed_up_accs+=np.array(accs) accs=summed_up_accs/len(found_at_ranks) if fid is not None: fid.write(str(accs)) return accs def smiles_to_fingerprint(smi, length=2048, radius=2, useFeatures=False, useChirality=True): mol = Chem.MolFromSmiles(smi) if not mol: raise ValueError('Cannot parse {}'.format(smi)) fp_bit = AllChem.GetMorganFingerprintAsBitVect( mol=mol, radius=radius, nBits = length, useFeatures=useFeatures, useChirality=useChirality ) return np.array(fp_bit) def fingerprint_training_dataset( smiles, labels, batch_size=256, train=True, fp_length=2048, fp_radius=2, fp_use_features=False, fp_use_chirality=True, sparse_labels=False, shuffle_buffer=1024, nproc=8, cache=True, precompute=False ): smiles_ds = fingerprint_dataset_from_smiles(smiles, fp_length, fp_radius, fp_use_features, fp_use_chirality, nproc, precompute) labels_ds = labels_dataset(labels, sparse_labels) ds = tf.data.Dataset.zip((smiles_ds, labels_ds)) ds = ds.shuffle(shuffle_buffer).batch(batch_size) if train: ds = ds.repeat() if cache: ds = ds.cache() ds = ds.prefetch(buffer_size=batch_size*3) return ds def fingerprint_dataset_from_smiles(smiles, length, radius, useFeatures, useChirality, nproc=8, precompute=False): def smiles_tensor_to_fp(smi, length, radius, useFeatures, useChirality): smi = smi.numpy().decode('utf-8') length = int(length.numpy()) radius = int(radius.numpy()) useFeatures = bool(useFeatures.numpy()) useChirality = bool(useChirality.numpy()) fp_bit = smiles_to_fingerprint(smi, length, radius, useFeatures, useChirality) return np.array(fp_bit) def parse_smiles(smi): output = tf.py_function( smiles_tensor_to_fp, inp=[smi, length, radius, useFeatures, useChirality], Tout=tf.float32 ) output.set_shape((length,)) return output if not precompute: ds = tf.data.Dataset.from_tensor_slices(smiles) ds = ds.map(map_func=parse_smiles, num_parallel_calls=nproc) else: if nproc!=0: fps = Parallel(n_jobs=nproc, verbose=1)( delayed(smiles_to_fingerprint)(smi, length, radius, useFeatures, useChirality) for smi in smiles ) else: fps = [smiles_to_fingerprint(smi, length, radius, useFeatures, useChirality) for smi in smiles] fps = np.array(fps) ds = tf.data.Dataset.from_tensor_slices(fps) return ds def labels_dataset(labels, sparse=False): if not sparse: return tf.data.Dataset.from_tensor_slices(labels) coo = labels.tocoo() indices = np.array([coo.row, coo.col]).T labels = tf.SparseTensor(indices, coo.data, coo.shape) labels_ds = tf.data.Dataset.from_tensor_slices(labels) labels_ds = labels_ds.map(map_func=tf.sparse.to_dense) return labels_ds def sparse_categorical_crossentropy_from_logits(labels, logits): return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) def top_k(k=1): partial_fn = partial(tf.keras.metrics.sparse_top_k_categorical_accuracy, k=k) partial_fn.__name__ = 'top_{}'.format(k) return partial_fn def build_model( input_shape, output_shape, num_hidden, hidden_size, activation='relu', output_activation=None, dropout=0.0, clipnorm=None, optimizer=None, learning_rate=0.001, compile_model=True, loss=None, metrics=None ): model = tf.keras.models.Sequential() model.add(tf.keras.layers.Input(input_shape)) for _ in range(num_hidden): model.add(tf.keras.layers.Dense(hidden_size, activation=activation)) if dropout: model.add(tf.keras.layers.Dropout(dropout)) model.add(tf.keras.layers.Dense(output_shape, activation=output_activation)) if optimizer is None or optimizer == 'adam': optimizer = tf.keras.optimizers.Adam(learning_rate) if clipnorm is not None: optimizer.clipnorm = clipnorm if compile_model: model.compile( optimizer=optimizer, loss=loss, metrics=metrics ) return model def relevance(**kwargs): loss = sparse_categorical_crossentropy_from_logits metrics = [ top_k(k=1), top_k(k=3), top_k(k=5), top_k(k=10), top_k(k=20), top_k(k=50), ] options = { 'loss': loss, 'metrics': metrics } options.update(kwargs) return build_model(**options) def shuffle_arrays(a, b): p = np.random.permutation(len(a)) return a[p], b[p] def train_model(num_classes,train_smiles,train_labels,valid_smiles,valid_labels,test_smiles,test_labels,model_name1, model_name2,n_cpus): #Hyperparameters: fp_length=2048 fp_radius=2 weight_classes=True num_hidden=1 hidden_size=2048 dropout=0.2 learning_rate=0.001 activation='relu' batch_size=512 clipnorm=None epochs=25 early_stopping=3 nproc=n_cpus precompute_fps=True train_smiles, train_labels = shuffle_arrays(train_smiles, train_labels) valid_smiles, valid_labels = shuffle_arrays(valid_smiles, valid_labels) train_ds = fingerprint_training_dataset( train_smiles, train_labels, batch_size=batch_size, train=True, fp_length=fp_length, fp_radius=fp_radius, nproc=nproc, precompute=precompute_fps ) train_steps = np.ceil(len(train_smiles)/batch_size).astype(int) valid_ds = fingerprint_training_dataset( valid_smiles, valid_labels, batch_size=batch_size, train=False, fp_length=fp_length, fp_radius=fp_radius, nproc=nproc, precompute=precompute_fps ) valid_steps = np.ceil(len(valid_smiles)/batch_size).astype(int) #Setup model details model = relevance( input_shape=(fp_length,), output_shape=num_classes, num_hidden=num_hidden, hidden_size=hidden_size, dropout=dropout, learning_rate=learning_rate, activation=activation, clipnorm=clipnorm ) if not os.path.exists('models/ml-fixed/training_'+model_name1): os.makedirs('models/ml-fixed/training_'+model_name1) model_output = 'models/ml-fixed/training_'+model_name1+'/'+model_name2+'-weights.hdf5' history_output = 'models/ml-fixed/training_'+model_name1+'/'+model_name2+'-history.json' callbacks = [] if early_stopping: callbacks.append( tf.keras.callbacks.EarlyStopping( patience=early_stopping, restore_best_weights=True ) ) callbacks.append( tf.keras.callbacks.ModelCheckpoint( model_output, monitor='val_loss', save_weights_only=True ) ) if weight_classes: class_weight = sklearn.utils.class_weight.compute_class_weight( 'balanced', np.unique(train_labels), train_labels ) else: class_weight = sklearn.utils.class_weight.compute_class_weight( None, np.unique(train_labels), train_labels ) if nproc !=0 : multiproc = True nproc = nproc else: multiproc = False nproc = None length = len(np.unique(train_labels)) class_weight_dict = {i : class_weight[i] for i in range(length)} #Train neural network history = model.fit( train_ds, epochs=epochs, steps_per_epoch=train_steps, validation_data=valid_ds, validation_steps=valid_steps, callbacks=callbacks, class_weight=class_weight_dict, use_multiprocessing=multiproc, workers=nproc ) pd.DataFrame(history.history).to_json(history_output) #Predict on test set: if nproc!=0: test_fps = Parallel(n_jobs=nproc, verbose=1)( delayed(smiles_to_fingerprint)(smi, length=fp_length, radius=fp_radius) for smi in test_smiles ) else: test_fps = [smiles_to_fingerprint(smi, length=fp_length, radius=fp_radius) for smi in test_smiles] test_fps = np.array(test_fps) acc = model.evaluate(test_fps, test_labels, batch_size=batch_size) print(model.metrics_names[1:]) print(acc[1:]) with open('models/ml-fixed/evaluation_'+model_name1+'/'+model_name2+'_accuracy_t.out','w') as f: print(model.metrics_names[1:],file=f) print(acc[1:],file=f) return model,batch_size,test_fps def ml_fixed_model(system,n_cpus=20): for name in ["","canonical_","corrected_","canonical_corrected_"]: print("###",name) if not os.path.exists('models/ml-fixed/evaluation_'+name+system): os.makedirs('models/ml-fixed/evaluation_'+name+system) if name in ["","canonical_"]: choices= ["default","r0","r1","r2","r3"] else: choices=["default","r1","r2","r3"] #Reverse for i in choices: num_classes = int(np.load("data/"+system+"num_classes_"+name+"template_"+i+".npy")) print("Training model ("+i+" templates, retro) with",num_classes,"classes:") data_train=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_train.csv") data_val=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_val.csv") data_test=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_test.csv") train_smiles=data_train['prod_smiles'].values train_labels=data_train[name+"template_"+i+"_id"].values valid_smiles=data_val['prod_smiles'].values valid_labels=data_val[name+"template_"+i+"_id"].values test_smiles=data_test['prod_smiles'].values test_labels=data_test[name+"template_"+i+"_id"].values model,batch_size,test_fps = train_model(num_classes,train_smiles,train_labels,valid_smiles,valid_labels,test_smiles,test_labels,name+system,i+"_retro",n_cpus) #Check precursor evaluation: data_test=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_test.csv") forward_test_smiles=data_test['reac_smiles'].values templates=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_unique_templates.txt",header=None)[0].values preds=model.predict(test_fps,batch_size=batch_size) #Calculate ranks found_at_rank = [] found_at_ranks = [] recalls=[] for j in range(len(test_labels)): print(j, end='\r') found_ranks,found_rank,recall=get_rank_precursor_multi(preds[j],test_smiles[j],forward_test_smiles[j],templates, n_cpus) found_at_rank.append(found_rank) found_at_ranks.append(found_ranks) recalls.append(recall) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p.out','w') as fid: accs=ranks_to_acc(found_at_rank,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p_multi.out','w') as fid: accs_multi=get_multi_accs(found_at_ranks,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/appl__retro_template_'+i+'.out','w') as fid: mean_recall=average_recalls(recalls,fid=fid) print("Via precursor:") print(accs) print(mean_recall) print("Via precursor (multi):") print(accs_multi) #Forward for i in choices: num_classes = int(np.load("data/"+system+"num_classes_forward_"+name+"template_"+i+".npy")) print("Training model ("+i+" templates, forward) with",num_classes,"classes:") data_train=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_train.csv") data_val=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_val.csv") data_test=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_test.csv") train_smiles=data_train['reac_smiles'].values train_labels=data_train['forward_'+name+"template_"+i+"_id"].values valid_smiles=data_val['reac_smiles'].values valid_labels=data_val['forward_'+name+"template_"+i+"_id"].values test_smiles=data_test['reac_smiles'].values test_labels=data_test['forward_'+name+"template_"+i+"_id"].values model,batch_size,test_fps = train_model(num_classes,train_smiles,train_labels,valid_smiles,valid_labels,test_smiles,test_labels,name+system,i+"_forward", n_cpus) #Check precursor evaluation: data_test=pd.read_csv("data/"+system+"_"+name+"template_"+i+"_test.csv") forward_test_smiles=data_test['prod_smiles'].values templates=pd.read_csv("data/"+system+"_forward_"+name+"template_"+i+"_unique_templates.txt",header=None)[0].values preds=model.predict(test_fps,batch_size=batch_size) #Calculate ranks found_at_rank = [] found_at_ranks = [] recalls=[] for j in range(len(test_labels)): print(j, end='\r') found_ranks,found_rank,recall=get_rank_precursor_multi(preds[j],test_smiles[j],forward_test_smiles[j],templates, n_cpus) found_at_rank.append(found_rank) found_at_ranks.append(found_ranks) recalls.append(recall) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p.out','w') as fid: accs=ranks_to_acc(found_at_rank,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/'+i+"_retro"+'_accuracy_p_multi.out','w') as fid: accs_multi=get_multi_accs(found_at_ranks,fid=fid) with open('models/ml-fixed/evaluation_'+name+system+'/appl__retro_template_'+i+'.out','w') as fid: mean_recall=average_recalls(recalls,fid=fid) print("Via precursor:") print(accs) print(mean_recall) print("Via precursor (multi):") print(accs_multi) if __name__ == '__main__': ml_fixed_model('uspto_50k') #ml_fixed_model('uspto_460k')
0.317426
0.193681
from typing import List, Tuple import cv2 import io import time import imagehash import threading import cv2 from contextlib import contextmanager from PIL import Image from fluxhelper import Logger from queue import Queue VIDEO_MAPPINGS = { "video/x-msvideo": ".avi", "video/mp4": ".mp4", "video/mpeg": ".mpeg", "video/ogg": ".ogv", "video/mp2t": ".ts", "video/webm": ".webm", "video/x-matroska": ".mkv", "video/quicktime": ".mov" } @contextmanager def VideoCapture(*args, **kwargs): cap = cv2.VideoCapture(*args, **kwargs) try: yield cap finally: cap.release() def extractGifFrames(filelike: io.BytesIO, logging: Logger, uniqueness: float) -> List[Tuple[Image.Image, imagehash.ImageHash]]: """ Extract frames from a filelike object. """ frames = [] start = time.time() with Image.open(filelike) as img: if logging: logging.debug(f"Extracting {img.n_frames} frames from a GIF") for frame in range(img.n_frames): img.seek(frame) go = True hashed = imagehash.average_hash(img) if len(frames) > 1: for fc in frames: if (fc[1] - hashed) < uniqueness: go = False break if go: frames.append((img, hashed)) end = round((time.time() - start) * 1000, 2) if logging: logging.debug(f"Extracted {len(frames)} unique frames in {end}ms.") return frames def extractVideoFrames(filepath: str, logging: Logger, uniqueness: float, workers: int) -> List[Tuple[Image.Image, imagehash.ImageHash]]: """ Extract unique frames from a video file path. """ queue = Queue() frames = Queue() total = 0 frameCount = cv2.VideoCapture(filepath).get(cv2.CAP_PROP_FRAME_COUNT) start = time.time() def p(): while True: frame = queue.get() if frame is None: logging.debug("Exiting worker...") break frame = frame[:, :, ::-1] with Image.fromarray(frame) as frame: hashed = imagehash.average_hash(frame) go = True if len(list(frames.queue)) > 1: for fc in list(frames.queue): if (fc[1] - hashed) < uniqueness: go = False break if go: frames.put((frame, hashed)) queue.task_done() if frameCount <50: logging.warning("There are less than 20 frames, using 1 worker instead as it should do the job.") workers = 1 # Construct workers funcs = [p] * workers # Launch workers for i, t in enumerate(funcs): th = threading.Thread(target=t, daemon=True) th.start() logging.debug(f"Launched worker {i}") # Put frames into queue logging.debug("Extracting frames...") with VideoCapture(filepath) as cap: status, frame = cap.read() while status: queue.put(frame) total += 1 status, frame = cap.read() # Wait for all workers to be finished logging.debug("Waiting for workers to finish...") queue.join() logging.debug("Workers finished, exiting them...") for i in range(workers): queue.put(None) end = round((time.time() - start) * 1000, 2) frames = list(frames.queue) if logging: logging.debug( f"Extracted {len(frames)}/{total} unique frames in {end}ms.") return frames
fastnsfw/helpers.py
from typing import List, Tuple import cv2 import io import time import imagehash import threading import cv2 from contextlib import contextmanager from PIL import Image from fluxhelper import Logger from queue import Queue VIDEO_MAPPINGS = { "video/x-msvideo": ".avi", "video/mp4": ".mp4", "video/mpeg": ".mpeg", "video/ogg": ".ogv", "video/mp2t": ".ts", "video/webm": ".webm", "video/x-matroska": ".mkv", "video/quicktime": ".mov" } @contextmanager def VideoCapture(*args, **kwargs): cap = cv2.VideoCapture(*args, **kwargs) try: yield cap finally: cap.release() def extractGifFrames(filelike: io.BytesIO, logging: Logger, uniqueness: float) -> List[Tuple[Image.Image, imagehash.ImageHash]]: """ Extract frames from a filelike object. """ frames = [] start = time.time() with Image.open(filelike) as img: if logging: logging.debug(f"Extracting {img.n_frames} frames from a GIF") for frame in range(img.n_frames): img.seek(frame) go = True hashed = imagehash.average_hash(img) if len(frames) > 1: for fc in frames: if (fc[1] - hashed) < uniqueness: go = False break if go: frames.append((img, hashed)) end = round((time.time() - start) * 1000, 2) if logging: logging.debug(f"Extracted {len(frames)} unique frames in {end}ms.") return frames def extractVideoFrames(filepath: str, logging: Logger, uniqueness: float, workers: int) -> List[Tuple[Image.Image, imagehash.ImageHash]]: """ Extract unique frames from a video file path. """ queue = Queue() frames = Queue() total = 0 frameCount = cv2.VideoCapture(filepath).get(cv2.CAP_PROP_FRAME_COUNT) start = time.time() def p(): while True: frame = queue.get() if frame is None: logging.debug("Exiting worker...") break frame = frame[:, :, ::-1] with Image.fromarray(frame) as frame: hashed = imagehash.average_hash(frame) go = True if len(list(frames.queue)) > 1: for fc in list(frames.queue): if (fc[1] - hashed) < uniqueness: go = False break if go: frames.put((frame, hashed)) queue.task_done() if frameCount <50: logging.warning("There are less than 20 frames, using 1 worker instead as it should do the job.") workers = 1 # Construct workers funcs = [p] * workers # Launch workers for i, t in enumerate(funcs): th = threading.Thread(target=t, daemon=True) th.start() logging.debug(f"Launched worker {i}") # Put frames into queue logging.debug("Extracting frames...") with VideoCapture(filepath) as cap: status, frame = cap.read() while status: queue.put(frame) total += 1 status, frame = cap.read() # Wait for all workers to be finished logging.debug("Waiting for workers to finish...") queue.join() logging.debug("Workers finished, exiting them...") for i in range(workers): queue.put(None) end = round((time.time() - start) * 1000, 2) frames = list(frames.queue) if logging: logging.debug( f"Extracted {len(frames)}/{total} unique frames in {end}ms.") return frames
0.726329
0.212293
import argparse import json import logging import os import requests import shutil import subprocess import tomputils.util as tutil from datetime import datetime, timedelta from pathlib import Path from requests.auth import HTTPDigestAuth from requests.exceptions import Timeout, ConnectionError, RequestException from sys import exit from twisted.internet import task, reactor parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, required=True, help='Config File') starttm = datetime.now() sdate = starttm.strftime('%Y-%m-%d') shour = starttm.strftime('%H') endtm = None loop = None archpath = Path(os.getenv('VID_LOC', '/data')) tmppath = Path('/tmp') / shour timeout = None count = 0 def get_image(): global count if datetime.now() < endtm: try: if 'auth' in config: r = requests.get(config['url'], auth=HTTPDigestAuth(config['auth']['user'], config['auth']['passwd']), timeout=timeout) else: r = requests.get(config['url'], timeout=timeout) with open('image%04d.jpg' % count, 'wb') as f: f.write(r.content) r.close() count += 1 except ConnectionError as e: logger.error('Connection error: {}'.format(e)) except Timeout as e: logger.error('Timeout: {}'.format(e)) except RequestException as e: logger.error('Other requests error: {}'.format(e)) else: loop.stop() return def fix_images(): logger.debug('Delete any failed images') files = tmppath.glob('*.jpg') sz = int(config['1fps']['minFileSize']) for f in files: if f.stat().st_size < sz: f.unlink() logger.debug('Renumber images') c = 0 files = sorted(tmppath.glob('*.jpg')) for f in files: f.rename('image%04d.jpg' % c) c += 1 def encode_video(): cmd = ['ffmpeg', '-framerate', '5', '-i', 'image%04d.jpg', '-c:v', 'libx265', '-crf', '28', '-vf', 'scale=iw*.75:ih*.75', '-threads', '1', '1fps_{}00.mp4'.format(shour)] logger.debug('Encode video: {}'.format(' '.join(cmd))) subprocess.call(cmd) def copy_to_share(): logger.info('Copying to share') path = archpath / config['cam'] / sdate if not path.exists(): logger.debug('Creating new archive directory: {}'.format(path)) path.mkdir(parents=True) shutil.copy2('{}/1fps_{}00.mp4'.format(tmppath, shour), '{}/'.format(path)) def images_to_video_to_share(result): logger.info('Images gathered, creating video') fix_images() encode_video() copy_to_share() reactor.stop() def parse_config(confFile): logger.debug('Parse config at {}'.format(confFile)) with open(confFile, 'r') as f: return json.load(f) def loop_failed(failure): logger.error(failure.getBriefTraceback()) reactor.stop() def cleanup(): logger.debug('Deleting stuff') ftypes = ('*.jpg', '*.mp4') files = [] for t in ftypes: files.extend(tmppath.glob(t)) for f in files: f.unlink() tmppath.rmdir() def main(): global logger logger = tutil.setup_logging("1FPS") if 'PYLOGLEVEL' in os.environ: level = logging.getLevelName(os.getenv('PYLOGLEVEL', 'DEBUG')) logger.setLevel(level) args = parser.parse_args() logger.info('Starting') global config config = parse_config(args.config) global endtm endtm = starttm + timedelta(seconds=config['1fps']['time']) global timeout timeout = int(config['1fps']['interval']) * 2 try: tmppath.mkdir() os.chdir(str(tmppath)) except FileExistsError as e: logger.error('Temp path already exists. Is another process using it?') logger.error(e) logger.info('Exiting because of error') exit(0) global loop loop = task.LoopingCall(get_image) loopDeferred = loop.start(config['1fps']['interval']) loopDeferred.addCallback(images_to_video_to_share) loopDeferred.addErrback(loop_failed) reactor.run() cleanup() logger.info('Finished') logging.shutdown() if __name__ == '__main__': main()
support/bin/1FPSVideo.py
import argparse import json import logging import os import requests import shutil import subprocess import tomputils.util as tutil from datetime import datetime, timedelta from pathlib import Path from requests.auth import HTTPDigestAuth from requests.exceptions import Timeout, ConnectionError, RequestException from sys import exit from twisted.internet import task, reactor parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, required=True, help='Config File') starttm = datetime.now() sdate = starttm.strftime('%Y-%m-%d') shour = starttm.strftime('%H') endtm = None loop = None archpath = Path(os.getenv('VID_LOC', '/data')) tmppath = Path('/tmp') / shour timeout = None count = 0 def get_image(): global count if datetime.now() < endtm: try: if 'auth' in config: r = requests.get(config['url'], auth=HTTPDigestAuth(config['auth']['user'], config['auth']['passwd']), timeout=timeout) else: r = requests.get(config['url'], timeout=timeout) with open('image%04d.jpg' % count, 'wb') as f: f.write(r.content) r.close() count += 1 except ConnectionError as e: logger.error('Connection error: {}'.format(e)) except Timeout as e: logger.error('Timeout: {}'.format(e)) except RequestException as e: logger.error('Other requests error: {}'.format(e)) else: loop.stop() return def fix_images(): logger.debug('Delete any failed images') files = tmppath.glob('*.jpg') sz = int(config['1fps']['minFileSize']) for f in files: if f.stat().st_size < sz: f.unlink() logger.debug('Renumber images') c = 0 files = sorted(tmppath.glob('*.jpg')) for f in files: f.rename('image%04d.jpg' % c) c += 1 def encode_video(): cmd = ['ffmpeg', '-framerate', '5', '-i', 'image%04d.jpg', '-c:v', 'libx265', '-crf', '28', '-vf', 'scale=iw*.75:ih*.75', '-threads', '1', '1fps_{}00.mp4'.format(shour)] logger.debug('Encode video: {}'.format(' '.join(cmd))) subprocess.call(cmd) def copy_to_share(): logger.info('Copying to share') path = archpath / config['cam'] / sdate if not path.exists(): logger.debug('Creating new archive directory: {}'.format(path)) path.mkdir(parents=True) shutil.copy2('{}/1fps_{}00.mp4'.format(tmppath, shour), '{}/'.format(path)) def images_to_video_to_share(result): logger.info('Images gathered, creating video') fix_images() encode_video() copy_to_share() reactor.stop() def parse_config(confFile): logger.debug('Parse config at {}'.format(confFile)) with open(confFile, 'r') as f: return json.load(f) def loop_failed(failure): logger.error(failure.getBriefTraceback()) reactor.stop() def cleanup(): logger.debug('Deleting stuff') ftypes = ('*.jpg', '*.mp4') files = [] for t in ftypes: files.extend(tmppath.glob(t)) for f in files: f.unlink() tmppath.rmdir() def main(): global logger logger = tutil.setup_logging("1FPS") if 'PYLOGLEVEL' in os.environ: level = logging.getLevelName(os.getenv('PYLOGLEVEL', 'DEBUG')) logger.setLevel(level) args = parser.parse_args() logger.info('Starting') global config config = parse_config(args.config) global endtm endtm = starttm + timedelta(seconds=config['1fps']['time']) global timeout timeout = int(config['1fps']['interval']) * 2 try: tmppath.mkdir() os.chdir(str(tmppath)) except FileExistsError as e: logger.error('Temp path already exists. Is another process using it?') logger.error(e) logger.info('Exiting because of error') exit(0) global loop loop = task.LoopingCall(get_image) loopDeferred = loop.start(config['1fps']['interval']) loopDeferred.addCallback(images_to_video_to_share) loopDeferred.addErrback(loop_failed) reactor.run() cleanup() logger.info('Finished') logging.shutdown() if __name__ == '__main__': main()
0.207536
0.059674
import cv2 import numpy as np import os import json import glob frame_width, frame_height = 100, 100 dim = (frame_width,frame_height) fps = 25 output_extension = '.avi' def extract_hands(hands, bb, out, image): buff = 10 confidence_threshold = .1 confidence = np.mean(hands[:, 2]) if confidence >= confidence_threshold: bb = [ int(x) for x in bb] w, h = bb[2]-bb[0], bb[3]-bb[1] size = max(w, h) // 2 midw, midh = int(np.mean(hands[:, 0])), int(np.mean(hands[:, 1])) startw, starth, endw, endh = midw-size-buff, midh-size-buff, midw+size+buff, midh+size+buff cropped = image[starth:endh, startw:endw] # print(cropped.shape) if cropped.shape[0] > 0 and cropped.shape[1] > 0: frame = cv2.resize(cropped, dim) # cv2.imwrite("frame%d.jpg" % count, frame) # save frame as JPEG file out.write(frame) def generate_hand_videos(video, json_base, output_path): output_paths = [output_path.replace(output_extension, '_{}_{}'.format(x, output_extension)) for x in ['right', 'left']] if os.path.exists(output_paths[0]) and os.path.exists(output_paths[1]): print('skipping {}'.format(video)) return count = 0 vidcap = cv2.VideoCapture(video) success, image = vidcap.read() out_right = cv2.VideoWriter(output_paths[0], cv2.VideoWriter_fourcc('M','J','P','G'), fps, dim) out_left = cv2.VideoWriter(output_paths[1], cv2.VideoWriter_fourcc('M','J','P','G'), fps, dim) vname = video.rsplit('/', 1)[-1].split('.')[0] while success: kp_path = os.path.join(json_base, '{}_{}_keypoints.json'.format(vname, str(count).zfill(12))) if os.path.exists(kp_path): with open(kp_path) as r: kp = json.load(r)['people'][0] # x, y, score hands_right, hands_left = np.array(kp['hand_right_keypoints_2d']).reshape(-1, 3), np.array(kp['hand_left_keypoints_2d']).reshape(-1, 3) bb_right = np.min(hands_right[:, 0]), np.min(hands_right[:, 1]), np.max(hands_right[:, 0]), np.max(hands_right[:, 1]) # x0, y0, x1, y1 bb_left = np.min(hands_left[:, 0]), np.min(hands_left[:, 1]), np.max(hands_left[:, 0]), np.max(hands_left[:, 1]) extract_hands(hands_right, bb_right, out_right, image) extract_hands(hands_left, bb_left, out_left, image) success, image = vidcap.read() count += 1 print('done with {}'.format(video)) vidcap.release() out_right.release() out_left.release() if count == 0: for output_path in output_paths: os.remove(outputs_path) cv2.destroyAllWindows() if __name__ == '__main__': videos_path, jsons_path, outputs_path = 'test_rgb_front_clips/raw_videos', 'test_2D_keypoints/openpose_output/json', 'outputs' videos = glob.glob('{}/*.mp4'.format(videos_path)) if not os.path.exists(outputs_path): os.makedirs(outputs_path) for i, video in enumerate(sorted(videos)): output_path = video.replace('.mp4', output_extension).replace(videos_path, outputs_path) json_base_path = video.replace('.mp4', '').replace(videos_path, jsons_path) print('starting {}/{}. {}'.format(i, len(videos), video)) generate_hand_videos(video, json_base_path, output_path)
utils/crop_hand.py
import cv2 import numpy as np import os import json import glob frame_width, frame_height = 100, 100 dim = (frame_width,frame_height) fps = 25 output_extension = '.avi' def extract_hands(hands, bb, out, image): buff = 10 confidence_threshold = .1 confidence = np.mean(hands[:, 2]) if confidence >= confidence_threshold: bb = [ int(x) for x in bb] w, h = bb[2]-bb[0], bb[3]-bb[1] size = max(w, h) // 2 midw, midh = int(np.mean(hands[:, 0])), int(np.mean(hands[:, 1])) startw, starth, endw, endh = midw-size-buff, midh-size-buff, midw+size+buff, midh+size+buff cropped = image[starth:endh, startw:endw] # print(cropped.shape) if cropped.shape[0] > 0 and cropped.shape[1] > 0: frame = cv2.resize(cropped, dim) # cv2.imwrite("frame%d.jpg" % count, frame) # save frame as JPEG file out.write(frame) def generate_hand_videos(video, json_base, output_path): output_paths = [output_path.replace(output_extension, '_{}_{}'.format(x, output_extension)) for x in ['right', 'left']] if os.path.exists(output_paths[0]) and os.path.exists(output_paths[1]): print('skipping {}'.format(video)) return count = 0 vidcap = cv2.VideoCapture(video) success, image = vidcap.read() out_right = cv2.VideoWriter(output_paths[0], cv2.VideoWriter_fourcc('M','J','P','G'), fps, dim) out_left = cv2.VideoWriter(output_paths[1], cv2.VideoWriter_fourcc('M','J','P','G'), fps, dim) vname = video.rsplit('/', 1)[-1].split('.')[0] while success: kp_path = os.path.join(json_base, '{}_{}_keypoints.json'.format(vname, str(count).zfill(12))) if os.path.exists(kp_path): with open(kp_path) as r: kp = json.load(r)['people'][0] # x, y, score hands_right, hands_left = np.array(kp['hand_right_keypoints_2d']).reshape(-1, 3), np.array(kp['hand_left_keypoints_2d']).reshape(-1, 3) bb_right = np.min(hands_right[:, 0]), np.min(hands_right[:, 1]), np.max(hands_right[:, 0]), np.max(hands_right[:, 1]) # x0, y0, x1, y1 bb_left = np.min(hands_left[:, 0]), np.min(hands_left[:, 1]), np.max(hands_left[:, 0]), np.max(hands_left[:, 1]) extract_hands(hands_right, bb_right, out_right, image) extract_hands(hands_left, bb_left, out_left, image) success, image = vidcap.read() count += 1 print('done with {}'.format(video)) vidcap.release() out_right.release() out_left.release() if count == 0: for output_path in output_paths: os.remove(outputs_path) cv2.destroyAllWindows() if __name__ == '__main__': videos_path, jsons_path, outputs_path = 'test_rgb_front_clips/raw_videos', 'test_2D_keypoints/openpose_output/json', 'outputs' videos = glob.glob('{}/*.mp4'.format(videos_path)) if not os.path.exists(outputs_path): os.makedirs(outputs_path) for i, video in enumerate(sorted(videos)): output_path = video.replace('.mp4', output_extension).replace(videos_path, outputs_path) json_base_path = video.replace('.mp4', '').replace(videos_path, jsons_path) print('starting {}/{}. {}'.format(i, len(videos), video)) generate_hand_videos(video, json_base_path, output_path)
0.183484
0.262021
from accounting import models from django.db import transaction from rest_framework.serializers import HyperlinkedModelSerializer class LedgerSerializer(HyperlinkedModelSerializer): class Meta: model = models.Ledger fields = ( 'url', 'id', 'persons_company', 'name' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:ledger-detail' }, 'persons_company': { 'view_name': 'api:persons:company-detail' } } class AccountSerializer(HyperlinkedModelSerializer): class Meta: model = models.Account fields = ( 'url', 'id', 'ledger', 'account_type', 'code', 'name', 'balance' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:account-detail' }, 'ledger': { 'view_name': 'api:accounting:ledger-detail' }, 'balance': { 'coerce_to_string': False } } class TransactionSerializer(HyperlinkedModelSerializer): class Meta: model = models.Transaction read_only_fields = ( 'url', 'id', 'amount', 'debit_account', 'debit_account_balance', 'credit_account', 'credit_account_balance' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:transaction-detail' }, 'debit_account': { 'view_name': 'api:accounting:account-detail' }, 'credit_account': { 'view_name': 'api:accounting:account-detail' }, 'amount': { 'coerce_to_string': False }, 'debit_account_balance': { 'coerce_to_string': False }, 'credit_account_balance': { 'coerce_to_string': False } } class PaymentSerializer(HyperlinkedModelSerializer): class Meta: model = models.Payment fields = ( 'url', 'id', 'accounting_company', 'contact_contact', 'payment_date', 'payment_type', 'payment_method', 'amount', 'description', 'transaction' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:payment-detail' }, 'accounting_company': { 'view_name': 'api:accounting:companyaccounting-detail', }, 'contact_contact': { 'view_name': 'api:contact:contact-detail' }, 'amount': { 'coerce_to_string': False }, 'transaction': { 'view_name': 'api:accounting:transaction-detail', 'read_only': True } } @transaction.atomic def create(self, validated_data): accounting_company = validated_data.get('accounting_company') payment_method = validated_data.get('payment_method') amount = validated_data.get('amount') if payment_method == models.PAYMENT_METHOD_CASH: debit_account = ( accounting_company.default_debit_account_for_cash ) credit_account = ( accounting_company.default_credit_account_for_cash ) elif payment_method == models.PAYMENT_METHOD_CREDITCARD: debit_account = ( accounting_company.default_debit_account_for_creditcard ) credit_account = ( accounting_company.default_credit_account_for_creditcard ) elif payment_method == models.PAYMENT_METHOD_DEBITCARD: debit_account = ( accounting_company.default_debit_account_for_debitcard ) credit_account = ( accounting_company.default_credit_account_for_debitcard ) elif payment_method == models.PAYMENT_METHOD_BANKACCOUNT: debit_account = ( accounting_company.default_debit_account_for_bankaccount ) credit_account = ( accounting_company.default_credit_account_for_bankaccount ) elif payment_method == models.PAYMENT_METHOD_CHECK: debit_account = ( accounting_company.default_debit_account_for_check ) credit_account = ( accounting_company.default_credit_account_for_check ) elif payment_method == models.PAYMENT_METHOD_PAYPAL: debit_account = ( accounting_company.default_debit_account_for_paypal ) credit_account = ( accounting_company.default_credit_account_for_paypal ) elif payment_method == models.PAYMENT_METHOD_GOOGLEWALLET: debit_account = ( accounting_company.default_debit_account_for_googlewallet ) credit_account = ( accounting_company.default_credit_account_for_googlewallet ) elif payment_method == models.PAYMENT_METHOD_APPLEPAY: debit_account = ( accounting_company.default_debit_account_for_applepay ) credit_account = ( accounting_company.default_credit_account_for_applepay ) elif payment_method == models.PAYMENT_METHOD_BITCOIN: debit_account = ( accounting_company.default_debit_account_for_bitcoin ) credit_account = ( accounting_company.default_credit_account_for_bitcoin ) transaction = models.Transaction.objects.create( amount=amount, debit_account=debit_account, debit_account_balance=debit_account.balance+amount, credit_account=credit_account, credit_account_balance=credit_account.balance+amount ) validated_data['transaction'] = transaction return models.Payment.objects.create(**validated_data) class CompanyAccountingSerializer(HyperlinkedModelSerializer): class Meta: model = models.CompanyAccounting fields = ( 'url', 'id', 'persons_company', 'default_debit_account_for_cash', 'default_credit_account_for_cash', 'default_debit_account_for_creditcard', 'default_credit_account_for_creditcard', 'default_debit_account_for_debitcard', 'default_credit_account_for_debitcard', 'default_debit_account_for_bankaccount', 'default_credit_account_for_bankaccount', 'default_debit_account_for_check', 'default_credit_account_for_check', 'default_debit_account_for_paypal', 'default_credit_account_for_paypal', 'default_debit_account_for_googlewallet', 'default_credit_account_for_googlewallet', 'default_debit_account_for_applepay', 'default_credit_account_for_applepay', 'default_debit_account_for_bitcoin', 'default_credit_account_for_bitcoin' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:companyaccounting-detail' }, 'persons_company': { 'view_name': 'api:persons:company-detail' }, 'default_debit_account_for_cash': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_cash': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_creditcard': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_creditcard': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_debitcard': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_debitcard': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_bankaccount': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_bankaccount': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_check': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_check': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_paypal': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_paypal': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_googlewallet': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_googlewallet': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_applepay': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_applepay': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_bitcoin': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_bitcoin': { 'view_name': 'api:accounting:account-detail' } }
accounting/serializers.py
from accounting import models from django.db import transaction from rest_framework.serializers import HyperlinkedModelSerializer class LedgerSerializer(HyperlinkedModelSerializer): class Meta: model = models.Ledger fields = ( 'url', 'id', 'persons_company', 'name' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:ledger-detail' }, 'persons_company': { 'view_name': 'api:persons:company-detail' } } class AccountSerializer(HyperlinkedModelSerializer): class Meta: model = models.Account fields = ( 'url', 'id', 'ledger', 'account_type', 'code', 'name', 'balance' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:account-detail' }, 'ledger': { 'view_name': 'api:accounting:ledger-detail' }, 'balance': { 'coerce_to_string': False } } class TransactionSerializer(HyperlinkedModelSerializer): class Meta: model = models.Transaction read_only_fields = ( 'url', 'id', 'amount', 'debit_account', 'debit_account_balance', 'credit_account', 'credit_account_balance' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:transaction-detail' }, 'debit_account': { 'view_name': 'api:accounting:account-detail' }, 'credit_account': { 'view_name': 'api:accounting:account-detail' }, 'amount': { 'coerce_to_string': False }, 'debit_account_balance': { 'coerce_to_string': False }, 'credit_account_balance': { 'coerce_to_string': False } } class PaymentSerializer(HyperlinkedModelSerializer): class Meta: model = models.Payment fields = ( 'url', 'id', 'accounting_company', 'contact_contact', 'payment_date', 'payment_type', 'payment_method', 'amount', 'description', 'transaction' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:payment-detail' }, 'accounting_company': { 'view_name': 'api:accounting:companyaccounting-detail', }, 'contact_contact': { 'view_name': 'api:contact:contact-detail' }, 'amount': { 'coerce_to_string': False }, 'transaction': { 'view_name': 'api:accounting:transaction-detail', 'read_only': True } } @transaction.atomic def create(self, validated_data): accounting_company = validated_data.get('accounting_company') payment_method = validated_data.get('payment_method') amount = validated_data.get('amount') if payment_method == models.PAYMENT_METHOD_CASH: debit_account = ( accounting_company.default_debit_account_for_cash ) credit_account = ( accounting_company.default_credit_account_for_cash ) elif payment_method == models.PAYMENT_METHOD_CREDITCARD: debit_account = ( accounting_company.default_debit_account_for_creditcard ) credit_account = ( accounting_company.default_credit_account_for_creditcard ) elif payment_method == models.PAYMENT_METHOD_DEBITCARD: debit_account = ( accounting_company.default_debit_account_for_debitcard ) credit_account = ( accounting_company.default_credit_account_for_debitcard ) elif payment_method == models.PAYMENT_METHOD_BANKACCOUNT: debit_account = ( accounting_company.default_debit_account_for_bankaccount ) credit_account = ( accounting_company.default_credit_account_for_bankaccount ) elif payment_method == models.PAYMENT_METHOD_CHECK: debit_account = ( accounting_company.default_debit_account_for_check ) credit_account = ( accounting_company.default_credit_account_for_check ) elif payment_method == models.PAYMENT_METHOD_PAYPAL: debit_account = ( accounting_company.default_debit_account_for_paypal ) credit_account = ( accounting_company.default_credit_account_for_paypal ) elif payment_method == models.PAYMENT_METHOD_GOOGLEWALLET: debit_account = ( accounting_company.default_debit_account_for_googlewallet ) credit_account = ( accounting_company.default_credit_account_for_googlewallet ) elif payment_method == models.PAYMENT_METHOD_APPLEPAY: debit_account = ( accounting_company.default_debit_account_for_applepay ) credit_account = ( accounting_company.default_credit_account_for_applepay ) elif payment_method == models.PAYMENT_METHOD_BITCOIN: debit_account = ( accounting_company.default_debit_account_for_bitcoin ) credit_account = ( accounting_company.default_credit_account_for_bitcoin ) transaction = models.Transaction.objects.create( amount=amount, debit_account=debit_account, debit_account_balance=debit_account.balance+amount, credit_account=credit_account, credit_account_balance=credit_account.balance+amount ) validated_data['transaction'] = transaction return models.Payment.objects.create(**validated_data) class CompanyAccountingSerializer(HyperlinkedModelSerializer): class Meta: model = models.CompanyAccounting fields = ( 'url', 'id', 'persons_company', 'default_debit_account_for_cash', 'default_credit_account_for_cash', 'default_debit_account_for_creditcard', 'default_credit_account_for_creditcard', 'default_debit_account_for_debitcard', 'default_credit_account_for_debitcard', 'default_debit_account_for_bankaccount', 'default_credit_account_for_bankaccount', 'default_debit_account_for_check', 'default_credit_account_for_check', 'default_debit_account_for_paypal', 'default_credit_account_for_paypal', 'default_debit_account_for_googlewallet', 'default_credit_account_for_googlewallet', 'default_debit_account_for_applepay', 'default_credit_account_for_applepay', 'default_debit_account_for_bitcoin', 'default_credit_account_for_bitcoin' ) extra_kwargs = { 'url': { 'view_name': 'api:accounting:companyaccounting-detail' }, 'persons_company': { 'view_name': 'api:persons:company-detail' }, 'default_debit_account_for_cash': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_cash': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_creditcard': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_creditcard': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_debitcard': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_debitcard': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_bankaccount': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_bankaccount': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_check': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_check': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_paypal': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_paypal': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_googlewallet': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_googlewallet': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_applepay': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_applepay': { 'view_name': 'api:accounting:account-detail' }, 'default_debit_account_for_bitcoin': { 'view_name': 'api:accounting:account-detail' }, 'default_credit_account_for_bitcoin': { 'view_name': 'api:accounting:account-detail' } }
0.603465
0.118896
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import models from dataset import get_feature def rescore_valid(cfg, temp, ori_scores): temp = np.array(temp) feature = get_feature(temp, cfg.DATASET.DATASET) feature = feature.cuda() PredictOKSmodel = eval('models.'+'predictOKS'+'.get_pose_net')( cfg, feature.shape[1], is_train=False ) pretrained_state_dict = torch.load(cfg.RESCORE.MODEL_FILE) need_init_state_dict = {} for name, m in pretrained_state_dict.items(): need_init_state_dict[name] = m PredictOKSmodel.load_state_dict(need_init_state_dict, strict=False) PredictOKSmodel = torch.nn.DataParallel( PredictOKSmodel, device_ids=cfg.GPUS).cuda() PredictOKSmodel.eval() scores = PredictOKSmodel(feature) scores = scores.cpu().numpy() scores[np.isnan(scores)] = 0 mul_scores = scores*np.array(ori_scores).reshape(scores.shape) scores = [np.float(i) for i in list(scores)] mul_scores = [np.float(i) for i in list(mul_scores)] return mul_scores def rescore_fit(cfg, model, x_data, y_data): loss_fn = nn.MSELoss(reduction='mean') train_losses = [] optimizer = torch.optim.Adam(model.parameters(), lr=cfg.RESCORE.LR) x_data = Variable(x_data, requires_grad=True) y_data = Variable(y_data, requires_grad=True) save_final_model_file = cfg.RESCORE.MODEL_FILE for epoch in range(cfg.RESCORE.END_EPOCH): train_loss = train(x_data, y_data, optimizer, model, loss_fn, cfg.RESCORE.BATCHSIZE) train_losses.append(train_loss) if epoch % 1 == 0: print("step:", epoch+1, "train_loss:", train_loss) torch.save(model.state_dict(), save_final_model_file) return train_losses def train(x_data, y_data, optimizer, model, loss_fn, batchsize): datasize = len(x_data) loss_sum = 0 index = np.arange(datasize) np.random.shuffle(index) for i in range(int(datasize/batchsize)): x_temp = x_data[index[i*batchsize:(i+1)*(batchsize)]] y_temp = y_data[index[i*batchsize:(i+1)*(batchsize)]] model.train() optimizer.zero_grad() y_pred = model(x_temp) loss = loss_fn(y_pred, y_temp) loss.backward() optimizer.step() loss_sum += loss.item() return loss_sum/int(datasize/batchsize)
lib/core/rescore.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import models from dataset import get_feature def rescore_valid(cfg, temp, ori_scores): temp = np.array(temp) feature = get_feature(temp, cfg.DATASET.DATASET) feature = feature.cuda() PredictOKSmodel = eval('models.'+'predictOKS'+'.get_pose_net')( cfg, feature.shape[1], is_train=False ) pretrained_state_dict = torch.load(cfg.RESCORE.MODEL_FILE) need_init_state_dict = {} for name, m in pretrained_state_dict.items(): need_init_state_dict[name] = m PredictOKSmodel.load_state_dict(need_init_state_dict, strict=False) PredictOKSmodel = torch.nn.DataParallel( PredictOKSmodel, device_ids=cfg.GPUS).cuda() PredictOKSmodel.eval() scores = PredictOKSmodel(feature) scores = scores.cpu().numpy() scores[np.isnan(scores)] = 0 mul_scores = scores*np.array(ori_scores).reshape(scores.shape) scores = [np.float(i) for i in list(scores)] mul_scores = [np.float(i) for i in list(mul_scores)] return mul_scores def rescore_fit(cfg, model, x_data, y_data): loss_fn = nn.MSELoss(reduction='mean') train_losses = [] optimizer = torch.optim.Adam(model.parameters(), lr=cfg.RESCORE.LR) x_data = Variable(x_data, requires_grad=True) y_data = Variable(y_data, requires_grad=True) save_final_model_file = cfg.RESCORE.MODEL_FILE for epoch in range(cfg.RESCORE.END_EPOCH): train_loss = train(x_data, y_data, optimizer, model, loss_fn, cfg.RESCORE.BATCHSIZE) train_losses.append(train_loss) if epoch % 1 == 0: print("step:", epoch+1, "train_loss:", train_loss) torch.save(model.state_dict(), save_final_model_file) return train_losses def train(x_data, y_data, optimizer, model, loss_fn, batchsize): datasize = len(x_data) loss_sum = 0 index = np.arange(datasize) np.random.shuffle(index) for i in range(int(datasize/batchsize)): x_temp = x_data[index[i*batchsize:(i+1)*(batchsize)]] y_temp = y_data[index[i*batchsize:(i+1)*(batchsize)]] model.train() optimizer.zero_grad() y_pred = model(x_temp) loss = loss_fn(y_pred, y_temp) loss.backward() optimizer.step() loss_sum += loss.item() return loss_sum/int(datasize/batchsize)
0.748168
0.210482
from django.urls import reverse from simple.models import SimpleManager, SimpleModel def test_AbstractIAMUser(django_user_model): username = 'user' user = django_user_model.objects.create_user(username=username) assert user.full_name == "" assert user.display_name == username assert user.initials == "U" SimpleManager.objects.create(user=user) add_model_perm = SimpleModel.get_perm('add') assert user.has_perm(add_model_perm) user.first_name = "User" user.last_name = "McUser" user.save() assert user.full_name == "<NAME>" assert user.display_name == "<NAME>" assert user.initials == "UM" def test_IAMUserAdmin(client, django_user_model): default_user_post_dict = { 'is_active': True, 'is_staff': True, } user_superuser_username = 'user_superuser' user_superuser = django_user_model.objects.create(username=user_superuser_username, is_staff=True, is_superuser=True) user_staff_username = 'user_staff' user_staff = django_user_model.objects.create(username=user_staff_username, is_staff=True) opts = django_user_model._meta admin_url_changelist = reverse(f'admin:{opts.app_label}_{opts.model_name}_changelist') admin_url_change_superuser = reverse(f'admin:{opts.app_label}_{opts.model_name}_change', args=[user_superuser.id]) # Check if superuser can access change page for superusers client.force_login(user_superuser) response = client.get(admin_url_changelist) assert response.status_code == 200 response = client.get(admin_url_change_superuser) assert response.status_code == 200 # Check is superuser can edit is_superuser, a protected attribute response = client.post( admin_url_change_superuser, { **default_user_post_dict, 'username': user_superuser_username, 'is_superuser': False, } ) assert response.status_code == 302 user_superuser = django_user_model.objects.get(username=user_superuser_username) assert not user_superuser.is_superuser user_superuser.is_superuser = True # Set this back to the original condition for the rest of the test user_superuser.save() # Check if normal staff can access change page for superusers client.force_login(user_staff) response = client.get(admin_url_changelist) assert response.status_code == 200 response = client.get(admin_url_change_superuser) assert response.status_code == 302 # Check is normal staff can edit is_superuser, a protected attribute admin_url_change_staff_user = reverse(f'admin:{opts.app_label}_{opts.model_name}_change', args=[user_staff.id]) response = client.post( admin_url_change_staff_user, { **default_user_post_dict, 'username': user_staff_username, 'is_superuser': True, } ) assert response.status_code == 302 user_staff = django_user_model.objects.get(username=user_staff_username) assert not user_staff.is_superuser
tests/contrib/test_users.py
from django.urls import reverse from simple.models import SimpleManager, SimpleModel def test_AbstractIAMUser(django_user_model): username = 'user' user = django_user_model.objects.create_user(username=username) assert user.full_name == "" assert user.display_name == username assert user.initials == "U" SimpleManager.objects.create(user=user) add_model_perm = SimpleModel.get_perm('add') assert user.has_perm(add_model_perm) user.first_name = "User" user.last_name = "McUser" user.save() assert user.full_name == "<NAME>" assert user.display_name == "<NAME>" assert user.initials == "UM" def test_IAMUserAdmin(client, django_user_model): default_user_post_dict = { 'is_active': True, 'is_staff': True, } user_superuser_username = 'user_superuser' user_superuser = django_user_model.objects.create(username=user_superuser_username, is_staff=True, is_superuser=True) user_staff_username = 'user_staff' user_staff = django_user_model.objects.create(username=user_staff_username, is_staff=True) opts = django_user_model._meta admin_url_changelist = reverse(f'admin:{opts.app_label}_{opts.model_name}_changelist') admin_url_change_superuser = reverse(f'admin:{opts.app_label}_{opts.model_name}_change', args=[user_superuser.id]) # Check if superuser can access change page for superusers client.force_login(user_superuser) response = client.get(admin_url_changelist) assert response.status_code == 200 response = client.get(admin_url_change_superuser) assert response.status_code == 200 # Check is superuser can edit is_superuser, a protected attribute response = client.post( admin_url_change_superuser, { **default_user_post_dict, 'username': user_superuser_username, 'is_superuser': False, } ) assert response.status_code == 302 user_superuser = django_user_model.objects.get(username=user_superuser_username) assert not user_superuser.is_superuser user_superuser.is_superuser = True # Set this back to the original condition for the rest of the test user_superuser.save() # Check if normal staff can access change page for superusers client.force_login(user_staff) response = client.get(admin_url_changelist) assert response.status_code == 200 response = client.get(admin_url_change_superuser) assert response.status_code == 302 # Check is normal staff can edit is_superuser, a protected attribute admin_url_change_staff_user = reverse(f'admin:{opts.app_label}_{opts.model_name}_change', args=[user_staff.id]) response = client.post( admin_url_change_staff_user, { **default_user_post_dict, 'username': user_staff_username, 'is_superuser': True, } ) assert response.status_code == 302 user_staff = django_user_model.objects.get(username=user_staff_username) assert not user_staff.is_superuser
0.511961
0.280764
import unittest from serviceparser import Parser import yaml import copy import json from groupinfo import GroupInfo from registryinfo import RegistryInfo class ServiceParserTests(unittest.TestCase): def _get_default_parser(self, service_info=None): group_info = GroupInfo('group_name', 'group_qualifier', 1) registry_info = RegistryInfo('host', 'username', 'password') if not service_info: service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'expose': ['80'], 'ports': ['8080'] } service_name = 'my_service' service_parser = Parser(group_info, registry_info, service_name, service_info) return service_parser def test_not_none(self): service_parser = self._get_default_parser() self.assertIsNotNone(service_parser) def test_get_service_name_label(self): service_name = 'my_service' service_parser = self._get_default_parser() expected = {'com.microsoft.acs.k8s.service_name': service_name} actual = service_parser._get_service_name_label() self.assertEquals(actual, expected) def test_get_empty_service_json(self): service_parser = self._get_default_parser() expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [] } } actual = service_parser._get_empty_service_json() self.assertEquals(actual, expected) def test_get_empty_deployment_json(self): service_parser = self._get_default_parser() service_name = 'my_service' expected = { "apiVersion": "extensions/v1beta1", "kind": "Deployment", "metadata": { "name": service_name }, "spec": { "replicas": 1, "template": { "metadata": { "labels": { 'com.microsoft.acs.k8s.service_name': service_name } }, "spec": { "containers": [{ "name": service_name }], "imagePullSecrets": [] } } } } actual = service_parser._get_empty_deployment_json() self.assertEquals(actual, expected) def test_add_label(self): service_parser = self._get_default_parser() service_parser._add_label('label_name', 'some_value') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'label_name': 'some_value', 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_label_no_name(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_label('', 'some_value') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_label_no_value(self): service_parser = self._get_default_parser() expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'some_label': '', 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } service_parser._add_label('some_label', '') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_image(self): service_parser = self._get_default_parser() service_parser._add_container_image('my_service', 'some_image') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'image': 'some_image' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_image_no_service(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_container_image('', 'some_image') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_image_no_image(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_container_image('my_service', '') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_image(self): service_parser = self._get_default_parser() expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'image': 'some_image' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } service_parser._parse_image('image') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_image_no_key(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._parse_image('blah') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_image_pull_secret(self): service_parser = self._get_default_parser() service_parser._add_image_pull_secret('secret_name') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [{ 'name': 'secret_name' }], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_image_pull_secret_no_name(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_image_pull_secret('') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_port(self): service_parser = self._get_default_parser() service_parser._add_container_port(1234) expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'ports': [{ 'containerPort': 1234 }] }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_port_no_port(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_container_port(None) actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_get_service_json_no_service(self): service_parser = self._get_default_parser() self.assertIsNone(service_parser.get_service_json()) def test_get_service_json(self): service_parser = self._get_default_parser() service_parser.service_added = True expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [] } } actual = service_parser.service_json self.assertEquals(actual, expected) def test_create_new_ingress_rule_default_path(self): service_parser = self._get_default_parser() expected = { "host": 'myhost.com', "http": { "paths": [{ "path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } } actual = service_parser._create_new_ingress_rule( 'myhost.com', 1234, 'my_service') self.assertEquals(actual, expected) def test_create_new_ingress_rule_empty_path(self): service_parser = self._get_default_parser() expected = { "host": 'myhost.com', "http": { "paths": [{ "path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } } actual = service_parser._create_new_ingress_rule( 'myhost.com', 1234, 'my_service', path=None) self.assertEquals(actual, expected) def test_create_new_ingress_rule_custom_path(self): service_parser = self._get_default_parser() expected = { "host": 'myhost.com', "http": { "paths": [{ "path": "/path", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } } actual = service_parser._create_new_ingress_rule( 'myhost.com', 1234, 'my_service', path="/path") self.assertEquals(actual, expected) def test_create_new_ingress_rule_no_host(self): service_parser = self._get_default_parser() self.assertRaises( ValueError, service_parser._create_new_ingress_rule, None, 1234, 'my_service') def test_create_new_ingress_rule_no_service(self): service_parser = self._get_default_parser() self.assertRaises( ValueError, service_parser._create_new_ingress_rule, 'myhost.com', 1234, '') def test_create_new_ingress_rule_no_port(self): service_parser = self._get_default_parser() self.assertRaises( ValueError, service_parser._create_new_ingress_rule, 'myhost.com', None, 'blah') def test_add_ingress_rule(self): service_parser = self._get_default_parser() expected = [{ 'host': 'host.com', 'http': { 'paths': [{ 'path': '/', 'backend': { 'serviceName': 'my_service', 'servicePort': 1234 } }] } }] service_parser._add_ingress_rule('host.com', 1234, 'my_service') actual = service_parser.ingress_rules self.assertEquals(actual, expected) def test_add_ingress_rule_update_existing(self): service_parser = self._get_default_parser() service_parser.ingress_rules = [{ 'host': 'host.com', 'http': { 'paths': [{ 'path': '/', 'backend': { 'serviceName': 'my_service', 'servicePort': 1234 } }] } }] expected = [{ 'host': 'host.com', 'http': { 'paths': [{ 'path': '/', 'backend': { 'serviceName': 'my_service', 'servicePort': 1234 } }, { 'path': '/', 'backend': { 'serviceName': 'anotherservice', 'servicePort': 80 } }] } }] service_parser._add_ingress_rule('host.com', 80, 'anotherservice') actual = service_parser.ingress_rules self.assertEquals(actual, expected) def test_get_ingress_json(self): service_parser = self._get_default_parser() ingress_rules = [{ "host": "host.com", "http": { "paths": [{ "path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } }] service_parser.ingress_rules = ingress_rules expected = {"kind": "Ingress", "spec": {"rules": [{"host": "host.com", "http": {"paths": [{"path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234}}]}}]}, "apiVersion": "extensions/v1beta1", "metadata": {"name": "my_service"}} actual = service_parser.get_ingress_json() self.assertEquals(actual, json.dumps(expected)) def test_get_ingress_json_no_rules(self): service_parser = self._get_default_parser() self.assertIsNone(service_parser.get_ingress_json()) def test_get_port_name(self): service_parser = self._get_default_parser() expected = "port-80" actual = service_parser._get_port_name(80) self.assertEquals(actual, expected) def test_get_port_name_multiple(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": "port-80", "protocol": "TCP", "targetPort": 8080, "port": 80 }) expected = "port-80-1" actual = service_parser._get_port_name(80) self.assertEquals(actual, expected) def test_create_service(self): service_parser = self._get_default_parser() self.assertFalse(service_parser.service_added) service_parser._create_service((80, 8080)) expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [{ "name": "port-8080", "protocol": "TCP", "targetPort": 80, "port": 8080 }] } } self.assertTrue(service_parser.service_added) actual = service_parser.service_json self.assertEquals(actual, expected) def test_create_service_existing_ports(self): service_parser = self._get_default_parser() self.assertFalse(service_parser.service_added) service_parser._create_service((80, 8080)) expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [{ "name": "port-8080", "protocol": "TCP", "targetPort": 80, "port": 8080 }] } } service_parser._create_service((80, 8080)) self.assertTrue(service_parser.service_added) actual = service_parser.service_json self.assertEquals(actual, expected) def test_create_service_multiple_ports(self): service_parser = self._get_default_parser() self.assertFalse(service_parser.service_added) service_parser._create_service((80, 8080)) expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [{ "name": "port-8080", "protocol": "TCP", "targetPort": 80, "port": 8080 }, { "name": "port-8080-1", "protocol": "TCP", "targetPort": 81, "port": 8080 }] } } service_parser._create_service((81, 8080)) self.assertTrue(service_parser.service_added) actual = service_parser.service_json self.assertEquals(actual, expected) def test_port_exists_default(self): service_parser = self._get_default_parser() self.assertFalse(service_parser._port_exists((80, 8080))) def test_port_exists_none(self): service_parser = self._get_default_parser() self.assertFalse(service_parser._port_exists(None)) def test_port_exists(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 80, "port": 8080 }) self.assertTrue(service_parser._port_exists((80, 8080))) def test_port_exists_false(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 80, "port": 8080 }) self.assertFalse(service_parser._port_exists((81, 8080))) def test_port_exists_multiple(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 80, "port": 8080 }) service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 81, "port": 8080 }) self.assertTrue(service_parser._port_exists((81, 8080))) def test_parse_environment(self): service_parser = self._get_default_parser() service_parser._parse_environment('environment') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'env': [{ 'name': 'variable_one', 'value': 'value_one' }] }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_environment_list(self): service_info = { 'image': 'some_image', 'environment': ['variable_one=value_one', 'variable_two=value_two'] } service_parser = self._get_default_parser(service_info) service_parser._parse_environment('environment') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'env': [{ 'name': 'variable_one', 'value': 'value_one' }, { 'name': 'variable_two', 'value': 'value_two' }] }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_expose(self): service_parser = self._get_default_parser() expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-80', 'port': 80 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_expose_multiple_ports(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'expose': ['80', '8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-80', 'port': 80 }, { 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_expose_no_expose(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' } } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports(self): service_parser = self._get_default_parser() expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_pair(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['80:8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_range(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['80-81:90-91'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-90', 'port': 90 }, { 'targetPort': 81, 'protocol': 'TCP', 'name': 'port-91', 'port': 91 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_and_expose_no_dupes(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['8080'], 'expose': ['8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_and_expose(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['80:8080'], 'expose': ['8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }, { 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080-1', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_labels(self): service_info = { 'labels': {'my_label': 'label_value'}, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': 'label_value' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_labels_ignore_com_ms(self): service_info = { 'labels': { 'my_label': 'label_value', 'com.microsoft.acs.kubernetes.vhosts': 'should_be_ignored' }, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': 'label_value' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_labels_single_string(self): service_info = { 'labels': { 'my_label=some_value' }, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': 'some_value' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_labels_no_value(self): service_info = { 'labels': { 'my_label' }, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': '' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_get_deployment_json(self): service_info = {'environment': {'APPINSIGHTS_INSTRUMENTATIONKEY': None}, 'image': 'peterjausovec-exp.azurecr.io/peterjausovecsampleapp_service-a@sha256:67a44ab41d40e8c5b76530dd525008fef0d16f07b5e4e486ea569c88de543b9f', 'depends_on': ['service-b'], 'expose': ['8080'], 'labels': {'com.microsoft.acs.kubernetes.vhosts': '["www.containers.site", "api.containers.site:1234"]', 'some_label': 'label-value'}, 'ports': ['8080:80']} expected = { "kind": "Deployment", "spec": { "template": { "spec": { "imagePullSecrets": [{ "name": "host" }], "containers": [{ "image": "peterjausovec-exp.azurecr.io/peterjausovecsampleapp_service-a@sha256:67a44ab41d40e8c5b76530dd525008fef0d16f07b5e4e486ea569c88de543b9f", "name": "my_service", "env": [{ "name": "APPINSIGHTS_INSTRUMENTATIONKEY", "value": "" }], "ports": [{ "containerPort": 80 }, { "containerPort": 8080 }] }] }, "metadata": { "labels": { "some_label": "label-value", "com.microsoft.acs.k8s.service_name": "my_service" } } }, "replicas": 1 }, "apiVersion": "extensions/v1beta1", "metadata": { "name": "my_service" } } service_parser = self._get_default_parser(service_info) actual = service_parser.get_deployment_json() self.assertEquals(actual, json.dumps(expected))
src/tasks/dockerDeploy/acs-kubernetes/test_serviceparser.py
import unittest from serviceparser import Parser import yaml import copy import json from groupinfo import GroupInfo from registryinfo import RegistryInfo class ServiceParserTests(unittest.TestCase): def _get_default_parser(self, service_info=None): group_info = GroupInfo('group_name', 'group_qualifier', 1) registry_info = RegistryInfo('host', 'username', 'password') if not service_info: service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'expose': ['80'], 'ports': ['8080'] } service_name = 'my_service' service_parser = Parser(group_info, registry_info, service_name, service_info) return service_parser def test_not_none(self): service_parser = self._get_default_parser() self.assertIsNotNone(service_parser) def test_get_service_name_label(self): service_name = 'my_service' service_parser = self._get_default_parser() expected = {'com.microsoft.acs.k8s.service_name': service_name} actual = service_parser._get_service_name_label() self.assertEquals(actual, expected) def test_get_empty_service_json(self): service_parser = self._get_default_parser() expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [] } } actual = service_parser._get_empty_service_json() self.assertEquals(actual, expected) def test_get_empty_deployment_json(self): service_parser = self._get_default_parser() service_name = 'my_service' expected = { "apiVersion": "extensions/v1beta1", "kind": "Deployment", "metadata": { "name": service_name }, "spec": { "replicas": 1, "template": { "metadata": { "labels": { 'com.microsoft.acs.k8s.service_name': service_name } }, "spec": { "containers": [{ "name": service_name }], "imagePullSecrets": [] } } } } actual = service_parser._get_empty_deployment_json() self.assertEquals(actual, expected) def test_add_label(self): service_parser = self._get_default_parser() service_parser._add_label('label_name', 'some_value') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'label_name': 'some_value', 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_label_no_name(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_label('', 'some_value') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_label_no_value(self): service_parser = self._get_default_parser() expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'some_label': '', 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } service_parser._add_label('some_label', '') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_image(self): service_parser = self._get_default_parser() service_parser._add_container_image('my_service', 'some_image') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'image': 'some_image' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_image_no_service(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_container_image('', 'some_image') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_image_no_image(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_container_image('my_service', '') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_image(self): service_parser = self._get_default_parser() expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'image': 'some_image' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } service_parser._parse_image('image') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_image_no_key(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._parse_image('blah') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_image_pull_secret(self): service_parser = self._get_default_parser() service_parser._add_image_pull_secret('secret_name') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [{ 'name': 'secret_name' }], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_image_pull_secret_no_name(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_image_pull_secret('') actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_port(self): service_parser = self._get_default_parser() service_parser._add_container_port(1234) expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'ports': [{ 'containerPort': 1234 }] }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_add_container_port_no_port(self): service_parser = self._get_default_parser() expected = copy.deepcopy(service_parser.deployment_json) service_parser._add_container_port(None) actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_get_service_json_no_service(self): service_parser = self._get_default_parser() self.assertIsNone(service_parser.get_service_json()) def test_get_service_json(self): service_parser = self._get_default_parser() service_parser.service_added = True expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [] } } actual = service_parser.service_json self.assertEquals(actual, expected) def test_create_new_ingress_rule_default_path(self): service_parser = self._get_default_parser() expected = { "host": 'myhost.com', "http": { "paths": [{ "path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } } actual = service_parser._create_new_ingress_rule( 'myhost.com', 1234, 'my_service') self.assertEquals(actual, expected) def test_create_new_ingress_rule_empty_path(self): service_parser = self._get_default_parser() expected = { "host": 'myhost.com', "http": { "paths": [{ "path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } } actual = service_parser._create_new_ingress_rule( 'myhost.com', 1234, 'my_service', path=None) self.assertEquals(actual, expected) def test_create_new_ingress_rule_custom_path(self): service_parser = self._get_default_parser() expected = { "host": 'myhost.com', "http": { "paths": [{ "path": "/path", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } } actual = service_parser._create_new_ingress_rule( 'myhost.com', 1234, 'my_service', path="/path") self.assertEquals(actual, expected) def test_create_new_ingress_rule_no_host(self): service_parser = self._get_default_parser() self.assertRaises( ValueError, service_parser._create_new_ingress_rule, None, 1234, 'my_service') def test_create_new_ingress_rule_no_service(self): service_parser = self._get_default_parser() self.assertRaises( ValueError, service_parser._create_new_ingress_rule, 'myhost.com', 1234, '') def test_create_new_ingress_rule_no_port(self): service_parser = self._get_default_parser() self.assertRaises( ValueError, service_parser._create_new_ingress_rule, 'myhost.com', None, 'blah') def test_add_ingress_rule(self): service_parser = self._get_default_parser() expected = [{ 'host': 'host.com', 'http': { 'paths': [{ 'path': '/', 'backend': { 'serviceName': 'my_service', 'servicePort': 1234 } }] } }] service_parser._add_ingress_rule('host.com', 1234, 'my_service') actual = service_parser.ingress_rules self.assertEquals(actual, expected) def test_add_ingress_rule_update_existing(self): service_parser = self._get_default_parser() service_parser.ingress_rules = [{ 'host': 'host.com', 'http': { 'paths': [{ 'path': '/', 'backend': { 'serviceName': 'my_service', 'servicePort': 1234 } }] } }] expected = [{ 'host': 'host.com', 'http': { 'paths': [{ 'path': '/', 'backend': { 'serviceName': 'my_service', 'servicePort': 1234 } }, { 'path': '/', 'backend': { 'serviceName': 'anotherservice', 'servicePort': 80 } }] } }] service_parser._add_ingress_rule('host.com', 80, 'anotherservice') actual = service_parser.ingress_rules self.assertEquals(actual, expected) def test_get_ingress_json(self): service_parser = self._get_default_parser() ingress_rules = [{ "host": "host.com", "http": { "paths": [{ "path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234 } }] } }] service_parser.ingress_rules = ingress_rules expected = {"kind": "Ingress", "spec": {"rules": [{"host": "host.com", "http": {"paths": [{"path": "/", "backend": { "serviceName": "my_service", "servicePort": 1234}}]}}]}, "apiVersion": "extensions/v1beta1", "metadata": {"name": "my_service"}} actual = service_parser.get_ingress_json() self.assertEquals(actual, json.dumps(expected)) def test_get_ingress_json_no_rules(self): service_parser = self._get_default_parser() self.assertIsNone(service_parser.get_ingress_json()) def test_get_port_name(self): service_parser = self._get_default_parser() expected = "port-80" actual = service_parser._get_port_name(80) self.assertEquals(actual, expected) def test_get_port_name_multiple(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": "port-80", "protocol": "TCP", "targetPort": 8080, "port": 80 }) expected = "port-80-1" actual = service_parser._get_port_name(80) self.assertEquals(actual, expected) def test_create_service(self): service_parser = self._get_default_parser() self.assertFalse(service_parser.service_added) service_parser._create_service((80, 8080)) expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [{ "name": "port-8080", "protocol": "TCP", "targetPort": 80, "port": 8080 }] } } self.assertTrue(service_parser.service_added) actual = service_parser.service_json self.assertEquals(actual, expected) def test_create_service_existing_ports(self): service_parser = self._get_default_parser() self.assertFalse(service_parser.service_added) service_parser._create_service((80, 8080)) expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [{ "name": "port-8080", "protocol": "TCP", "targetPort": 80, "port": 8080 }] } } service_parser._create_service((80, 8080)) self.assertTrue(service_parser.service_added) actual = service_parser.service_json self.assertEquals(actual, expected) def test_create_service_multiple_ports(self): service_parser = self._get_default_parser() self.assertFalse(service_parser.service_added) service_parser._create_service((80, 8080)) expected = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": 'my_service' }, "spec": { "selector": { 'com.microsoft.acs.k8s.service_name': 'my_service' }, "ports": [{ "name": "port-8080", "protocol": "TCP", "targetPort": 80, "port": 8080 }, { "name": "port-8080-1", "protocol": "TCP", "targetPort": 81, "port": 8080 }] } } service_parser._create_service((81, 8080)) self.assertTrue(service_parser.service_added) actual = service_parser.service_json self.assertEquals(actual, expected) def test_port_exists_default(self): service_parser = self._get_default_parser() self.assertFalse(service_parser._port_exists((80, 8080))) def test_port_exists_none(self): service_parser = self._get_default_parser() self.assertFalse(service_parser._port_exists(None)) def test_port_exists(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 80, "port": 8080 }) self.assertTrue(service_parser._port_exists((80, 8080))) def test_port_exists_false(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 80, "port": 8080 }) self.assertFalse(service_parser._port_exists((81, 8080))) def test_port_exists_multiple(self): service_parser = self._get_default_parser() service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 80, "port": 8080 }) service_parser.service_json['spec']['ports'].append({ "name": 'port-8080', "protocol": "TCP", "targetPort": 81, "port": 8080 }) self.assertTrue(service_parser._port_exists((81, 8080))) def test_parse_environment(self): service_parser = self._get_default_parser() service_parser._parse_environment('environment') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'env': [{ 'name': 'variable_one', 'value': 'value_one' }] }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_environment_list(self): service_info = { 'image': 'some_image', 'environment': ['variable_one=value_one', 'variable_two=value_two'] } service_parser = self._get_default_parser(service_info) service_parser._parse_environment('environment') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service', 'env': [{ 'name': 'variable_one', 'value': 'value_one' }, { 'name': 'variable_two', 'value': 'value_two' }] }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_expose(self): service_parser = self._get_default_parser() expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-80', 'port': 80 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_expose_multiple_ports(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'expose': ['80', '8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-80', 'port': 80 }, { 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_expose_no_expose(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' } } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports(self): service_parser = self._get_default_parser() expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_pair(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['80:8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_range(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['80-81:90-91'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-90', 'port': 90 }, { 'targetPort': 81, 'protocol': 'TCP', 'name': 'port-91', 'port': 91 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_and_expose_no_dupes(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['8080'], 'expose': ['8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_ports_and_expose(self): service_info = { 'image': 'some_image', 'environment': { 'variable_one': 'value_one' }, 'ports': ['80:8080'], 'expose': ['8080'] } service_parser = self._get_default_parser(service_info) expected = { 'kind': 'Service', 'spec': { 'ports': [{ 'targetPort': 80, 'protocol': 'TCP', 'name': 'port-8080', 'port': 8080 }, { 'targetPort': 8080, 'protocol': 'TCP', 'name': 'port-8080-1', 'port': 8080 }], 'selector': { 'com.microsoft.acs.k8s.service_name': 'my_service' } }, 'apiVersion': 'v1', 'metadata': { 'name': 'my_service' } } service_parser._parse_ports('ports') service_parser._parse_expose('expose') actual = service_parser.service_json self.assertEquals(actual, expected) def test_parse_labels(self): service_info = { 'labels': {'my_label': 'label_value'}, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': 'label_value' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_labels_ignore_com_ms(self): service_info = { 'labels': { 'my_label': 'label_value', 'com.microsoft.acs.kubernetes.vhosts': 'should_be_ignored' }, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': 'label_value' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_labels_single_string(self): service_info = { 'labels': { 'my_label=some_value' }, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': 'some_value' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_parse_labels_no_value(self): service_info = { 'labels': { 'my_label' }, 'image': 'some_image', } service_parser = self._get_default_parser(service_info) service_parser._parse_labels('labels') expected = { 'kind': 'Deployment', 'spec': { 'template': { 'spec': { 'imagePullSecrets': [], 'containers': [{ 'name': 'my_service' }] }, 'metadata': { 'labels': { 'com.microsoft.acs.k8s.service_name': 'my_service', 'my_label': '' } } }, 'replicas': 1 }, 'apiVersion': 'extensions/v1beta1', 'metadata': { 'name': 'my_service' } } actual = service_parser.deployment_json self.assertEquals(actual, expected) def test_get_deployment_json(self): service_info = {'environment': {'APPINSIGHTS_INSTRUMENTATIONKEY': None}, 'image': 'peterjausovec-exp.azurecr.io/peterjausovecsampleapp_service-a@sha256:67a44ab41d40e8c5b76530dd525008fef0d16f07b5e4e486ea569c88de543b9f', 'depends_on': ['service-b'], 'expose': ['8080'], 'labels': {'com.microsoft.acs.kubernetes.vhosts': '["www.containers.site", "api.containers.site:1234"]', 'some_label': 'label-value'}, 'ports': ['8080:80']} expected = { "kind": "Deployment", "spec": { "template": { "spec": { "imagePullSecrets": [{ "name": "host" }], "containers": [{ "image": "peterjausovec-exp.azurecr.io/peterjausovecsampleapp_service-a@sha256:67a44ab41d40e8c5b76530dd525008fef0d16f07b5e4e486ea569c88de543b9f", "name": "my_service", "env": [{ "name": "APPINSIGHTS_INSTRUMENTATIONKEY", "value": "" }], "ports": [{ "containerPort": 80 }, { "containerPort": 8080 }] }] }, "metadata": { "labels": { "some_label": "label-value", "com.microsoft.acs.k8s.service_name": "my_service" } } }, "replicas": 1 }, "apiVersion": "extensions/v1beta1", "metadata": { "name": "my_service" } } service_parser = self._get_default_parser(service_info) actual = service_parser.get_deployment_json() self.assertEquals(actual, json.dumps(expected))
0.568775
0.192065
import os import json import argparse import numpy as np from sklearn.model_selection import train_test_split import torch import torch.optim as optimiser import torch.nn.functional as F from torch.utils.data import DataLoader from tqdm import tqdm from core.dataset import LungDataset from core.model import PointNetDenseCls from utils.transform import feature_transform_regularizer __DEVICE__ = "cuda" if torch.cuda.is_available() else "cpu" __PIN_MEMORY__ = True if __DEVICE__ == "cuda" else False class ProgramArguments(object): def __init__(self): self.input_config = None def _prepare_data(config: dict): root = config["root"] path = os.path.join(root, config["lung"]) points_path = list() for file_name in os.listdir(os.path.join(path, "points")): points_path.append(os.path.join(path, "points", file_name)) labels_path = list() for file_name in os.listdir(os.path.join(path, "points_label")): labels_path.append(os.path.join(path, "points_label", file_name)) split = train_test_split(points_path, labels_path, test_size=config["split"], random_state=42) train_points, test_points = split[:2] train_labels, test_labels = split[2:] train_dataset = LungDataset(train_points, train_labels) test_dataset = LungDataset(test_points, test_labels) # TODO: Suspected PyTorch bug when try to pin the memory: # A leaking CAFFE2 thread-pool after fork. Possibly doesn't really matter but let's ignore the ping_memory for now. # create the training data loaders train_loader = DataLoader(train_dataset, shuffle=True, batch_size=config["batch_size"], # pin_memory=__PIN_MEMORY__, num_workers=config["workers"]) # create the test data loaders test_loader = DataLoader(test_dataset, shuffle=False, batch_size=config["batch_size"], # pin_memory=__PIN_MEMORY__, num_workers=config["workers"]) return train_dataset, test_dataset, train_loader, test_loader def train(config: dict, train_loader: DataLoader, test_loader: DataLoader, train_dataset: LungDataset): blue_log = lambda x: '\033[94m' + x + '\033[0m' num_classes = 3 model = PointNetDenseCls(k=num_classes, feature_transform=config["feature_transform"]) optimizer = optimiser.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999)) scheduler = optimiser.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.5) model.to(__DEVICE__) num_batch = len(train_dataset) // config["batch_size"] for epoch in range(config["epoch"]): scheduler.step() for i, data in enumerate(train_loader, 0): points, target = data points = points.transpose(2, 1) points, target = points.to(__DEVICE__), target.to(__DEVICE__) optimizer.zero_grad() classifier = model.train() pred, trans, trans_feat = classifier(points) pred = pred.view(-1, num_classes) target = target.view(-1, 1)[:, 0] - 1 loss = F.nll_loss(pred, target) if config["feature_transform"] == "True": loss += feature_transform_regularizer(trans_feat, __DEVICE__) * 0.001 loss.backward() optimizer.step() pred_choice = pred.data.max(1)[1] correct = pred_choice.eq(target.data).cpu().sum() print(f"[{epoch}: {i} / {num_batch}] train loss: {loss.item()} " f"accuracy: {correct.item() / float(config['batch_size'] * 2500)}") if i % 10 == 0: j, data = next(enumerate(test_loader, 0)) points, target = data points = points.transpose(2, 1) points, target = points.to(__DEVICE__), target.to(__DEVICE__) classifier = classifier.eval() pred, _, _ = classifier(points) pred = pred.view(-1, num_classes) target = target.view(-1, 1)[:, 0] - 1 loss = F.nll_loss(pred, target) pred_choice = pred.data.max(1)[1] correct = pred_choice.eq(target.data).cpu().sum() b = blue_log('test') print(f"[{epoch}: {i} / {num_batch}] {b} loss: {loss.item()} " f"accuracy: {correct.item() / float(config['batch_size'] * 2500)}") torch.save(model.state_dict(), f"{config['output_model']}/seg_model_{epoch}.pth") shape_ious = [] for i, data in tqdm(enumerate(test_loader, 0)): points, target = data points = points.transpose(2, 1) points, target = points.to(__DEVICE__), target.to(__DEVICE__) classifier = model.eval() pred, _, _ = classifier(points) pred_choice = pred.data.max(2)[1] pred_np = pred_choice.cpu().data.numpy() target_np = target.cpu().data.numpy() - 1 for shape_idx in range(target_np.shape[0]): parts = range(num_classes) # np.unique(target_np[shape_idx]) part_ious = [] for part in parts: I = np.sum(np.logical_and(pred_np[shape_idx] == part, target_np[shape_idx] == part)) U = np.sum(np.logical_or(pred_np[shape_idx] == part, target_np[shape_idx] == part)) if U == 0: iou = 1 # If the union of groundtruth and prediction points is empty, then count part IoU as 1 else: iou = I / float(U) part_ious.append(iou) shape_ious.append(np.mean(part_ious)) print(f"mIOU: {np.mean(shape_ious)}") def main(): args = parse_args() if os.path.exists(args.input_config): with open(args.input_config, "r") as input_config: config = json.load(input_config) train_data, test_data, train_loader, test_loader = _prepare_data(config) print(f"[INFO] found {len(train_data)} samples in the training set...") print(f"[INFO] found {len(test_data)} samples in the test set...") train(config, train_loader, test_loader, train_data) def parse_args(): parser = argparse.ArgumentParser(description="Training a PointNet architecture on 3D lung data cloud.") parser.add_argument("input_config", help="Location of the configuration file.") program_arguments = ProgramArguments() parser.parse_args(namespace=program_arguments) return program_arguments if __name__ == '__main__': main()
lung-annotator/train.py
import os import json import argparse import numpy as np from sklearn.model_selection import train_test_split import torch import torch.optim as optimiser import torch.nn.functional as F from torch.utils.data import DataLoader from tqdm import tqdm from core.dataset import LungDataset from core.model import PointNetDenseCls from utils.transform import feature_transform_regularizer __DEVICE__ = "cuda" if torch.cuda.is_available() else "cpu" __PIN_MEMORY__ = True if __DEVICE__ == "cuda" else False class ProgramArguments(object): def __init__(self): self.input_config = None def _prepare_data(config: dict): root = config["root"] path = os.path.join(root, config["lung"]) points_path = list() for file_name in os.listdir(os.path.join(path, "points")): points_path.append(os.path.join(path, "points", file_name)) labels_path = list() for file_name in os.listdir(os.path.join(path, "points_label")): labels_path.append(os.path.join(path, "points_label", file_name)) split = train_test_split(points_path, labels_path, test_size=config["split"], random_state=42) train_points, test_points = split[:2] train_labels, test_labels = split[2:] train_dataset = LungDataset(train_points, train_labels) test_dataset = LungDataset(test_points, test_labels) # TODO: Suspected PyTorch bug when try to pin the memory: # A leaking CAFFE2 thread-pool after fork. Possibly doesn't really matter but let's ignore the ping_memory for now. # create the training data loaders train_loader = DataLoader(train_dataset, shuffle=True, batch_size=config["batch_size"], # pin_memory=__PIN_MEMORY__, num_workers=config["workers"]) # create the test data loaders test_loader = DataLoader(test_dataset, shuffle=False, batch_size=config["batch_size"], # pin_memory=__PIN_MEMORY__, num_workers=config["workers"]) return train_dataset, test_dataset, train_loader, test_loader def train(config: dict, train_loader: DataLoader, test_loader: DataLoader, train_dataset: LungDataset): blue_log = lambda x: '\033[94m' + x + '\033[0m' num_classes = 3 model = PointNetDenseCls(k=num_classes, feature_transform=config["feature_transform"]) optimizer = optimiser.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999)) scheduler = optimiser.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.5) model.to(__DEVICE__) num_batch = len(train_dataset) // config["batch_size"] for epoch in range(config["epoch"]): scheduler.step() for i, data in enumerate(train_loader, 0): points, target = data points = points.transpose(2, 1) points, target = points.to(__DEVICE__), target.to(__DEVICE__) optimizer.zero_grad() classifier = model.train() pred, trans, trans_feat = classifier(points) pred = pred.view(-1, num_classes) target = target.view(-1, 1)[:, 0] - 1 loss = F.nll_loss(pred, target) if config["feature_transform"] == "True": loss += feature_transform_regularizer(trans_feat, __DEVICE__) * 0.001 loss.backward() optimizer.step() pred_choice = pred.data.max(1)[1] correct = pred_choice.eq(target.data).cpu().sum() print(f"[{epoch}: {i} / {num_batch}] train loss: {loss.item()} " f"accuracy: {correct.item() / float(config['batch_size'] * 2500)}") if i % 10 == 0: j, data = next(enumerate(test_loader, 0)) points, target = data points = points.transpose(2, 1) points, target = points.to(__DEVICE__), target.to(__DEVICE__) classifier = classifier.eval() pred, _, _ = classifier(points) pred = pred.view(-1, num_classes) target = target.view(-1, 1)[:, 0] - 1 loss = F.nll_loss(pred, target) pred_choice = pred.data.max(1)[1] correct = pred_choice.eq(target.data).cpu().sum() b = blue_log('test') print(f"[{epoch}: {i} / {num_batch}] {b} loss: {loss.item()} " f"accuracy: {correct.item() / float(config['batch_size'] * 2500)}") torch.save(model.state_dict(), f"{config['output_model']}/seg_model_{epoch}.pth") shape_ious = [] for i, data in tqdm(enumerate(test_loader, 0)): points, target = data points = points.transpose(2, 1) points, target = points.to(__DEVICE__), target.to(__DEVICE__) classifier = model.eval() pred, _, _ = classifier(points) pred_choice = pred.data.max(2)[1] pred_np = pred_choice.cpu().data.numpy() target_np = target.cpu().data.numpy() - 1 for shape_idx in range(target_np.shape[0]): parts = range(num_classes) # np.unique(target_np[shape_idx]) part_ious = [] for part in parts: I = np.sum(np.logical_and(pred_np[shape_idx] == part, target_np[shape_idx] == part)) U = np.sum(np.logical_or(pred_np[shape_idx] == part, target_np[shape_idx] == part)) if U == 0: iou = 1 # If the union of groundtruth and prediction points is empty, then count part IoU as 1 else: iou = I / float(U) part_ious.append(iou) shape_ious.append(np.mean(part_ious)) print(f"mIOU: {np.mean(shape_ious)}") def main(): args = parse_args() if os.path.exists(args.input_config): with open(args.input_config, "r") as input_config: config = json.load(input_config) train_data, test_data, train_loader, test_loader = _prepare_data(config) print(f"[INFO] found {len(train_data)} samples in the training set...") print(f"[INFO] found {len(test_data)} samples in the test set...") train(config, train_loader, test_loader, train_data) def parse_args(): parser = argparse.ArgumentParser(description="Training a PointNet architecture on 3D lung data cloud.") parser.add_argument("input_config", help="Location of the configuration file.") program_arguments = ProgramArguments() parser.parse_args(namespace=program_arguments) return program_arguments if __name__ == '__main__': main()
0.50952
0.304623
from cc3d.core.PySteppables import * from collections import defaultdict from collections import namedtuple # For convenience we define a named tuple that will store anchor parameters AnchorData = namedtuple('AnchorData', 'lambda_ target_length max_length x y z') class FocalPointPlasticityAnchorSteppable(SteppableBasePy): def __init__(self, frequency=10): SteppableBasePy.__init__(self, frequency) self.anchor_dict = defaultdict(dict) def start(self): for cell in self.cell_list: if cell.id == 5: # it is a good idea to store anchor id because any modification to anchor parameters/ deletion # of an anchor require the anchor id anchor_data = AnchorData(lambda_=20.0, target_length=30.0, max_length=1000.0, x=1, y=1, z=0) anchor_id = self.focalPointPlasticityPlugin.createAnchor(cell, anchor_data.lambda_, anchor_data.target_length, anchor_data.max_length, anchor_data.x, anchor_data.y, anchor_data.z) self.anchor_dict[cell.id][anchor_id] = anchor_data def step(self, mcs): for cell in self.cell_list: if mcs < 100: for fppd in self.get_focal_point_plasticity_data_list(cell): print("CELL ID=", cell.id, " CELL TYPE=", cell.type, " volume=", cell.volume) print("fppd.neighborId", fppd.neighborAddress.id, " lambda=", fppd.lambdaDistance, " targetDistance=", fppd.targetDistance) for anchor_fppd in self.get_anchor_focal_point_plasticity_data_list(cell): print("ANCHORED CELL ID=", cell.id, " CELL TYPE=", cell.type, " volume=", cell.volume) print("lambda=", anchor_fppd.lambdaDistance, " targetDistance=", anchor_fppd.targetDistance, "anchor_x=", anchor_fppd.anchorPoint[0], "anchor_y=", anchor_fppd.anchorPoint[1], "anchor_z=", anchor_fppd.anchorPoint[2]) elif mcs > 200 and mcs < 300: # setting plasticity constraints to 0 for fppd in self.get_focal_point_plasticity_data_list(cell): print("fppd.neighborId", fppd.neighborAddress.id, " lambda=", fppd.lambdaDistance, " targetDistance=", fppd.targetDistance) # IMPORTANT: although you can access and manipulate focal point plasticity data directly # it is better to do it via setFocalPointPlasticityParameters # IMPORTANT: this way you ensure that data you change is changed in both cell1 and cell2 . # Otherwise if you do direct manipulation , make sure you change parameters in cell1 and # its focal point plasticity neighbor self.focalPointPlasticityPlugin.setFocalPointPlasticityParameters( cell, fppd.neighborAddress, 0.0, 0.0, 0.0) elif mcs == 400: anchor_list = self.get_anchor_focal_point_plasticity_data_list(cell) if len(anchor_list): for anchor_fppd in anchor_list: self.focalPointPlasticityPlugin.setAnchorParameters( cell, anchor_fppd.anchorId, anchor_fppd.lambdaDistance, anchor_fppd.targetDistance / 2.0, anchor_fppd.maxDistance, anchor_fppd.anchorPoint[0], anchor_fppd.anchorPoint[1], anchor_fppd.anchorPoint[2] ) elif mcs == 600: anchor_list = self.get_anchor_focal_point_plasticity_data_list(cell) if len(anchor_list): for anchor_fppd in anchor_list: self.focalPointPlasticityPlugin.deleteAnchor(cell, anchor_fppd.anchorId)
main/PluginDemos/FocalPointPlasticityAnchorsPython/Simulation/FocalPointPlasticityAnchorsSteppables.py
from cc3d.core.PySteppables import * from collections import defaultdict from collections import namedtuple # For convenience we define a named tuple that will store anchor parameters AnchorData = namedtuple('AnchorData', 'lambda_ target_length max_length x y z') class FocalPointPlasticityAnchorSteppable(SteppableBasePy): def __init__(self, frequency=10): SteppableBasePy.__init__(self, frequency) self.anchor_dict = defaultdict(dict) def start(self): for cell in self.cell_list: if cell.id == 5: # it is a good idea to store anchor id because any modification to anchor parameters/ deletion # of an anchor require the anchor id anchor_data = AnchorData(lambda_=20.0, target_length=30.0, max_length=1000.0, x=1, y=1, z=0) anchor_id = self.focalPointPlasticityPlugin.createAnchor(cell, anchor_data.lambda_, anchor_data.target_length, anchor_data.max_length, anchor_data.x, anchor_data.y, anchor_data.z) self.anchor_dict[cell.id][anchor_id] = anchor_data def step(self, mcs): for cell in self.cell_list: if mcs < 100: for fppd in self.get_focal_point_plasticity_data_list(cell): print("CELL ID=", cell.id, " CELL TYPE=", cell.type, " volume=", cell.volume) print("fppd.neighborId", fppd.neighborAddress.id, " lambda=", fppd.lambdaDistance, " targetDistance=", fppd.targetDistance) for anchor_fppd in self.get_anchor_focal_point_plasticity_data_list(cell): print("ANCHORED CELL ID=", cell.id, " CELL TYPE=", cell.type, " volume=", cell.volume) print("lambda=", anchor_fppd.lambdaDistance, " targetDistance=", anchor_fppd.targetDistance, "anchor_x=", anchor_fppd.anchorPoint[0], "anchor_y=", anchor_fppd.anchorPoint[1], "anchor_z=", anchor_fppd.anchorPoint[2]) elif mcs > 200 and mcs < 300: # setting plasticity constraints to 0 for fppd in self.get_focal_point_plasticity_data_list(cell): print("fppd.neighborId", fppd.neighborAddress.id, " lambda=", fppd.lambdaDistance, " targetDistance=", fppd.targetDistance) # IMPORTANT: although you can access and manipulate focal point plasticity data directly # it is better to do it via setFocalPointPlasticityParameters # IMPORTANT: this way you ensure that data you change is changed in both cell1 and cell2 . # Otherwise if you do direct manipulation , make sure you change parameters in cell1 and # its focal point plasticity neighbor self.focalPointPlasticityPlugin.setFocalPointPlasticityParameters( cell, fppd.neighborAddress, 0.0, 0.0, 0.0) elif mcs == 400: anchor_list = self.get_anchor_focal_point_plasticity_data_list(cell) if len(anchor_list): for anchor_fppd in anchor_list: self.focalPointPlasticityPlugin.setAnchorParameters( cell, anchor_fppd.anchorId, anchor_fppd.lambdaDistance, anchor_fppd.targetDistance / 2.0, anchor_fppd.maxDistance, anchor_fppd.anchorPoint[0], anchor_fppd.anchorPoint[1], anchor_fppd.anchorPoint[2] ) elif mcs == 600: anchor_list = self.get_anchor_focal_point_plasticity_data_list(cell) if len(anchor_list): for anchor_fppd in anchor_list: self.focalPointPlasticityPlugin.deleteAnchor(cell, anchor_fppd.anchorId)
0.677261
0.349366
import subprocess, sys, itertools, getpass username = getpass.getuser() usage_error = False allservers = ["maris%03i" % i for i in range(2, 68)] if len(sys.argv) == 2: if sys.argv[1].lower() == "default": servers = ["maris%03i" % i for i in range(25,33) + range(61,68)] elif sys.argv[1].lower() == "all": servers = allservers else: usage_error = True if len(sys.argv) == 1 or usage_error: print "Usage: %s [DEFAULT|ALL]" % sys.argv[0] print "Assuming ALL" print "" servers = allservers if "-v" in sys.argv: verbose = True else: verbose = False justown = False if "--own" in sys.argv: justown = True verbose = True thekilling = False if "--kill" in sys.argv: thekilling = True verbose = True justown = True processes = [subprocess.Popen(["ssh", server, "cat /proc/cpuinfo | grep processor | wc -l && uptime && ps -eo pcpu,pid,user,args | awk '{if ($1 > 95) print $0}'"], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")) for server in servers] total_cpu_available = 0 total_cpu = 0 total_serv_available = 0 for server,process in zip(servers, processes): data = process.stdout.read().strip().split("\n") if not data or not data[0]: print server, "[ offline ]" continue total_serv_available += 1 uptime = data[1].strip() nprocs = int(data[0].strip()) load = round(float(data[1].split()[-3][:-1])) available = int(nprocs - load) if available < 0: available = 0 total_cpu += nprocs total_cpu_available += available total_serv_available += 1 print server, "[% 2i/% 2i processors available]\t" % (available, nprocs), processes = [d.split(None, 3) for d in data[2:]] if not verbose: # summarize processes key = lambda x: x[2] users = [] for user, procs in itertools.groupby(sorted(processes, key=key), key=key): totalcpu = sum(float(p[0]) for p in procs) users.append((user, totalcpu)) print "\t".join("%s (%.1f%%)" % (user, totalcpu) for (user, totalcpu) in users) else: print "" # newline tokill = [] for process in sorted(processes): if process[2] == username or not justown: print "\t".join(process) tokill.append(process) if thekilling and tokill: kill = raw_input("Kill %i processes? [y/n]" % len(tokill)).upper() if kill == "Y": subprocess.Popen(["ssh", server, "kill " + " ".join(str(pid) for pcpu,pid,user,args in tokill)], stderr=open("/dev/null", "w")) print total_cpu_available, "/", total_cpu, "processors available on", total_serv_available, "hosts (%i%%)" % (((total_cpu_available) * 100) / total_cpu) print total_cpu - total_cpu_available, "processors in use (%i%%)" % (((total_cpu - total_cpu_available) * 100) / total_cpu)
tools/check_uptimes.py
import subprocess, sys, itertools, getpass username = getpass.getuser() usage_error = False allservers = ["maris%03i" % i for i in range(2, 68)] if len(sys.argv) == 2: if sys.argv[1].lower() == "default": servers = ["maris%03i" % i for i in range(25,33) + range(61,68)] elif sys.argv[1].lower() == "all": servers = allservers else: usage_error = True if len(sys.argv) == 1 or usage_error: print "Usage: %s [DEFAULT|ALL]" % sys.argv[0] print "Assuming ALL" print "" servers = allservers if "-v" in sys.argv: verbose = True else: verbose = False justown = False if "--own" in sys.argv: justown = True verbose = True thekilling = False if "--kill" in sys.argv: thekilling = True verbose = True justown = True processes = [subprocess.Popen(["ssh", server, "cat /proc/cpuinfo | grep processor | wc -l && uptime && ps -eo pcpu,pid,user,args | awk '{if ($1 > 95) print $0}'"], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")) for server in servers] total_cpu_available = 0 total_cpu = 0 total_serv_available = 0 for server,process in zip(servers, processes): data = process.stdout.read().strip().split("\n") if not data or not data[0]: print server, "[ offline ]" continue total_serv_available += 1 uptime = data[1].strip() nprocs = int(data[0].strip()) load = round(float(data[1].split()[-3][:-1])) available = int(nprocs - load) if available < 0: available = 0 total_cpu += nprocs total_cpu_available += available total_serv_available += 1 print server, "[% 2i/% 2i processors available]\t" % (available, nprocs), processes = [d.split(None, 3) for d in data[2:]] if not verbose: # summarize processes key = lambda x: x[2] users = [] for user, procs in itertools.groupby(sorted(processes, key=key), key=key): totalcpu = sum(float(p[0]) for p in procs) users.append((user, totalcpu)) print "\t".join("%s (%.1f%%)" % (user, totalcpu) for (user, totalcpu) in users) else: print "" # newline tokill = [] for process in sorted(processes): if process[2] == username or not justown: print "\t".join(process) tokill.append(process) if thekilling and tokill: kill = raw_input("Kill %i processes? [y/n]" % len(tokill)).upper() if kill == "Y": subprocess.Popen(["ssh", server, "kill " + " ".join(str(pid) for pcpu,pid,user,args in tokill)], stderr=open("/dev/null", "w")) print total_cpu_available, "/", total_cpu, "processors available on", total_serv_available, "hosts (%i%%)" % (((total_cpu_available) * 100) / total_cpu) print total_cpu - total_cpu_available, "processors in use (%i%%)" % (((total_cpu - total_cpu_available) * 100) / total_cpu)
0.065239
0.094929
import typing as ty import builtins import itertools from collections.abc import Iterator, AsyncIterator import pytest from hypothesis import given, assume, strategies as st import none #: Maximum range stop value not to have infinite loop tests. MAX_RANGE = (2 ** 13) - 1 @pytest.fixture def arange() -> ty.Type[ty.AsyncIterator[int]]: """Generate an asynchronous range iterator.""" class AsyncRange(AsyncIterator): __slots__ = ("_it",) def __init__(self, *args: ty.Optional[int]): s = builtins.slice(*args) start, stop, step = ( s.start or 0, s.stop or builtins.min(s.stop, MAX_RANGE), s.step or 1, ) self._it = builtins.iter(builtins.range(start, stop, step)) def __aiter__(self) -> "AsyncRange": return self async def __anext__(self) -> int: try: return builtins.next(self._it) except StopIteration: raise StopAsyncIteration return AsyncRange @pytest.fixture def astarrange() -> ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]]: """Generate an asynchronous star range iterator.""" class AsyncStarRange(AsyncIterator): __slots__ = ("_it",) def __init__(self, *args: ty.Optional[int], elements: int = 1): s = builtins.slice(*args) start, stop, step = ( s.start or 0, s.stop or builtins.min(s.stop, MAX_RANGE), s.step or 1, ) self._it = builtins.tuple( builtins.iter(builtins.range(start, stop, step)) for _ in builtins.range(elements) ) def __aiter__(self) -> "AsyncStarRange": return self async def __anext__(self) -> ty.Tuple[int, ...]: try: return builtins.tuple([builtins.next(x) for x in self._it]) except StopIteration: raise StopAsyncIteration return AsyncStarRange @pytest.fixture def starrange() -> ty.Type[ty.Iterator[ty.Tuple[int, ...]]]: """Generate a synchronous star range iterator.""" class StarRange(Iterator): __slots__ = ("_it",) def __init__(self, *args: ty.Optional[int], elements: int = 1): s = slice(*args) start, stop, step = ( s.start or 0, s.stop or min(s.stop, MAX_RANGE), s.step or 1, ) self._it = tuple(iter(range(start, stop, step)) for _ in range(elements)) def __iter__(self) -> "StarRange": return self def __next__(self) -> ty.Tuple[int, ...]: return tuple([next(x) for x in self._it]) return StarRange @pytest.fixture def noopiter() -> ty.Type[ty.AsyncIterator]: """Generate an asynchronous iterator which just raises ``StopAsyncIterator``. """ class NoopIter(AsyncIterator): __slots__ = () def __aiter__(self) -> "NoopIter": return self async def __anext__(self): raise StopAsyncIteration return NoopIter @pytest.fixture def repeatfalse() -> ty.Type[ty.AsyncIterator[bool]]: """Generate an asynchronous iterator which repeats ``False`` for a specified amount of times. """ class RepeatFalse(AsyncIterator): __slots__ = ("_it",) def __init__(self, times: int): self._it = iter(range(min(times, MAX_RANGE))) def __aiter__(self) -> "RepeatFalse": return self async def __anext__(self) -> bool: try: next(self._it) except StopIteration: raise StopAsyncIteration return False return RepeatFalse @pytest.fixture def repeattrue() -> ty.Type[ty.AsyncIterator[bool]]: """Generate an asynchronous iterator which repeats ``True`` for a specified amount of times. """ class RepeatTrue(AsyncIterator): __slots__ = ("_it",) def __init__(self, times: int): self._it = iter(range(min(times, MAX_RANGE))) def __aiter__(self) -> "RepeatTrue": return self async def __anext__(self) -> bool: try: next(self._it) except StopIteration: raise StopAsyncIteration return True return RepeatTrue @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_all_should_return_true( repeattrue: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only true values should return ``True``.""" assert await none.collection.a.all(repeattrue(stop)) is True @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_all_should_return_false( repeatfalse: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only false values should return ``False``.""" assert await none.collection.a.all(repeatfalse(stop)) is False @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_all_mixed_should_return_false( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """An iterable mixed with false and true values should return ``False``.""" assert await none.collection.a.all(arange(stop)) is False # Empty list will return ``False`` so start from ``1``. @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_any_should_return_true( repeattrue: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only true values should return ``True``.""" assert await none.collection.a.any(repeattrue(stop)) is True @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_any_should_return_false( repeatfalse: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only false values should return ``False``.""" assert await none.collection.a.any(repeatfalse(stop)) is False @pytest.mark.asyncio @given(stop=st.integers(2, MAX_RANGE)) async def test_any_mixed_should_return_true( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """An iterable mixed with false and true values should return ``True``.""" assert await none.collection.a.any(arange(stop)) is True @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_dropwhile_matches_itertools_dropwhile( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async dropwhile implementation follows the standard implementation. """ async def _lowerhalf(x): return x < int(stop / 2) target = list(itertools.dropwhile(lambda x: x < int(stop / 2), range(stop))) result = [x async for x in none.collection.a.dropwhile(_lowerhalf, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_enumerate_expected_result( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.enumerate`. """ async for i, x in none.collection.a.enumerate(arange(stop)): assert i == x @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_enumerate_matches_builtin_enumerate( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async enumerate implementation follows the standard implementation. """ target = list(enumerate(range(stop))) result = [x async for x in none.collection.a.enumerate(arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_filter_matches_builtin_filter( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async filter implementation follows the standard implementation. """ async def _pair(x): return (x % 2) == 0 target = list(filter(lambda x: (x % 2) == 0, range(stop))) result = [x async for x in none.collection.a.filter(_pair, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_filterfalse_matches_itertools_filterfalse( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async filterfalse implementation follows the standard implementation. """ async def _pair(x): return (x % 2) == 0 target = list(itertools.filterfalse(lambda x: (x % 2) == 0, range(stop))) result = [x async for x in none.collection.a.filterfalse(_pair, arange(stop))] assert result == target @pytest.mark.asyncio @given( start=st.integers(0, MAX_RANGE), stop=st.integers(0, MAX_RANGE), step=st.integers(0, MAX_RANGE), ) async def test_islice_matches_itertools_islice( arange: ty.Type[ty.AsyncIterator[int]], start: int, stop: int, step: int ): """Ensure that our async islice implementation follows the standard implementation. """ assume(step != 0) assume(start < stop) target = list(itertools.islice(range(stop), start, stop, step)) result = [ x async for x in none.collection.a.islice(arange(stop), start, stop, step) ] assert result == target @pytest.mark.parametrize("start,stop,step", [(1, 1, 0), (1, -1, 1), (-1, 1, 1)]) def test_islice_should_raise_valueerror_on_negative_indicies( noopiter: ty.Type[ty.AsyncIterator], start: int, stop: int, step: int ): """Giving negative indices to :class:`none.collection.a.islice` should raise a ``ValueError`` exception. """ with pytest.raises(ValueError): none.collection.a.islice(noopiter(), start, stop, step) @given(start=st.integers(0, MAX_RANGE), stop=st.integers(0, MAX_RANGE)) def test_islice_start_higher_than_stop_should_raise_valueerror_on_negative_indicies( noopiter: ty.Type[ty.AsyncIterator], start: int, stop: int ): """Providing a ``start`` value higher than ``stop`` should raise a ``ValueError``. """ assume(start > stop) with pytest.raises(ValueError): none.collection.a.islice(noopiter(), start, stop) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_iter_with_callable_matches_builtin_iter(stop: int): """Ensure that our async iter implementation follows the standard implementation when using a callable function/awaitable. """ sentinel = object() class _agen(object): def __init__(self, high: int, marker: ty.Any = sentinel): self._low = int(high / 2) self._cursor = 0 self._marker = marker async def __call__(self) -> ty.Union[int, ty.Any]: if self._cursor < self._low or self._cursor > self._low: self._cursor += 1 else: return self._marker return self._cursor class _gen(object): def __init__(self, high: int, marker: ty.Any = sentinel): self._low = int(high / 2) self._cursor = 0 self._marker = marker def __call__(self) -> ty.Union[int, ty.Any]: if self._cursor < self._low or self._cursor > self._low: self._cursor += 1 else: return self._marker return self._cursor target = [x for x in iter(_gen(stop), sentinel)] result = [x async for x in none.collection.a.iter(_agen(stop), sentinel)] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_expected_result(arange: ty.Type[ty.AsyncIterator[int]], stop: int): """Look for expected results which should returned by :class:`none.collection.a.map`. """ async def _add1(x: int) -> int: return x + 1 async for i, x in none.collection.a.enumerate( none.collection.a.map(_add1, arange(stop)), start=1 ): assert x == i def test_map_non_callable_should_raise_typeerror(noopiter: ty.Type[ty.AsyncIterator]): """Providing a non-callable object should raise a ``TypeError``.""" with pytest.raises(TypeError): none.collection.a.map(None, noopiter()) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_matches_builtin_map( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async map implementation follows the standard implementation. """ async def _add1(x: int) -> int: return x + 1 target = list(map(lambda x: x + 1, range(stop))) result = [x async for x in none.collection.a.map(_add1, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_two_iterables_expected_result( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.map` with two iterables given. """ async def _add(a: int, b: int) -> int: return a + b async for i, x in none.collection.a.enumerate( none.collection.a.map(_add, arange(stop), arange(stop)) ): assert x == (i + i) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_matches_builtin_map_with_two_iterables( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async map implementation follows the standard implementation with two iterables. """ async def _add(a: int, b: int) -> int: return a + b target = list(map(lambda a, b: a + b, range(stop), range(stop))) result = [x async for x in none.collection.a.map(_add, arange(stop), arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_next_should_provide_expected_value( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.enumerate`. """ async def _noop(x): return x it = none.collection.a.map(_noop, arange(stop)) for i in range(stop): assert await none.collection.a.next(it) == i @pytest.mark.asyncio async def test_map_exhausted_should_raise_stopasynciteration( noopiter: ty.Type[ty.AsyncIterator], ): """Reaching iterator exhaustion should raise a ``StopAsyncIteration`` exception. """ async def _noop(x): return x with pytest.raises(StopAsyncIteration): await none.collection.a.next(none.collection.a.map(_noop, noopiter())) @pytest.mark.asyncio async def test_next_exhausted_should_raise_stopasynciteration( noopiter: ty.Type[ty.AsyncIterator], ): """Reaching iterator exhaustion should raise a ``StopAsyncIteration`` exception. """ with pytest.raises(StopAsyncIteration): await none.collection.a.next(noopiter()) @pytest.mark.asyncio @pytest.mark.parametrize("default", [object(), None]) async def test_next_exhausted_should_return_default( noopiter: ty.Type[ty.AsyncIterator], default ): """Reaching iterator exhaustion should return the default value when provided. """ assert await none.collection.a.next(noopiter(), default=default) is default @pytest.mark.asyncio async def test_next_non_iterator_should_raise_typeerror(): """Providing a non-iterable object should raise a ``TypeError``.""" with pytest.raises(TypeError): await none.collection.a.next(1) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_onexlast_list_expected( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """At least one item from a given iterable should be returned except the last element. """ if stop > 1: target = list(range(stop))[:-1] else: target = list(range(stop)) result = [x async for x in none.collection.a.onexlast(arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_repeat_awaitable_callable(stop: int): """Ensure that :class:`none.collection.a.repeat` can repeat the value returned by an awaitable callable. """ async def _true(): return True result = [x async for x in none.collection.a.repeat(_true, times=stop)] assert len(result) == stop assert all(result) @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_starmap_expected_result( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.starmap`. """ async def _add1(x: int) -> int: return x + 1 async for i, x in none.collection.a.enumerate( none.collection.a.starmap(_add1, astarrange(stop)), start=1 ): assert x == i def test_starmap_non_callable_should_raise_typeerror( noopiter: ty.Type[ty.AsyncIterator], ): """Providing a non-callable object should raise a ``TypeError``.""" with pytest.raises(TypeError): none.collection.a.starmap(None, noopiter()) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_starmap_matches_builtin_starmap( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], starrange: ty.Type[ty.Iterator[ty.Tuple[int, ...]]], stop: int, ): """Ensure that our async starmap implementation follows the standard implementation. """ async def _add1(x: int) -> int: return x + 1 target = list(itertools.starmap(lambda x: x + 1, starrange(stop))) result = [x async for x in none.collection.a.starmap(_add1, astarrange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_startmap_two_elements_iterable_expected_result( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.start` with a two elements iterable given. """ async def _add(a: int, b: int) -> int: return a + b async for i, x in none.collection.a.enumerate( none.collection.a.starmap(_add, astarrange(stop, elements=2)) ): assert x == (i + i) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_starmap_matches_itertools_starmap_with_two_elements_iterable( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], starrange: ty.Type[ty.Iterator[ty.Tuple[int, ...]]], stop: int, ): """Ensure that our async starmap implementation follows the standard implementation with two elements. """ async def _add(a: int, b: int) -> int: return a + b target = list(itertools.starmap(lambda a, b: a + b, starrange(stop, elements=2))) result = [ x async for x in none.collection.a.starmap(_add, astarrange(stop, elements=2)) ] assert result == target @pytest.mark.asyncio async def test_starmap_exhausted_should_raise_stopasynciteration( noopiter: ty.Type[ty.AsyncIterator], ): """Reaching iterator exhaustion should raise a ``StopAsyncIteration`` exception. """ async def _noop(x): return x with pytest.raises(StopAsyncIteration): await none.collection.a.next(none.collection.a.starmap(_noop, noopiter())) @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_sum_matches_builtin_sum( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async sum implementation follows the standard implementation. """ target = sum(range(stop)) result = await none.collection.a.sum(arange(stop)) assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_takewhile_matches_itertools_takewhile( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async takewhile implementation follows the standard implementation. """ async def _lowerhalf(x): return x < int(stop / 2) target = list(itertools.takewhile(lambda x: x < int(stop / 2), range(stop))) result = [x async for x in none.collection.a.takewhile(_lowerhalf, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_xlast_list_expected(arange: ty.Type[ty.AsyncIterator[int]], stop: int): """All items from a given iterable should be returned except the last element. """ target = list(range(stop))[:-1] result = [x async for x in none.collection.a.xlast(arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_zip_matches_builtin_zip( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async zip implementation follows the standard implementation. """ target = list(zip(range(int(stop / 2)), range(int(stop)))) result = [ x async for x in none.collection.a.zip(arange(int(stop / 2)), arange(stop)) ] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_zip_longest_matches_itertools_zip_longest( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async zip_longest implementation follows the standard implementation. """ fillvalue = object() target = list( itertools.zip_longest( range(int(stop / 2)), range(int(stop)), fillvalue=fillvalue ) ) result = [ x async for x in none.collection.a.zip_longest( arange(int(stop / 2)), arange(stop), fillvalue=fillvalue ) ] assert result == target
tests/collection/test_a.py
import typing as ty import builtins import itertools from collections.abc import Iterator, AsyncIterator import pytest from hypothesis import given, assume, strategies as st import none #: Maximum range stop value not to have infinite loop tests. MAX_RANGE = (2 ** 13) - 1 @pytest.fixture def arange() -> ty.Type[ty.AsyncIterator[int]]: """Generate an asynchronous range iterator.""" class AsyncRange(AsyncIterator): __slots__ = ("_it",) def __init__(self, *args: ty.Optional[int]): s = builtins.slice(*args) start, stop, step = ( s.start or 0, s.stop or builtins.min(s.stop, MAX_RANGE), s.step or 1, ) self._it = builtins.iter(builtins.range(start, stop, step)) def __aiter__(self) -> "AsyncRange": return self async def __anext__(self) -> int: try: return builtins.next(self._it) except StopIteration: raise StopAsyncIteration return AsyncRange @pytest.fixture def astarrange() -> ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]]: """Generate an asynchronous star range iterator.""" class AsyncStarRange(AsyncIterator): __slots__ = ("_it",) def __init__(self, *args: ty.Optional[int], elements: int = 1): s = builtins.slice(*args) start, stop, step = ( s.start or 0, s.stop or builtins.min(s.stop, MAX_RANGE), s.step or 1, ) self._it = builtins.tuple( builtins.iter(builtins.range(start, stop, step)) for _ in builtins.range(elements) ) def __aiter__(self) -> "AsyncStarRange": return self async def __anext__(self) -> ty.Tuple[int, ...]: try: return builtins.tuple([builtins.next(x) for x in self._it]) except StopIteration: raise StopAsyncIteration return AsyncStarRange @pytest.fixture def starrange() -> ty.Type[ty.Iterator[ty.Tuple[int, ...]]]: """Generate a synchronous star range iterator.""" class StarRange(Iterator): __slots__ = ("_it",) def __init__(self, *args: ty.Optional[int], elements: int = 1): s = slice(*args) start, stop, step = ( s.start or 0, s.stop or min(s.stop, MAX_RANGE), s.step or 1, ) self._it = tuple(iter(range(start, stop, step)) for _ in range(elements)) def __iter__(self) -> "StarRange": return self def __next__(self) -> ty.Tuple[int, ...]: return tuple([next(x) for x in self._it]) return StarRange @pytest.fixture def noopiter() -> ty.Type[ty.AsyncIterator]: """Generate an asynchronous iterator which just raises ``StopAsyncIterator``. """ class NoopIter(AsyncIterator): __slots__ = () def __aiter__(self) -> "NoopIter": return self async def __anext__(self): raise StopAsyncIteration return NoopIter @pytest.fixture def repeatfalse() -> ty.Type[ty.AsyncIterator[bool]]: """Generate an asynchronous iterator which repeats ``False`` for a specified amount of times. """ class RepeatFalse(AsyncIterator): __slots__ = ("_it",) def __init__(self, times: int): self._it = iter(range(min(times, MAX_RANGE))) def __aiter__(self) -> "RepeatFalse": return self async def __anext__(self) -> bool: try: next(self._it) except StopIteration: raise StopAsyncIteration return False return RepeatFalse @pytest.fixture def repeattrue() -> ty.Type[ty.AsyncIterator[bool]]: """Generate an asynchronous iterator which repeats ``True`` for a specified amount of times. """ class RepeatTrue(AsyncIterator): __slots__ = ("_it",) def __init__(self, times: int): self._it = iter(range(min(times, MAX_RANGE))) def __aiter__(self) -> "RepeatTrue": return self async def __anext__(self) -> bool: try: next(self._it) except StopIteration: raise StopAsyncIteration return True return RepeatTrue @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_all_should_return_true( repeattrue: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only true values should return ``True``.""" assert await none.collection.a.all(repeattrue(stop)) is True @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_all_should_return_false( repeatfalse: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only false values should return ``False``.""" assert await none.collection.a.all(repeatfalse(stop)) is False @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_all_mixed_should_return_false( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """An iterable mixed with false and true values should return ``False``.""" assert await none.collection.a.all(arange(stop)) is False # Empty list will return ``False`` so start from ``1``. @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_any_should_return_true( repeattrue: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only true values should return ``True``.""" assert await none.collection.a.any(repeattrue(stop)) is True @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_any_should_return_false( repeatfalse: ty.Type[ty.AsyncIterator[bool]], stop: int ): """An iterable with only false values should return ``False``.""" assert await none.collection.a.any(repeatfalse(stop)) is False @pytest.mark.asyncio @given(stop=st.integers(2, MAX_RANGE)) async def test_any_mixed_should_return_true( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """An iterable mixed with false and true values should return ``True``.""" assert await none.collection.a.any(arange(stop)) is True @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_dropwhile_matches_itertools_dropwhile( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async dropwhile implementation follows the standard implementation. """ async def _lowerhalf(x): return x < int(stop / 2) target = list(itertools.dropwhile(lambda x: x < int(stop / 2), range(stop))) result = [x async for x in none.collection.a.dropwhile(_lowerhalf, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_enumerate_expected_result( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.enumerate`. """ async for i, x in none.collection.a.enumerate(arange(stop)): assert i == x @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_enumerate_matches_builtin_enumerate( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async enumerate implementation follows the standard implementation. """ target = list(enumerate(range(stop))) result = [x async for x in none.collection.a.enumerate(arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_filter_matches_builtin_filter( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async filter implementation follows the standard implementation. """ async def _pair(x): return (x % 2) == 0 target = list(filter(lambda x: (x % 2) == 0, range(stop))) result = [x async for x in none.collection.a.filter(_pair, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_filterfalse_matches_itertools_filterfalse( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async filterfalse implementation follows the standard implementation. """ async def _pair(x): return (x % 2) == 0 target = list(itertools.filterfalse(lambda x: (x % 2) == 0, range(stop))) result = [x async for x in none.collection.a.filterfalse(_pair, arange(stop))] assert result == target @pytest.mark.asyncio @given( start=st.integers(0, MAX_RANGE), stop=st.integers(0, MAX_RANGE), step=st.integers(0, MAX_RANGE), ) async def test_islice_matches_itertools_islice( arange: ty.Type[ty.AsyncIterator[int]], start: int, stop: int, step: int ): """Ensure that our async islice implementation follows the standard implementation. """ assume(step != 0) assume(start < stop) target = list(itertools.islice(range(stop), start, stop, step)) result = [ x async for x in none.collection.a.islice(arange(stop), start, stop, step) ] assert result == target @pytest.mark.parametrize("start,stop,step", [(1, 1, 0), (1, -1, 1), (-1, 1, 1)]) def test_islice_should_raise_valueerror_on_negative_indicies( noopiter: ty.Type[ty.AsyncIterator], start: int, stop: int, step: int ): """Giving negative indices to :class:`none.collection.a.islice` should raise a ``ValueError`` exception. """ with pytest.raises(ValueError): none.collection.a.islice(noopiter(), start, stop, step) @given(start=st.integers(0, MAX_RANGE), stop=st.integers(0, MAX_RANGE)) def test_islice_start_higher_than_stop_should_raise_valueerror_on_negative_indicies( noopiter: ty.Type[ty.AsyncIterator], start: int, stop: int ): """Providing a ``start`` value higher than ``stop`` should raise a ``ValueError``. """ assume(start > stop) with pytest.raises(ValueError): none.collection.a.islice(noopiter(), start, stop) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_iter_with_callable_matches_builtin_iter(stop: int): """Ensure that our async iter implementation follows the standard implementation when using a callable function/awaitable. """ sentinel = object() class _agen(object): def __init__(self, high: int, marker: ty.Any = sentinel): self._low = int(high / 2) self._cursor = 0 self._marker = marker async def __call__(self) -> ty.Union[int, ty.Any]: if self._cursor < self._low or self._cursor > self._low: self._cursor += 1 else: return self._marker return self._cursor class _gen(object): def __init__(self, high: int, marker: ty.Any = sentinel): self._low = int(high / 2) self._cursor = 0 self._marker = marker def __call__(self) -> ty.Union[int, ty.Any]: if self._cursor < self._low or self._cursor > self._low: self._cursor += 1 else: return self._marker return self._cursor target = [x for x in iter(_gen(stop), sentinel)] result = [x async for x in none.collection.a.iter(_agen(stop), sentinel)] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_expected_result(arange: ty.Type[ty.AsyncIterator[int]], stop: int): """Look for expected results which should returned by :class:`none.collection.a.map`. """ async def _add1(x: int) -> int: return x + 1 async for i, x in none.collection.a.enumerate( none.collection.a.map(_add1, arange(stop)), start=1 ): assert x == i def test_map_non_callable_should_raise_typeerror(noopiter: ty.Type[ty.AsyncIterator]): """Providing a non-callable object should raise a ``TypeError``.""" with pytest.raises(TypeError): none.collection.a.map(None, noopiter()) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_matches_builtin_map( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async map implementation follows the standard implementation. """ async def _add1(x: int) -> int: return x + 1 target = list(map(lambda x: x + 1, range(stop))) result = [x async for x in none.collection.a.map(_add1, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_two_iterables_expected_result( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.map` with two iterables given. """ async def _add(a: int, b: int) -> int: return a + b async for i, x in none.collection.a.enumerate( none.collection.a.map(_add, arange(stop), arange(stop)) ): assert x == (i + i) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_matches_builtin_map_with_two_iterables( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async map implementation follows the standard implementation with two iterables. """ async def _add(a: int, b: int) -> int: return a + b target = list(map(lambda a, b: a + b, range(stop), range(stop))) result = [x async for x in none.collection.a.map(_add, arange(stop), arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_map_next_should_provide_expected_value( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.enumerate`. """ async def _noop(x): return x it = none.collection.a.map(_noop, arange(stop)) for i in range(stop): assert await none.collection.a.next(it) == i @pytest.mark.asyncio async def test_map_exhausted_should_raise_stopasynciteration( noopiter: ty.Type[ty.AsyncIterator], ): """Reaching iterator exhaustion should raise a ``StopAsyncIteration`` exception. """ async def _noop(x): return x with pytest.raises(StopAsyncIteration): await none.collection.a.next(none.collection.a.map(_noop, noopiter())) @pytest.mark.asyncio async def test_next_exhausted_should_raise_stopasynciteration( noopiter: ty.Type[ty.AsyncIterator], ): """Reaching iterator exhaustion should raise a ``StopAsyncIteration`` exception. """ with pytest.raises(StopAsyncIteration): await none.collection.a.next(noopiter()) @pytest.mark.asyncio @pytest.mark.parametrize("default", [object(), None]) async def test_next_exhausted_should_return_default( noopiter: ty.Type[ty.AsyncIterator], default ): """Reaching iterator exhaustion should return the default value when provided. """ assert await none.collection.a.next(noopiter(), default=default) is default @pytest.mark.asyncio async def test_next_non_iterator_should_raise_typeerror(): """Providing a non-iterable object should raise a ``TypeError``.""" with pytest.raises(TypeError): await none.collection.a.next(1) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_onexlast_list_expected( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """At least one item from a given iterable should be returned except the last element. """ if stop > 1: target = list(range(stop))[:-1] else: target = list(range(stop)) result = [x async for x in none.collection.a.onexlast(arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_repeat_awaitable_callable(stop: int): """Ensure that :class:`none.collection.a.repeat` can repeat the value returned by an awaitable callable. """ async def _true(): return True result = [x async for x in none.collection.a.repeat(_true, times=stop)] assert len(result) == stop assert all(result) @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_starmap_expected_result( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.starmap`. """ async def _add1(x: int) -> int: return x + 1 async for i, x in none.collection.a.enumerate( none.collection.a.starmap(_add1, astarrange(stop)), start=1 ): assert x == i def test_starmap_non_callable_should_raise_typeerror( noopiter: ty.Type[ty.AsyncIterator], ): """Providing a non-callable object should raise a ``TypeError``.""" with pytest.raises(TypeError): none.collection.a.starmap(None, noopiter()) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_starmap_matches_builtin_starmap( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], starrange: ty.Type[ty.Iterator[ty.Tuple[int, ...]]], stop: int, ): """Ensure that our async starmap implementation follows the standard implementation. """ async def _add1(x: int) -> int: return x + 1 target = list(itertools.starmap(lambda x: x + 1, starrange(stop))) result = [x async for x in none.collection.a.starmap(_add1, astarrange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_startmap_two_elements_iterable_expected_result( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.start` with a two elements iterable given. """ async def _add(a: int, b: int) -> int: return a + b async for i, x in none.collection.a.enumerate( none.collection.a.starmap(_add, astarrange(stop, elements=2)) ): assert x == (i + i) @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_starmap_matches_itertools_starmap_with_two_elements_iterable( astarrange: ty.Type[ty.AsyncIterator[ty.Tuple[int, ...]]], starrange: ty.Type[ty.Iterator[ty.Tuple[int, ...]]], stop: int, ): """Ensure that our async starmap implementation follows the standard implementation with two elements. """ async def _add(a: int, b: int) -> int: return a + b target = list(itertools.starmap(lambda a, b: a + b, starrange(stop, elements=2))) result = [ x async for x in none.collection.a.starmap(_add, astarrange(stop, elements=2)) ] assert result == target @pytest.mark.asyncio async def test_starmap_exhausted_should_raise_stopasynciteration( noopiter: ty.Type[ty.AsyncIterator], ): """Reaching iterator exhaustion should raise a ``StopAsyncIteration`` exception. """ async def _noop(x): return x with pytest.raises(StopAsyncIteration): await none.collection.a.next(none.collection.a.starmap(_noop, noopiter())) @pytest.mark.asyncio @given(stop=st.integers(1, MAX_RANGE)) async def test_sum_matches_builtin_sum( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async sum implementation follows the standard implementation. """ target = sum(range(stop)) result = await none.collection.a.sum(arange(stop)) assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_takewhile_matches_itertools_takewhile( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async takewhile implementation follows the standard implementation. """ async def _lowerhalf(x): return x < int(stop / 2) target = list(itertools.takewhile(lambda x: x < int(stop / 2), range(stop))) result = [x async for x in none.collection.a.takewhile(_lowerhalf, arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_xlast_list_expected(arange: ty.Type[ty.AsyncIterator[int]], stop: int): """All items from a given iterable should be returned except the last element. """ target = list(range(stop))[:-1] result = [x async for x in none.collection.a.xlast(arange(stop))] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_zip_matches_builtin_zip( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async zip implementation follows the standard implementation. """ target = list(zip(range(int(stop / 2)), range(int(stop)))) result = [ x async for x in none.collection.a.zip(arange(int(stop / 2)), arange(stop)) ] assert result == target @pytest.mark.asyncio @given(stop=st.integers(0, MAX_RANGE)) async def test_zip_longest_matches_itertools_zip_longest( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async zip_longest implementation follows the standard implementation. """ fillvalue = object() target = list( itertools.zip_longest( range(int(stop / 2)), range(int(stop)), fillvalue=fillvalue ) ) result = [ x async for x in none.collection.a.zip_longest( arange(int(stop / 2)), arange(stop), fillvalue=fillvalue ) ] assert result == target
0.807347
0.419232
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['JobScheduleArgs', 'JobSchedule'] @pulumi.input_type class JobScheduleArgs: def __init__(__self__, *, automation_account_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], runbook_name: pulumi.Input[str], schedule_name: pulumi.Input[str], job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, run_on: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a JobSchedule resource. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ pulumi.set(__self__, "automation_account_name", automation_account_name) pulumi.set(__self__, "resource_group_name", resource_group_name) pulumi.set(__self__, "runbook_name", runbook_name) pulumi.set(__self__, "schedule_name", schedule_name) if job_schedule_id is not None: pulumi.set(__self__, "job_schedule_id", job_schedule_id) if parameters is not None: pulumi.set(__self__, "parameters", parameters) if run_on is not None: pulumi.set(__self__, "run_on", run_on) @property @pulumi.getter(name="automationAccountName") def automation_account_name(self) -> pulumi.Input[str]: """ The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "automation_account_name") @automation_account_name.setter def automation_account_name(self, value: pulumi.Input[str]): pulumi.set(self, "automation_account_name", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="runbookName") def runbook_name(self) -> pulumi.Input[str]: """ The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ return pulumi.get(self, "runbook_name") @runbook_name.setter def runbook_name(self, value: pulumi.Input[str]): pulumi.set(self, "runbook_name", value) @property @pulumi.getter(name="scheduleName") def schedule_name(self) -> pulumi.Input[str]: return pulumi.get(self, "schedule_name") @schedule_name.setter def schedule_name(self, value: pulumi.Input[str]): pulumi.set(self, "schedule_name", value) @property @pulumi.getter(name="jobScheduleId") def job_schedule_id(self) -> Optional[pulumi.Input[str]]: """ The UUID identifying the Automation Job Schedule. """ return pulumi.get(self, "job_schedule_id") @job_schedule_id.setter def job_schedule_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "job_schedule_id", value) @property @pulumi.getter def parameters(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. """ return pulumi.get(self, "parameters") @parameters.setter def parameters(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "parameters", value) @property @pulumi.getter(name="runOn") def run_on(self) -> Optional[pulumi.Input[str]]: """ Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ return pulumi.get(self, "run_on") @run_on.setter def run_on(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "run_on", value) @pulumi.input_type class _JobScheduleState: def __init__(__self__, *, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None): """ Input properties used for looking up and filtering JobSchedule resources. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ if automation_account_name is not None: pulumi.set(__self__, "automation_account_name", automation_account_name) if job_schedule_id is not None: pulumi.set(__self__, "job_schedule_id", job_schedule_id) if parameters is not None: pulumi.set(__self__, "parameters", parameters) if resource_group_name is not None: pulumi.set(__self__, "resource_group_name", resource_group_name) if run_on is not None: pulumi.set(__self__, "run_on", run_on) if runbook_name is not None: pulumi.set(__self__, "runbook_name", runbook_name) if schedule_name is not None: pulumi.set(__self__, "schedule_name", schedule_name) @property @pulumi.getter(name="automationAccountName") def automation_account_name(self) -> Optional[pulumi.Input[str]]: """ The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "automation_account_name") @automation_account_name.setter def automation_account_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "automation_account_name", value) @property @pulumi.getter(name="jobScheduleId") def job_schedule_id(self) -> Optional[pulumi.Input[str]]: """ The UUID identifying the Automation Job Schedule. """ return pulumi.get(self, "job_schedule_id") @job_schedule_id.setter def job_schedule_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "job_schedule_id", value) @property @pulumi.getter def parameters(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. """ return pulumi.get(self, "parameters") @parameters.setter def parameters(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "parameters", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> Optional[pulumi.Input[str]]: """ The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="runOn") def run_on(self) -> Optional[pulumi.Input[str]]: """ Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ return pulumi.get(self, "run_on") @run_on.setter def run_on(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "run_on", value) @property @pulumi.getter(name="runbookName") def runbook_name(self) -> Optional[pulumi.Input[str]]: """ The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ return pulumi.get(self, "runbook_name") @runbook_name.setter def runbook_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "runbook_name", value) @property @pulumi.getter(name="scheduleName") def schedule_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "schedule_name") @schedule_name.setter def schedule_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "schedule_name", value) class JobSchedule(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None, __props__=None): """ Links an Automation Runbook and Schedule. ## Example Usage This is an example of just the Job Schedule. ```python import pulumi import pulumi_azure as azure example = azure.automation.JobSchedule("example", automation_account_name="tf-automation-account", parameters={ "resourcegroup": "tf-rgr-vm", "vmname": "TF-VM-01", }, resource_group_name="tf-rgr-automation", runbook_name="Get-VirtualMachine", schedule_name="hour") ``` ## Import Automation Job Schedules can be imported using the `resource id`, e.g. ```sh $ pulumi import azure:automation/jobSchedule:JobSchedule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Automation/automationAccounts/account1/jobSchedules/10000000-1001-1001-1001-000000000001 ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ ... @overload def __init__(__self__, resource_name: str, args: JobScheduleArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Links an Automation Runbook and Schedule. ## Example Usage This is an example of just the Job Schedule. ```python import pulumi import pulumi_azure as azure example = azure.automation.JobSchedule("example", automation_account_name="tf-automation-account", parameters={ "resourcegroup": "tf-rgr-vm", "vmname": "TF-VM-01", }, resource_group_name="tf-rgr-automation", runbook_name="Get-VirtualMachine", schedule_name="hour") ``` ## Import Automation Job Schedules can be imported using the `resource id`, e.g. ```sh $ pulumi import azure:automation/jobSchedule:JobSchedule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Automation/automationAccounts/account1/jobSchedules/10000000-1001-1001-1001-000000000001 ``` :param str resource_name: The name of the resource. :param JobScheduleArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(JobScheduleArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = JobScheduleArgs.__new__(JobScheduleArgs) if automation_account_name is None and not opts.urn: raise TypeError("Missing required property 'automation_account_name'") __props__.__dict__["automation_account_name"] = automation_account_name __props__.__dict__["job_schedule_id"] = job_schedule_id __props__.__dict__["parameters"] = parameters if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["run_on"] = run_on if runbook_name is None and not opts.urn: raise TypeError("Missing required property 'runbook_name'") __props__.__dict__["runbook_name"] = runbook_name if schedule_name is None and not opts.urn: raise TypeError("Missing required property 'schedule_name'") __props__.__dict__["schedule_name"] = schedule_name super(JobSchedule, __self__).__init__( 'azure:automation/jobSchedule:JobSchedule', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None) -> 'JobSchedule': """ Get an existing JobSchedule resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _JobScheduleState.__new__(_JobScheduleState) __props__.__dict__["automation_account_name"] = automation_account_name __props__.__dict__["job_schedule_id"] = job_schedule_id __props__.__dict__["parameters"] = parameters __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["run_on"] = run_on __props__.__dict__["runbook_name"] = runbook_name __props__.__dict__["schedule_name"] = schedule_name return JobSchedule(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="automationAccountName") def automation_account_name(self) -> pulumi.Output[str]: """ The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "automation_account_name") @property @pulumi.getter(name="jobScheduleId") def job_schedule_id(self) -> pulumi.Output[str]: """ The UUID identifying the Automation Job Schedule. """ return pulumi.get(self, "job_schedule_id") @property @pulumi.getter def parameters(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. """ return pulumi.get(self, "parameters") @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Output[str]: """ The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "resource_group_name") @property @pulumi.getter(name="runOn") def run_on(self) -> pulumi.Output[Optional[str]]: """ Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ return pulumi.get(self, "run_on") @property @pulumi.getter(name="runbookName") def runbook_name(self) -> pulumi.Output[str]: """ The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ return pulumi.get(self, "runbook_name") @property @pulumi.getter(name="scheduleName") def schedule_name(self) -> pulumi.Output[str]: return pulumi.get(self, "schedule_name")
sdk/python/pulumi_azure/automation/job_schedule.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['JobScheduleArgs', 'JobSchedule'] @pulumi.input_type class JobScheduleArgs: def __init__(__self__, *, automation_account_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], runbook_name: pulumi.Input[str], schedule_name: pulumi.Input[str], job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, run_on: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a JobSchedule resource. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ pulumi.set(__self__, "automation_account_name", automation_account_name) pulumi.set(__self__, "resource_group_name", resource_group_name) pulumi.set(__self__, "runbook_name", runbook_name) pulumi.set(__self__, "schedule_name", schedule_name) if job_schedule_id is not None: pulumi.set(__self__, "job_schedule_id", job_schedule_id) if parameters is not None: pulumi.set(__self__, "parameters", parameters) if run_on is not None: pulumi.set(__self__, "run_on", run_on) @property @pulumi.getter(name="automationAccountName") def automation_account_name(self) -> pulumi.Input[str]: """ The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "automation_account_name") @automation_account_name.setter def automation_account_name(self, value: pulumi.Input[str]): pulumi.set(self, "automation_account_name", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="runbookName") def runbook_name(self) -> pulumi.Input[str]: """ The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ return pulumi.get(self, "runbook_name") @runbook_name.setter def runbook_name(self, value: pulumi.Input[str]): pulumi.set(self, "runbook_name", value) @property @pulumi.getter(name="scheduleName") def schedule_name(self) -> pulumi.Input[str]: return pulumi.get(self, "schedule_name") @schedule_name.setter def schedule_name(self, value: pulumi.Input[str]): pulumi.set(self, "schedule_name", value) @property @pulumi.getter(name="jobScheduleId") def job_schedule_id(self) -> Optional[pulumi.Input[str]]: """ The UUID identifying the Automation Job Schedule. """ return pulumi.get(self, "job_schedule_id") @job_schedule_id.setter def job_schedule_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "job_schedule_id", value) @property @pulumi.getter def parameters(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. """ return pulumi.get(self, "parameters") @parameters.setter def parameters(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "parameters", value) @property @pulumi.getter(name="runOn") def run_on(self) -> Optional[pulumi.Input[str]]: """ Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ return pulumi.get(self, "run_on") @run_on.setter def run_on(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "run_on", value) @pulumi.input_type class _JobScheduleState: def __init__(__self__, *, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None): """ Input properties used for looking up and filtering JobSchedule resources. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ if automation_account_name is not None: pulumi.set(__self__, "automation_account_name", automation_account_name) if job_schedule_id is not None: pulumi.set(__self__, "job_schedule_id", job_schedule_id) if parameters is not None: pulumi.set(__self__, "parameters", parameters) if resource_group_name is not None: pulumi.set(__self__, "resource_group_name", resource_group_name) if run_on is not None: pulumi.set(__self__, "run_on", run_on) if runbook_name is not None: pulumi.set(__self__, "runbook_name", runbook_name) if schedule_name is not None: pulumi.set(__self__, "schedule_name", schedule_name) @property @pulumi.getter(name="automationAccountName") def automation_account_name(self) -> Optional[pulumi.Input[str]]: """ The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "automation_account_name") @automation_account_name.setter def automation_account_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "automation_account_name", value) @property @pulumi.getter(name="jobScheduleId") def job_schedule_id(self) -> Optional[pulumi.Input[str]]: """ The UUID identifying the Automation Job Schedule. """ return pulumi.get(self, "job_schedule_id") @job_schedule_id.setter def job_schedule_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "job_schedule_id", value) @property @pulumi.getter def parameters(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. """ return pulumi.get(self, "parameters") @parameters.setter def parameters(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "parameters", value) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> Optional[pulumi.Input[str]]: """ The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="runOn") def run_on(self) -> Optional[pulumi.Input[str]]: """ Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ return pulumi.get(self, "run_on") @run_on.setter def run_on(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "run_on", value) @property @pulumi.getter(name="runbookName") def runbook_name(self) -> Optional[pulumi.Input[str]]: """ The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ return pulumi.get(self, "runbook_name") @runbook_name.setter def runbook_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "runbook_name", value) @property @pulumi.getter(name="scheduleName") def schedule_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "schedule_name") @schedule_name.setter def schedule_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "schedule_name", value) class JobSchedule(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None, __props__=None): """ Links an Automation Runbook and Schedule. ## Example Usage This is an example of just the Job Schedule. ```python import pulumi import pulumi_azure as azure example = azure.automation.JobSchedule("example", automation_account_name="tf-automation-account", parameters={ "resourcegroup": "tf-rgr-vm", "vmname": "TF-VM-01", }, resource_group_name="tf-rgr-automation", runbook_name="Get-VirtualMachine", schedule_name="hour") ``` ## Import Automation Job Schedules can be imported using the `resource id`, e.g. ```sh $ pulumi import azure:automation/jobSchedule:JobSchedule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Automation/automationAccounts/account1/jobSchedules/10000000-1001-1001-1001-000000000001 ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ ... @overload def __init__(__self__, resource_name: str, args: JobScheduleArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Links an Automation Runbook and Schedule. ## Example Usage This is an example of just the Job Schedule. ```python import pulumi import pulumi_azure as azure example = azure.automation.JobSchedule("example", automation_account_name="tf-automation-account", parameters={ "resourcegroup": "tf-rgr-vm", "vmname": "TF-VM-01", }, resource_group_name="tf-rgr-automation", runbook_name="Get-VirtualMachine", schedule_name="hour") ``` ## Import Automation Job Schedules can be imported using the `resource id`, e.g. ```sh $ pulumi import azure:automation/jobSchedule:JobSchedule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Automation/automationAccounts/account1/jobSchedules/10000000-1001-1001-1001-000000000001 ``` :param str resource_name: The name of the resource. :param JobScheduleArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(JobScheduleArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = JobScheduleArgs.__new__(JobScheduleArgs) if automation_account_name is None and not opts.urn: raise TypeError("Missing required property 'automation_account_name'") __props__.__dict__["automation_account_name"] = automation_account_name __props__.__dict__["job_schedule_id"] = job_schedule_id __props__.__dict__["parameters"] = parameters if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["run_on"] = run_on if runbook_name is None and not opts.urn: raise TypeError("Missing required property 'runbook_name'") __props__.__dict__["runbook_name"] = runbook_name if schedule_name is None and not opts.urn: raise TypeError("Missing required property 'schedule_name'") __props__.__dict__["schedule_name"] = schedule_name super(JobSchedule, __self__).__init__( 'azure:automation/jobSchedule:JobSchedule', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, automation_account_name: Optional[pulumi.Input[str]] = None, job_schedule_id: Optional[pulumi.Input[str]] = None, parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, run_on: Optional[pulumi.Input[str]] = None, runbook_name: Optional[pulumi.Input[str]] = None, schedule_name: Optional[pulumi.Input[str]] = None) -> 'JobSchedule': """ Get an existing JobSchedule resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] automation_account_name: The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] job_schedule_id: The UUID identifying the Automation Job Schedule. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. :param pulumi.Input[str] run_on: Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. :param pulumi.Input[str] runbook_name: The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _JobScheduleState.__new__(_JobScheduleState) __props__.__dict__["automation_account_name"] = automation_account_name __props__.__dict__["job_schedule_id"] = job_schedule_id __props__.__dict__["parameters"] = parameters __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["run_on"] = run_on __props__.__dict__["runbook_name"] = runbook_name __props__.__dict__["schedule_name"] = schedule_name return JobSchedule(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="automationAccountName") def automation_account_name(self) -> pulumi.Output[str]: """ The name of the Automation Account in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "automation_account_name") @property @pulumi.getter(name="jobScheduleId") def job_schedule_id(self) -> pulumi.Output[str]: """ The UUID identifying the Automation Job Schedule. """ return pulumi.get(self, "job_schedule_id") @property @pulumi.getter def parameters(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ A map of key/value pairs corresponding to the arguments that can be passed to the Runbook. Changing this forces a new resource to be created. """ return pulumi.get(self, "parameters") @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Output[str]: """ The name of the resource group in which the Job Schedule is created. Changing this forces a new resource to be created. """ return pulumi.get(self, "resource_group_name") @property @pulumi.getter(name="runOn") def run_on(self) -> pulumi.Output[Optional[str]]: """ Name of a Hybrid Worker Group the Runbook will be executed on. Changing this forces a new resource to be created. """ return pulumi.get(self, "run_on") @property @pulumi.getter(name="runbookName") def runbook_name(self) -> pulumi.Output[str]: """ The name of a Runbook to link to a Schedule. It needs to be in the same Automation Account as the Schedule and Job Schedule. Changing this forces a new resource to be created. """ return pulumi.get(self, "runbook_name") @property @pulumi.getter(name="scheduleName") def schedule_name(self) -> pulumi.Output[str]: return pulumi.get(self, "schedule_name")
0.847369
0.090253
class Solution: def neighbours(self, board, pixel): neighbours = set() row = pixel[0] col = pixel[1] ROW = len(board) COL = len(board[0]) if row - 1 > -1 and board[row-1][col] == 'O': neighbours.add((row-1, col)) if row + 1 < ROW and board[row+1][col] == 'O': neighbours.add((row+1, col)) if col - 1 > -1 and board[row][col-1] == 'O': neighbours.add((row, col-1)) if col + 1 < COL and board[row][col+1] == 'O': neighbours.add((row, col+1)) return neighbours def surround(self, board, pixel, close_set): ROW = len(board) COL = len(board[0]) open_set = set() open_set.add(pixel) surround = True adjacent_pixel = set() def boundary(pixel): row = pixel[0] col = pixel[1] return row == 0 or row == ROW-1 or col == 0 or col == COL-1 while len(open_set) > 0: pixel = open_set.pop() close_set.add(pixel) if boundary(pixel): surround = False adjacent_pixel.add(pixel) neighbours = self.neighbours(board, pixel) open_set.update( neighbours - close_set ) # flip board if surround: for pixel in adjacent_pixel: board[pixel[0]][pixel[1]] = 'X' # @param {character[][]} board # @return {void} Do not return anything, modify board in-place instead. def solve(self, board): if not board: return ROW = len(board) COL = len(board[0]) close_set = set() for index_row in range(ROW): for index_col in range(COL): if (index_row, index_col) in close_set or board[index_row][index_col] == 'X': continue pixel = (index_row, index_col) self.surround(board, pixel, close_set) if __name__ == '__main__': solution = Solution() board = ["XXXX","XOOX", "XXOX", "XOXX"] solution.solve(board) print board
python/surround_region.py
class Solution: def neighbours(self, board, pixel): neighbours = set() row = pixel[0] col = pixel[1] ROW = len(board) COL = len(board[0]) if row - 1 > -1 and board[row-1][col] == 'O': neighbours.add((row-1, col)) if row + 1 < ROW and board[row+1][col] == 'O': neighbours.add((row+1, col)) if col - 1 > -1 and board[row][col-1] == 'O': neighbours.add((row, col-1)) if col + 1 < COL and board[row][col+1] == 'O': neighbours.add((row, col+1)) return neighbours def surround(self, board, pixel, close_set): ROW = len(board) COL = len(board[0]) open_set = set() open_set.add(pixel) surround = True adjacent_pixel = set() def boundary(pixel): row = pixel[0] col = pixel[1] return row == 0 or row == ROW-1 or col == 0 or col == COL-1 while len(open_set) > 0: pixel = open_set.pop() close_set.add(pixel) if boundary(pixel): surround = False adjacent_pixel.add(pixel) neighbours = self.neighbours(board, pixel) open_set.update( neighbours - close_set ) # flip board if surround: for pixel in adjacent_pixel: board[pixel[0]][pixel[1]] = 'X' # @param {character[][]} board # @return {void} Do not return anything, modify board in-place instead. def solve(self, board): if not board: return ROW = len(board) COL = len(board[0]) close_set = set() for index_row in range(ROW): for index_col in range(COL): if (index_row, index_col) in close_set or board[index_row][index_col] == 'X': continue pixel = (index_row, index_col) self.surround(board, pixel, close_set) if __name__ == '__main__': solution = Solution() board = ["XXXX","XOOX", "XXOX", "XOXX"] solution.solve(board) print board
0.672117
0.576363
import os import time import json import torch import dill import random import pathlib import evaluation import numpy as np import visualization as vis from argument_parser import args from model.online.online_trajectron import OnlineTrajectron from model.model_registrar import ModelRegistrar from environment import Environment, Scene import matplotlib.pyplot as plt if not torch.cuda.is_available() or args.device == 'cpu': args.device = torch.device('cpu') else: if torch.cuda.device_count() == 1: # If you have CUDA_VISIBLE_DEVICES set, which you should, # then this will prevent leftover flag arguments from # messing with the device allocation. args.device = 'cuda:0' args.device = torch.device(args.device) if args.eval_device is None: args.eval_device = 'cpu' if args.seed is not None: random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.seed) def create_online_env(env, hyperparams, scene_idx, init_timestep): test_scene = env.scenes[scene_idx] online_scene = Scene(timesteps=init_timestep + 1, map=test_scene.map, dt=test_scene.dt) online_scene.nodes = test_scene.get_nodes_clipped_at_time( timesteps=np.arange(init_timestep - hyperparams['maximum_history_length'], init_timestep + 1), state=hyperparams['state']) online_scene.robot = test_scene.robot online_scene.calculate_scene_graph(attention_radius=env.attention_radius, edge_addition_filter=hyperparams['edge_addition_filter'], edge_removal_filter=hyperparams['edge_removal_filter']) return Environment(node_type_list=env.node_type_list, standardization=env.standardization, scenes=[online_scene], attention_radius=env.attention_radius, robot_type=env.robot_type) def get_maps_for_input(input_dict, scene, hyperparams): scene_maps = list() scene_pts = list() heading_angles = list() patch_sizes = list() nodes_with_maps = list() for node in input_dict: if node.type in hyperparams['map_encoder']: x = input_dict[node] me_hyp = hyperparams['map_encoder'][node.type] if 'heading_state_index' in me_hyp: heading_state_index = me_hyp['heading_state_index'] # We have to rotate the map in the opposit direction of the agent to match them if type(heading_state_index) is list: # infer from velocity or heading vector heading_angle = -np.arctan2(x[-1, heading_state_index[1]], x[-1, heading_state_index[0]]) * 180 / np.pi else: heading_angle = -x[-1, heading_state_index] * 180 / np.pi else: heading_angle = None scene_map = scene.map[node.type] map_point = x[-1, :2] patch_size = hyperparams['map_encoder'][node.type]['patch_size'] scene_maps.append(scene_map) scene_pts.append(map_point) heading_angles.append(heading_angle) patch_sizes.append(patch_size) nodes_with_maps.append(node) if heading_angles[0] is None: heading_angles = None else: heading_angles = torch.Tensor(heading_angles) maps = scene_maps[0].get_cropped_maps_from_scene_map_batch(scene_maps, scene_pts=torch.Tensor(scene_pts), patch_size=patch_sizes[0], rotation=heading_angles) maps_dict = {node: maps[[i]] for i, node in enumerate(nodes_with_maps)} return maps_dict def main(): # Choose one of the model directory names under the experiment/*/models folders. # Possibilities are 'vel_ee', 'int_ee', 'int_ee_me', or 'robot' model_dir = os.path.join(args.log_dir, 'int_ee') # Load hyperparameters from json config_file = os.path.join(model_dir, args.conf) if not os.path.exists(config_file): raise ValueError('Config json not found!') with open(config_file, 'r') as conf_json: hyperparams = json.load(conf_json) # Add hyperparams from arguments hyperparams['dynamic_edges'] = args.dynamic_edges hyperparams['edge_state_combine_method'] = args.edge_state_combine_method hyperparams['edge_influence_combine_method'] = args.edge_influence_combine_method hyperparams['edge_addition_filter'] = args.edge_addition_filter hyperparams['edge_removal_filter'] = args.edge_removal_filter hyperparams['batch_size'] = args.batch_size hyperparams['k_eval'] = args.k_eval hyperparams['offline_scene_graph'] = args.offline_scene_graph hyperparams['incl_robot_node'] = args.incl_robot_node hyperparams['edge_encoding'] = not args.no_edge_encoding hyperparams['use_map_encoding'] = args.map_encoding output_save_dir = os.path.join(model_dir, 'pred_figs') pathlib.Path(output_save_dir).mkdir(parents=True, exist_ok=True) eval_data_path = os.path.join(args.data_dir, args.eval_data_dict) with open(eval_data_path, 'rb') as f: eval_env = dill.load(f, encoding='latin1') if eval_env.robot_type is None and hyperparams['incl_robot_node']: eval_env.robot_type = eval_env.NodeType[0] # TODO: Make more general, allow the user to specify? for scene in eval_env.scenes: scene.add_robot_from_nodes(eval_env.robot_type) print('Loaded data from %s' % (eval_data_path,)) # Creating a dummy environment with a single scene that contains information about the world. # When using this code, feel free to use whichever scene index or initial timestep you wish. scene_idx = 0 # You need to have at least acceleration, so you want 2 timesteps of prior data, e.g. [0, 1], # so that you can immediately start incremental inference from the 3rd timestep onwards. init_timestep = 1 eval_scene = eval_env.scenes[scene_idx] online_env = create_online_env(eval_env, hyperparams, scene_idx, init_timestep) model_registrar = ModelRegistrar(model_dir, args.eval_device) model_registrar.load_models(iter_num=12) trajectron = OnlineTrajectron(model_registrar, hyperparams, args.eval_device) # If you want to see what different robot futures do to the predictions, uncomment this line as well as # related "... += adjustment" lines below. # adjustment = np.stack([np.arange(13)/float(i*2.0) for i in range(6, 12)], axis=1) # Here's how you'd incrementally run the model, e.g. with streaming data. trajectron.set_environment(online_env, init_timestep) for timestep in range(init_timestep + 1, eval_scene.timesteps): input_dict = eval_scene.get_clipped_input_dict(timestep, hyperparams['state']) maps = None if hyperparams['use_map_encoding']: maps = get_maps_for_input(input_dict, eval_scene, hyperparams) robot_present_and_future = None if eval_scene.robot is not None and hyperparams['incl_robot_node']: robot_present_and_future = eval_scene.robot.get(np.array([timestep, timestep + hyperparams['prediction_horizon']]), hyperparams['state'][eval_scene.robot.type], padding=0.0) robot_present_and_future = np.stack([robot_present_and_future, robot_present_and_future], axis=0) # robot_present_and_future += adjustment start = time.time() dists, preds = trajectron.incremental_forward(input_dict, maps, prediction_horizon=6, num_samples=1, robot_present_and_future=robot_present_and_future, full_dist=True) end = time.time() print("t=%d: took %.2f s (= %.2f Hz) w/ %d nodes and %d edges" % (timestep, end - start, 1. / (end - start), len(trajectron.nodes), trajectron.scene_graph.get_num_edges())) detailed_preds_dict = dict() for node in eval_scene.nodes: if node in preds: detailed_preds_dict[node] = preds[node] fig, ax = plt.subplots() vis.visualize_distribution(ax, dists) vis.visualize_prediction(ax, {timestep: preds}, eval_scene.dt, hyperparams['maximum_history_length'], hyperparams['prediction_horizon']) if eval_scene.robot is not None and hyperparams['incl_robot_node']: robot_for_plotting = eval_scene.robot.get(np.array([timestep, timestep + hyperparams['prediction_horizon']]), hyperparams['state'][eval_scene.robot.type]) # robot_for_plotting += adjustment ax.plot(robot_for_plotting[1:, 1], robot_for_plotting[1:, 0], color='r', linewidth=1.0, alpha=1.0) # Current Node Position circle = plt.Circle((robot_for_plotting[0, 1], robot_for_plotting[0, 0]), 0.3, facecolor='r', edgecolor='k', lw=0.5, zorder=3) ax.add_artist(circle) fig.savefig(os.path.join(output_save_dir, f'pred_{timestep}.pdf'), dpi=300) plt.close(fig) if __name__ == '__main__': main()
trajectron/test_online.py
import os import time import json import torch import dill import random import pathlib import evaluation import numpy as np import visualization as vis from argument_parser import args from model.online.online_trajectron import OnlineTrajectron from model.model_registrar import ModelRegistrar from environment import Environment, Scene import matplotlib.pyplot as plt if not torch.cuda.is_available() or args.device == 'cpu': args.device = torch.device('cpu') else: if torch.cuda.device_count() == 1: # If you have CUDA_VISIBLE_DEVICES set, which you should, # then this will prevent leftover flag arguments from # messing with the device allocation. args.device = 'cuda:0' args.device = torch.device(args.device) if args.eval_device is None: args.eval_device = 'cpu' if args.seed is not None: random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(args.seed) def create_online_env(env, hyperparams, scene_idx, init_timestep): test_scene = env.scenes[scene_idx] online_scene = Scene(timesteps=init_timestep + 1, map=test_scene.map, dt=test_scene.dt) online_scene.nodes = test_scene.get_nodes_clipped_at_time( timesteps=np.arange(init_timestep - hyperparams['maximum_history_length'], init_timestep + 1), state=hyperparams['state']) online_scene.robot = test_scene.robot online_scene.calculate_scene_graph(attention_radius=env.attention_radius, edge_addition_filter=hyperparams['edge_addition_filter'], edge_removal_filter=hyperparams['edge_removal_filter']) return Environment(node_type_list=env.node_type_list, standardization=env.standardization, scenes=[online_scene], attention_radius=env.attention_radius, robot_type=env.robot_type) def get_maps_for_input(input_dict, scene, hyperparams): scene_maps = list() scene_pts = list() heading_angles = list() patch_sizes = list() nodes_with_maps = list() for node in input_dict: if node.type in hyperparams['map_encoder']: x = input_dict[node] me_hyp = hyperparams['map_encoder'][node.type] if 'heading_state_index' in me_hyp: heading_state_index = me_hyp['heading_state_index'] # We have to rotate the map in the opposit direction of the agent to match them if type(heading_state_index) is list: # infer from velocity or heading vector heading_angle = -np.arctan2(x[-1, heading_state_index[1]], x[-1, heading_state_index[0]]) * 180 / np.pi else: heading_angle = -x[-1, heading_state_index] * 180 / np.pi else: heading_angle = None scene_map = scene.map[node.type] map_point = x[-1, :2] patch_size = hyperparams['map_encoder'][node.type]['patch_size'] scene_maps.append(scene_map) scene_pts.append(map_point) heading_angles.append(heading_angle) patch_sizes.append(patch_size) nodes_with_maps.append(node) if heading_angles[0] is None: heading_angles = None else: heading_angles = torch.Tensor(heading_angles) maps = scene_maps[0].get_cropped_maps_from_scene_map_batch(scene_maps, scene_pts=torch.Tensor(scene_pts), patch_size=patch_sizes[0], rotation=heading_angles) maps_dict = {node: maps[[i]] for i, node in enumerate(nodes_with_maps)} return maps_dict def main(): # Choose one of the model directory names under the experiment/*/models folders. # Possibilities are 'vel_ee', 'int_ee', 'int_ee_me', or 'robot' model_dir = os.path.join(args.log_dir, 'int_ee') # Load hyperparameters from json config_file = os.path.join(model_dir, args.conf) if not os.path.exists(config_file): raise ValueError('Config json not found!') with open(config_file, 'r') as conf_json: hyperparams = json.load(conf_json) # Add hyperparams from arguments hyperparams['dynamic_edges'] = args.dynamic_edges hyperparams['edge_state_combine_method'] = args.edge_state_combine_method hyperparams['edge_influence_combine_method'] = args.edge_influence_combine_method hyperparams['edge_addition_filter'] = args.edge_addition_filter hyperparams['edge_removal_filter'] = args.edge_removal_filter hyperparams['batch_size'] = args.batch_size hyperparams['k_eval'] = args.k_eval hyperparams['offline_scene_graph'] = args.offline_scene_graph hyperparams['incl_robot_node'] = args.incl_robot_node hyperparams['edge_encoding'] = not args.no_edge_encoding hyperparams['use_map_encoding'] = args.map_encoding output_save_dir = os.path.join(model_dir, 'pred_figs') pathlib.Path(output_save_dir).mkdir(parents=True, exist_ok=True) eval_data_path = os.path.join(args.data_dir, args.eval_data_dict) with open(eval_data_path, 'rb') as f: eval_env = dill.load(f, encoding='latin1') if eval_env.robot_type is None and hyperparams['incl_robot_node']: eval_env.robot_type = eval_env.NodeType[0] # TODO: Make more general, allow the user to specify? for scene in eval_env.scenes: scene.add_robot_from_nodes(eval_env.robot_type) print('Loaded data from %s' % (eval_data_path,)) # Creating a dummy environment with a single scene that contains information about the world. # When using this code, feel free to use whichever scene index or initial timestep you wish. scene_idx = 0 # You need to have at least acceleration, so you want 2 timesteps of prior data, e.g. [0, 1], # so that you can immediately start incremental inference from the 3rd timestep onwards. init_timestep = 1 eval_scene = eval_env.scenes[scene_idx] online_env = create_online_env(eval_env, hyperparams, scene_idx, init_timestep) model_registrar = ModelRegistrar(model_dir, args.eval_device) model_registrar.load_models(iter_num=12) trajectron = OnlineTrajectron(model_registrar, hyperparams, args.eval_device) # If you want to see what different robot futures do to the predictions, uncomment this line as well as # related "... += adjustment" lines below. # adjustment = np.stack([np.arange(13)/float(i*2.0) for i in range(6, 12)], axis=1) # Here's how you'd incrementally run the model, e.g. with streaming data. trajectron.set_environment(online_env, init_timestep) for timestep in range(init_timestep + 1, eval_scene.timesteps): input_dict = eval_scene.get_clipped_input_dict(timestep, hyperparams['state']) maps = None if hyperparams['use_map_encoding']: maps = get_maps_for_input(input_dict, eval_scene, hyperparams) robot_present_and_future = None if eval_scene.robot is not None and hyperparams['incl_robot_node']: robot_present_and_future = eval_scene.robot.get(np.array([timestep, timestep + hyperparams['prediction_horizon']]), hyperparams['state'][eval_scene.robot.type], padding=0.0) robot_present_and_future = np.stack([robot_present_and_future, robot_present_and_future], axis=0) # robot_present_and_future += adjustment start = time.time() dists, preds = trajectron.incremental_forward(input_dict, maps, prediction_horizon=6, num_samples=1, robot_present_and_future=robot_present_and_future, full_dist=True) end = time.time() print("t=%d: took %.2f s (= %.2f Hz) w/ %d nodes and %d edges" % (timestep, end - start, 1. / (end - start), len(trajectron.nodes), trajectron.scene_graph.get_num_edges())) detailed_preds_dict = dict() for node in eval_scene.nodes: if node in preds: detailed_preds_dict[node] = preds[node] fig, ax = plt.subplots() vis.visualize_distribution(ax, dists) vis.visualize_prediction(ax, {timestep: preds}, eval_scene.dt, hyperparams['maximum_history_length'], hyperparams['prediction_horizon']) if eval_scene.robot is not None and hyperparams['incl_robot_node']: robot_for_plotting = eval_scene.robot.get(np.array([timestep, timestep + hyperparams['prediction_horizon']]), hyperparams['state'][eval_scene.robot.type]) # robot_for_plotting += adjustment ax.plot(robot_for_plotting[1:, 1], robot_for_plotting[1:, 0], color='r', linewidth=1.0, alpha=1.0) # Current Node Position circle = plt.Circle((robot_for_plotting[0, 1], robot_for_plotting[0, 0]), 0.3, facecolor='r', edgecolor='k', lw=0.5, zorder=3) ax.add_artist(circle) fig.savefig(os.path.join(output_save_dir, f'pred_{timestep}.pdf'), dpi=300) plt.close(fig) if __name__ == '__main__': main()
0.437343
0.295681
import os, sys import numpy as np import torch from torch import nn from torch import optim from torch.nn import functional as F #------------------------------------------------------- # params #------------------------------------------------------- name = sys.argv[1] i_wave = int(sys.argv[2]) nbatch = int(sys.argv[3]) #------------------------------------------------------- nhidden0 = 1280 nhidden1 = 1024 nhidden2 = 512 nhidden3 = 256 nhidden4 = 64 # load in training set dat_dir = '/tigress/chhahn/provabgs/' wave = np.load(os.path.join(dat_dir, 'wave_fsps.npy')) wave_bin = [(wave < 4500), ((wave >= 4500) & (wave < 6500)), (wave >= 6500)][i_wave] nwave = len(wave[wave_bin]) # average and sigma of ln(spectra) fshift = os.path.join(dat_dir, 'fsps.%s.w%i.shift_lnspectrum.%i.npy' % (name, i_wave, nbatch)) if not os.path.isfile(fshift): shift_lnspec = np.zeros(nwave) for i in range(nbatch): shift_lnspec += np.mean(np.load(os.path.join(dat_dir, 'fsps.%s.lnspectrum.seed%i.npy' % (name, i))), axis=0)[wave_bin]/float(nbatch) np.save(fshift, shift_lnspec) else: shift_lnspec = np.load(fshift) fscale = os.path.join(dat_dir, 'fsps.%s.w%i.scale_lnspectrum.%i.npy' % (name, i_wave, nbatch)) if not os.path.isfile(fscale): scale_lnspec = np.zeros(nwave) for i in range(nbatch): scale_lnspec += np.std(np.load(os.path.join(dat_dir, 'fsps.%s.lnspectrum.seed%i.npy' % (name, i))), axis=0)[wave_bin]/float(nbatch) np.save(fscale, scale_lnspec) else: scale_lnspec = np.load(fscale) print(shift_lnspec) print(scale_lnspec) n_theta = (np.load(os.path.join(dat_dir, 'fsps.%s.theta.seed0.npy' % name))).shape[1] n_lnspec = len(shift_lnspec) print('n_theta = %i' % n_theta) print('n_lnspec = %i' % n_lnspec) class Decoder(nn.Module): def __init__(self, nfeat=1000, ncode=5, nhidden0=128, nhidden1=128, nhidden2=35, nhidden3=35, nhidden4=35, dropout=0.2): super(Decoder, self).__init__() self.ncode = int(ncode) self.dec0 = nn.Linear(ncode, nhidden4) self.d1 = nn.Dropout(p=dropout) self.dec1 = nn.Linear(nhidden4, nhidden3) self.d2 = nn.Dropout(p=dropout) self.dec2 = nn.Linear(nhidden3, nhidden2) self.d3 = nn.Dropout(p=dropout) self.dec3 = nn.Linear(nhidden2, nhidden1) self.d4 = nn.Dropout(p=dropout) self.dec4 = nn.Linear(nhidden1, nhidden0) self.d5 = nn.Dropout(p=dropout) self.outp = nn.Linear(nhidden0, nfeat) def decode(self, x): x = self.d1(F.leaky_relu(self.dec0(x))) x = self.d2(F.leaky_relu(self.dec1(x))) x = self.d3(F.leaky_relu(self.dec2(x))) x = self.d4(F.leaky_relu(self.dec3(x))) x = self.d5(F.leaky_relu(self.dec4(x))) x = self.outp(x) return x def forward(self, x): return self.decode(x) def loss(self, x, y): recon_y = self.forward(x) MSE = torch.sum(0.5 * (y - recon_y).pow(2)) return MSE def train(batch_size): #model, optimizer, epoch, min_valid_loss, badepochs ''' train by looping through files with 10,000 SEDs and for each file, looping through batch_size batches. ''' model.train() train_loss = 0 for i in range(nbatch): #batch_idx, data in enumerate(train_loader): tt = torch.tensor(np.load(os.path.join(dat_dir, 'fsps.%s.theta.seed%i.npy' % (name, i))), dtype=torch.float32) lns = torch.tensor((np.load(os.path.join(dat_dir, 'fsps.%s.lnspectrum.seed%i.npy' % (name, i)))[:,wave_bin] - shift_lnspec)/scale_lnspec, dtype=torch.float32) train_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(tt, lns), batch_size=batch_size) _train_loss = 0 for data in train_loader: _tt, _lns = data optimizer.zero_grad() loss = model.loss(_tt, _lns) loss.backward() _train_loss += loss.item() optimizer.step() _train_loss /= len(train_loader.dataset) train_loss += _train_loss train_loss /= nbatch return train_loss class EarlyStopper: def __init__(self, precision=1e-3, patience=10): self.precision = precision self.patience = patience self.badepochs = 0 self.min_valid_loss = float('inf') def step(self, valid_loss): if valid_loss < self.min_valid_loss*(1-self.precision): self.badepochs = 0 self.min_valid_loss = valid_loss else: self.badepochs += 1 return not (self.badepochs == self.patience) # output loss _floss = os.path.join(dat_dir, 'decoder.fsps.%s.w%i.%ibatches.%i_%i_%i_%i_%i.loss' % (name, i_wave, nbatch, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4)) floss = open(_floss, 'w') floss.close() epochs = 200 n_config = 1 batch_sizes = [100, 1000, 5000, 10000] ibatch = 0 for config in range(n_config): dropout = 0. #0.9*np.random.uniform() print('config %i, dropout = %0.2f; 5 hidden layers with %i, %i, %i, %i, %i nodes' % (config, dropout, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4)) model = Decoder(nfeat=n_lnspec, nhidden0=nhidden0, nhidden1=nhidden1, nhidden2=nhidden2, nhidden3=nhidden3, nhidden4=nhidden4, ncode=n_theta, dropout=dropout) optimizer = optim.Adam(model.parameters(), lr=1e-3) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', verbose=True, patience=5) stopper = EarlyStopper(patience=10) for batch_size in batch_sizes: for epoch in range(1, epochs + 1): train_loss = train(batch_size) print('====> Epoch: %i BATCH SIZE %i TRAINING Loss: %.2e' % (epoch, batch_size, train_loss)) floss = open(_floss, "a") # append floss.write('%i \t %i \t %.5e \n' % (batch_size, epoch, train_loss)) floss.close() scheduler.step(train_loss) if (not stopper.step(train_loss)) or (epoch == epochs): print('Stopping') print('====> Epoch: %i BATCH SIZE %i TRAINING Loss: %.2e' % (epoch, batch_size, train_loss)) torch.save(model, os.path.join(dat_dir, 'decoder.fsps.%s.w%i.%ibatches.%i_%i_%i_%i_%i.final.pth' % (name, i_wave, nbatch, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4))) break torch.save(model, os.path.join(dat_dir, 'decoder.fsps.%s.w%i.%ibatches.%i_%i_%i_%i_%i.pth' % (name, i_wave, nbatch, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4)))
bin/decoder.py
import os, sys import numpy as np import torch from torch import nn from torch import optim from torch.nn import functional as F #------------------------------------------------------- # params #------------------------------------------------------- name = sys.argv[1] i_wave = int(sys.argv[2]) nbatch = int(sys.argv[3]) #------------------------------------------------------- nhidden0 = 1280 nhidden1 = 1024 nhidden2 = 512 nhidden3 = 256 nhidden4 = 64 # load in training set dat_dir = '/tigress/chhahn/provabgs/' wave = np.load(os.path.join(dat_dir, 'wave_fsps.npy')) wave_bin = [(wave < 4500), ((wave >= 4500) & (wave < 6500)), (wave >= 6500)][i_wave] nwave = len(wave[wave_bin]) # average and sigma of ln(spectra) fshift = os.path.join(dat_dir, 'fsps.%s.w%i.shift_lnspectrum.%i.npy' % (name, i_wave, nbatch)) if not os.path.isfile(fshift): shift_lnspec = np.zeros(nwave) for i in range(nbatch): shift_lnspec += np.mean(np.load(os.path.join(dat_dir, 'fsps.%s.lnspectrum.seed%i.npy' % (name, i))), axis=0)[wave_bin]/float(nbatch) np.save(fshift, shift_lnspec) else: shift_lnspec = np.load(fshift) fscale = os.path.join(dat_dir, 'fsps.%s.w%i.scale_lnspectrum.%i.npy' % (name, i_wave, nbatch)) if not os.path.isfile(fscale): scale_lnspec = np.zeros(nwave) for i in range(nbatch): scale_lnspec += np.std(np.load(os.path.join(dat_dir, 'fsps.%s.lnspectrum.seed%i.npy' % (name, i))), axis=0)[wave_bin]/float(nbatch) np.save(fscale, scale_lnspec) else: scale_lnspec = np.load(fscale) print(shift_lnspec) print(scale_lnspec) n_theta = (np.load(os.path.join(dat_dir, 'fsps.%s.theta.seed0.npy' % name))).shape[1] n_lnspec = len(shift_lnspec) print('n_theta = %i' % n_theta) print('n_lnspec = %i' % n_lnspec) class Decoder(nn.Module): def __init__(self, nfeat=1000, ncode=5, nhidden0=128, nhidden1=128, nhidden2=35, nhidden3=35, nhidden4=35, dropout=0.2): super(Decoder, self).__init__() self.ncode = int(ncode) self.dec0 = nn.Linear(ncode, nhidden4) self.d1 = nn.Dropout(p=dropout) self.dec1 = nn.Linear(nhidden4, nhidden3) self.d2 = nn.Dropout(p=dropout) self.dec2 = nn.Linear(nhidden3, nhidden2) self.d3 = nn.Dropout(p=dropout) self.dec3 = nn.Linear(nhidden2, nhidden1) self.d4 = nn.Dropout(p=dropout) self.dec4 = nn.Linear(nhidden1, nhidden0) self.d5 = nn.Dropout(p=dropout) self.outp = nn.Linear(nhidden0, nfeat) def decode(self, x): x = self.d1(F.leaky_relu(self.dec0(x))) x = self.d2(F.leaky_relu(self.dec1(x))) x = self.d3(F.leaky_relu(self.dec2(x))) x = self.d4(F.leaky_relu(self.dec3(x))) x = self.d5(F.leaky_relu(self.dec4(x))) x = self.outp(x) return x def forward(self, x): return self.decode(x) def loss(self, x, y): recon_y = self.forward(x) MSE = torch.sum(0.5 * (y - recon_y).pow(2)) return MSE def train(batch_size): #model, optimizer, epoch, min_valid_loss, badepochs ''' train by looping through files with 10,000 SEDs and for each file, looping through batch_size batches. ''' model.train() train_loss = 0 for i in range(nbatch): #batch_idx, data in enumerate(train_loader): tt = torch.tensor(np.load(os.path.join(dat_dir, 'fsps.%s.theta.seed%i.npy' % (name, i))), dtype=torch.float32) lns = torch.tensor((np.load(os.path.join(dat_dir, 'fsps.%s.lnspectrum.seed%i.npy' % (name, i)))[:,wave_bin] - shift_lnspec)/scale_lnspec, dtype=torch.float32) train_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(tt, lns), batch_size=batch_size) _train_loss = 0 for data in train_loader: _tt, _lns = data optimizer.zero_grad() loss = model.loss(_tt, _lns) loss.backward() _train_loss += loss.item() optimizer.step() _train_loss /= len(train_loader.dataset) train_loss += _train_loss train_loss /= nbatch return train_loss class EarlyStopper: def __init__(self, precision=1e-3, patience=10): self.precision = precision self.patience = patience self.badepochs = 0 self.min_valid_loss = float('inf') def step(self, valid_loss): if valid_loss < self.min_valid_loss*(1-self.precision): self.badepochs = 0 self.min_valid_loss = valid_loss else: self.badepochs += 1 return not (self.badepochs == self.patience) # output loss _floss = os.path.join(dat_dir, 'decoder.fsps.%s.w%i.%ibatches.%i_%i_%i_%i_%i.loss' % (name, i_wave, nbatch, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4)) floss = open(_floss, 'w') floss.close() epochs = 200 n_config = 1 batch_sizes = [100, 1000, 5000, 10000] ibatch = 0 for config in range(n_config): dropout = 0. #0.9*np.random.uniform() print('config %i, dropout = %0.2f; 5 hidden layers with %i, %i, %i, %i, %i nodes' % (config, dropout, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4)) model = Decoder(nfeat=n_lnspec, nhidden0=nhidden0, nhidden1=nhidden1, nhidden2=nhidden2, nhidden3=nhidden3, nhidden4=nhidden4, ncode=n_theta, dropout=dropout) optimizer = optim.Adam(model.parameters(), lr=1e-3) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', verbose=True, patience=5) stopper = EarlyStopper(patience=10) for batch_size in batch_sizes: for epoch in range(1, epochs + 1): train_loss = train(batch_size) print('====> Epoch: %i BATCH SIZE %i TRAINING Loss: %.2e' % (epoch, batch_size, train_loss)) floss = open(_floss, "a") # append floss.write('%i \t %i \t %.5e \n' % (batch_size, epoch, train_loss)) floss.close() scheduler.step(train_loss) if (not stopper.step(train_loss)) or (epoch == epochs): print('Stopping') print('====> Epoch: %i BATCH SIZE %i TRAINING Loss: %.2e' % (epoch, batch_size, train_loss)) torch.save(model, os.path.join(dat_dir, 'decoder.fsps.%s.w%i.%ibatches.%i_%i_%i_%i_%i.final.pth' % (name, i_wave, nbatch, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4))) break torch.save(model, os.path.join(dat_dir, 'decoder.fsps.%s.w%i.%ibatches.%i_%i_%i_%i_%i.pth' % (name, i_wave, nbatch, nhidden0, nhidden1, nhidden2, nhidden3, nhidden4)))
0.596786
0.210726
# This piece of code detects whether motion has been detected on the respective pir motion # sensor and determines whether someone is entering a room or leaving a room, relays that # information as occupancy level import esp import machine import connectWifi import time import config import utime import json from machine import Pin from umqtt.simple import MQTTClient # connect to wifi first connectWifi.connect() # define pins for the pir motion sensor pin_1 = machine.Pin(0, machine.Pin.IN) pin_2 = machine.Pin(2, machine.Pin.IN) state = "on" motiondetected_1 = 0 motiondetected_2 = 0 time_s1 = 0 time_s2 = 0 time_comp = 0 count = 0 SERVER = config.MQTT_CONFIG['MQTT_HOST'] PORT = config.MQTT_CONFIG['PORT'] SENSOR_ID = config.MQTT_CONFIG['SENSOR_ID'] PUB_TOPIC = config.MQTT_CONFIG['PUB_TOPIC'] # set up interrupt functions for in case pir motion sensor 1 is triggered def handle_interrupt_1(p_0): print('pin change', p_0) global motiondetected_1, time_s1 motiondetected_1 = 1 time_s1 = time.time() # set up interrupt functions for in case pir motion sensor 2 is triggered def handle_interrupt_2(p_1): print('pin change', p_1) global motiondetected_2, time_s2 motiondetected_2 = 1 time_s2 = time.time() # set up interrupts for the two pins pin_1.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt_1) pin_2.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt_2) def main(server=SERVER, port=PORT): # set up and connect to the MQTT client c = MQTTClient(SENSOR_ID, SERVER, 1883) c.connect() while True: global state, motiondetected_1, motiondetected_2, time_s1, time_s2, time_comp, count while True: time_comp = time_s1 - time_s2 # determine if someone is moving in to a room and transmit the occupancy if time_comp < 0 and abs(time_comp) < 4: print("moving in") print(time_comp) time.sleep(2) count = count + 1 time_s1 = 0 time_s2 = 0 data = {"occupancy": count} c.publish(PUB_TOPIC, json.dumps(data)) # determine if someone is movint out of a room and transmit the occupancy elif time_comp > 0 and abs(time_comp) < 4: print("moving out") print(time_comp) time.sleep(2) count = count - 1 if count < 0: count = 0 time_s1 = 0 time_s2 = 0 data = {"occupancy": count} c.publish(PUB_TOPIC, json.dumps(data)) time_comp = 0 if __name__ == "__main__": main()
esp/motion-sensor/main.py
# This piece of code detects whether motion has been detected on the respective pir motion # sensor and determines whether someone is entering a room or leaving a room, relays that # information as occupancy level import esp import machine import connectWifi import time import config import utime import json from machine import Pin from umqtt.simple import MQTTClient # connect to wifi first connectWifi.connect() # define pins for the pir motion sensor pin_1 = machine.Pin(0, machine.Pin.IN) pin_2 = machine.Pin(2, machine.Pin.IN) state = "on" motiondetected_1 = 0 motiondetected_2 = 0 time_s1 = 0 time_s2 = 0 time_comp = 0 count = 0 SERVER = config.MQTT_CONFIG['MQTT_HOST'] PORT = config.MQTT_CONFIG['PORT'] SENSOR_ID = config.MQTT_CONFIG['SENSOR_ID'] PUB_TOPIC = config.MQTT_CONFIG['PUB_TOPIC'] # set up interrupt functions for in case pir motion sensor 1 is triggered def handle_interrupt_1(p_0): print('pin change', p_0) global motiondetected_1, time_s1 motiondetected_1 = 1 time_s1 = time.time() # set up interrupt functions for in case pir motion sensor 2 is triggered def handle_interrupt_2(p_1): print('pin change', p_1) global motiondetected_2, time_s2 motiondetected_2 = 1 time_s2 = time.time() # set up interrupts for the two pins pin_1.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt_1) pin_2.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt_2) def main(server=SERVER, port=PORT): # set up and connect to the MQTT client c = MQTTClient(SENSOR_ID, SERVER, 1883) c.connect() while True: global state, motiondetected_1, motiondetected_2, time_s1, time_s2, time_comp, count while True: time_comp = time_s1 - time_s2 # determine if someone is moving in to a room and transmit the occupancy if time_comp < 0 and abs(time_comp) < 4: print("moving in") print(time_comp) time.sleep(2) count = count + 1 time_s1 = 0 time_s2 = 0 data = {"occupancy": count} c.publish(PUB_TOPIC, json.dumps(data)) # determine if someone is movint out of a room and transmit the occupancy elif time_comp > 0 and abs(time_comp) < 4: print("moving out") print(time_comp) time.sleep(2) count = count - 1 if count < 0: count = 0 time_s1 = 0 time_s2 = 0 data = {"occupancy": count} c.publish(PUB_TOPIC, json.dumps(data)) time_comp = 0 if __name__ == "__main__": main()
0.461502
0.379608
import sys import argparse from typing import List, Optional from .lib import FileHelper from .lib import TerminalStyle from .converter.ConverterInterface import ConverterInterface from .model.IntermediateLocalization import IntermediateLocalization from .model.LocalizationFile import LocalizationFile #-------------------- # properties #-------------------- sourceFilepath = "" destinationDirectory = "" importConverterIdentifier = "" exportConverterIdentifier = "" dryRun = False forceOverride = False #-------------------- # Starting point #-------------------- def start(args: argparse.Namespace, converter: List[ConverterInterface]) -> None: _parseArgsForConverting(args, converter) intermediate = _importToIntermediateLocalization(sourceFilepath, converter) if isinstance(intermediate, IntermediateLocalization): _exportToLocalizationFile(intermediate, converter) #-------------------- # private helper #-------------------- def _parseArgsForConverting(args: argparse.Namespace, converter: List[ConverterInterface]) -> None: # select and validate converter for export global exportConverterIdentifier exportConverterIdentifier = args.exportConverter selectedExportConverter = list(filter(lambda x: x.identifier() == exportConverterIdentifier, converter)) if len(selectedExportConverter) == 0: _handleError("ERROR: Converter with identifier {} not found".format(exportConverterIdentifier)) # validate source filepath global sourceFilepath sourceFilepath = args.source if not FileHelper.exists(sourceFilepath): _handleError("ERROR: Source does not exists") # select and validate converter for import global importConverterIdentifier importConverterIdentifier = args.importConverter extension = FileHelper.fileExtension(sourceFilepath) matchingImportConverter = list( filter( lambda x: x.fileExtension() == extension and x.identifier() == importConverterIdentifier, converter ) ) if len(matchingImportConverter) == 0: _handleError("ERROR: No matching converter found with identifier {} for fileextension {}".format(importConverterIdentifier, extension)) else: importConverterIdentifier = matchingImportConverter[0].identifier() # save and handle dryRun argument global dryRun dryRun = args.dryRun if dryRun: if args.verbose: _printSummary(sourceFilepath, "dryRun", importConverterIdentifier, exportConverterIdentifier) # If dryRun is enabled, there is no need to process destination directory. return # save forceOverride argument which is used when saving to a filepath global forceOverride forceOverride = args.force # save and validate destination filepath global destinationDirectory destinationDirectory = args.destination if not FileHelper.exists(destinationDirectory): FileHelper.createDir(destinationDirectory) elif FileHelper.exists(destinationDirectory) and forceOverride: _handleWarning("Warning: Destination directory [{}] already exists. Overwriting it.".format(destinationDirectory)) FileHelper.removeDir(destinationDirectory) FileHelper.createDir(destinationDirectory) else: _handleError("Error: Destination directory [{}] already exists. Use flag -f to override it.".format(destinationDirectory)) exit() # At this point everything was validated and nothing can go wrong (hopefully). if args.verbose: _printSummary(sourceFilepath, destinationDirectory, importConverterIdentifier, exportConverterIdentifier) def _importToIntermediateLocalization( sourceFilepath: str, converter: List[ConverterInterface] ) -> Optional[IntermediateLocalization]: importer = list(filter(lambda x: x.identifier() == importConverterIdentifier, converter)) return importer[0].toIntermediate(sourceFilepath) def _exportToLocalizationFile( intermediateLocalization: IntermediateLocalization, converter: List[ConverterInterface] ) -> None: exportConverter = list(filter(lambda x: x.identifier() == exportConverterIdentifier, converter)) for exporter in exportConverter: for file in exporter.fromIntermediate(intermediateLocalization): _handleLocalizationFile(file) def _handleLocalizationFile(localizationFile: LocalizationFile) -> None: global dryRun if dryRun: print(localizationFile.filecontent) else: destination = destinationDirectory + "/" + localizationFile.filepath _writeFile(destination, localizationFile.filecontent) def _writeFile(path: str, content: str) -> None: directoryPath = FileHelper.directoryPath(path) if FileHelper.exists(path): pass else: FileHelper.createDir(directoryPath) FileHelper.writeFile(path, content) #-------------------- # cli output #-------------------- def _printSummary( sourceFilepath: str, destinationFilepath: str, importConverterIdentifier: str, exportConverterIdentifier: str ) -> None: _handleInfo( "Summary:\n" + "input: {}\n".format(sourceFilepath) + "destination: {}\n".format(destinationFilepath) + "converter for import: {}\n".format(importConverterIdentifier) + "converter for export: {}".format(exportConverterIdentifier) ) def _handleError(errorText: str) -> None: print(TerminalStyle.FAIL + errorText + TerminalStyle.ENDC) sys.exit() def _handleWarning(warningText: str) -> None: print(TerminalStyle.WARNING + warningText + TerminalStyle.ENDC) def _handleInfo(infoText: str) -> None: print(TerminalStyle.GREEN + infoText + TerminalStyle.ENDC)
Logen/main_subcommand_convert.py
import sys import argparse from typing import List, Optional from .lib import FileHelper from .lib import TerminalStyle from .converter.ConverterInterface import ConverterInterface from .model.IntermediateLocalization import IntermediateLocalization from .model.LocalizationFile import LocalizationFile #-------------------- # properties #-------------------- sourceFilepath = "" destinationDirectory = "" importConverterIdentifier = "" exportConverterIdentifier = "" dryRun = False forceOverride = False #-------------------- # Starting point #-------------------- def start(args: argparse.Namespace, converter: List[ConverterInterface]) -> None: _parseArgsForConverting(args, converter) intermediate = _importToIntermediateLocalization(sourceFilepath, converter) if isinstance(intermediate, IntermediateLocalization): _exportToLocalizationFile(intermediate, converter) #-------------------- # private helper #-------------------- def _parseArgsForConverting(args: argparse.Namespace, converter: List[ConverterInterface]) -> None: # select and validate converter for export global exportConverterIdentifier exportConverterIdentifier = args.exportConverter selectedExportConverter = list(filter(lambda x: x.identifier() == exportConverterIdentifier, converter)) if len(selectedExportConverter) == 0: _handleError("ERROR: Converter with identifier {} not found".format(exportConverterIdentifier)) # validate source filepath global sourceFilepath sourceFilepath = args.source if not FileHelper.exists(sourceFilepath): _handleError("ERROR: Source does not exists") # select and validate converter for import global importConverterIdentifier importConverterIdentifier = args.importConverter extension = FileHelper.fileExtension(sourceFilepath) matchingImportConverter = list( filter( lambda x: x.fileExtension() == extension and x.identifier() == importConverterIdentifier, converter ) ) if len(matchingImportConverter) == 0: _handleError("ERROR: No matching converter found with identifier {} for fileextension {}".format(importConverterIdentifier, extension)) else: importConverterIdentifier = matchingImportConverter[0].identifier() # save and handle dryRun argument global dryRun dryRun = args.dryRun if dryRun: if args.verbose: _printSummary(sourceFilepath, "dryRun", importConverterIdentifier, exportConverterIdentifier) # If dryRun is enabled, there is no need to process destination directory. return # save forceOverride argument which is used when saving to a filepath global forceOverride forceOverride = args.force # save and validate destination filepath global destinationDirectory destinationDirectory = args.destination if not FileHelper.exists(destinationDirectory): FileHelper.createDir(destinationDirectory) elif FileHelper.exists(destinationDirectory) and forceOverride: _handleWarning("Warning: Destination directory [{}] already exists. Overwriting it.".format(destinationDirectory)) FileHelper.removeDir(destinationDirectory) FileHelper.createDir(destinationDirectory) else: _handleError("Error: Destination directory [{}] already exists. Use flag -f to override it.".format(destinationDirectory)) exit() # At this point everything was validated and nothing can go wrong (hopefully). if args.verbose: _printSummary(sourceFilepath, destinationDirectory, importConverterIdentifier, exportConverterIdentifier) def _importToIntermediateLocalization( sourceFilepath: str, converter: List[ConverterInterface] ) -> Optional[IntermediateLocalization]: importer = list(filter(lambda x: x.identifier() == importConverterIdentifier, converter)) return importer[0].toIntermediate(sourceFilepath) def _exportToLocalizationFile( intermediateLocalization: IntermediateLocalization, converter: List[ConverterInterface] ) -> None: exportConverter = list(filter(lambda x: x.identifier() == exportConverterIdentifier, converter)) for exporter in exportConverter: for file in exporter.fromIntermediate(intermediateLocalization): _handleLocalizationFile(file) def _handleLocalizationFile(localizationFile: LocalizationFile) -> None: global dryRun if dryRun: print(localizationFile.filecontent) else: destination = destinationDirectory + "/" + localizationFile.filepath _writeFile(destination, localizationFile.filecontent) def _writeFile(path: str, content: str) -> None: directoryPath = FileHelper.directoryPath(path) if FileHelper.exists(path): pass else: FileHelper.createDir(directoryPath) FileHelper.writeFile(path, content) #-------------------- # cli output #-------------------- def _printSummary( sourceFilepath: str, destinationFilepath: str, importConverterIdentifier: str, exportConverterIdentifier: str ) -> None: _handleInfo( "Summary:\n" + "input: {}\n".format(sourceFilepath) + "destination: {}\n".format(destinationFilepath) + "converter for import: {}\n".format(importConverterIdentifier) + "converter for export: {}".format(exportConverterIdentifier) ) def _handleError(errorText: str) -> None: print(TerminalStyle.FAIL + errorText + TerminalStyle.ENDC) sys.exit() def _handleWarning(warningText: str) -> None: print(TerminalStyle.WARNING + warningText + TerminalStyle.ENDC) def _handleInfo(infoText: str) -> None: print(TerminalStyle.GREEN + infoText + TerminalStyle.ENDC)
0.47244
0.149718
import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as transforms from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from torch.utils.data import TensorDataset from aijack.attack import MI_FACE from aijack.defense import GeneralMomentAccountant, PrivacyManager from aijack.utils import NumpyDataset # INPUT PATHS: BASE = "data/" lot_size = 40 batch_size = 1 iterations = 10 sigma = 0.5 l2_norm_clip = 1 delta = 1e-5 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fla = nn.Flatten() self.fc = nn.Linear(112 * 92, 40) def forward(self, x): x = self.fla(x) x = self.fc(x) x = F.softmax(x, dim=1) return x def prepare_dataset(): imgs = [] labels = [] for i in range(1, 41): for j in range(1, 11): img = cv2.imread(BASE + f"s{i}/{j}.pgm", 0) imgs.append(img) labels.append(i - 1) X = np.stack(imgs) y = np.array(labels) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))] ) trainset = NumpyDataset(X, y, transform=transform) return trainset def train(): trainset = prepare_dataset() accountant = GeneralMomentAccountant( noise_type="Gaussian", search="ternary", precision=0.001, order_max=1, order_min=72, max_iterations=1000, bound_type="rdp_upperbound_closedformula", backend="python", ) privacy_manager = PrivacyManager( accountant, optim.SGD, l2_norm_clip=l2_norm_clip, dataset=trainset, lot_size=lot_size, batch_size=batch_size, iterations=iterations, ) accountant.reset_step_info() accountant.add_step_info( {"sigma": sigma}, lot_size / len(trainset), iterations * (len(trainset) / lot_size), ) estimated_epsilon = accountant.get_epsilon(delta=delta) print(f"estimated epsilon is {estimated_epsilon}") accountant.reset_step_info() dpoptimizer_cls, lot_loader, batch_loader = privacy_manager.privatize( noise_multiplier=sigma ) net = Net() criterion = nn.CrossEntropyLoss() optimizer = dpoptimizer_cls(net.parameters(), lr=0.05, momentum=0.9) for epoch in range(iterations): # loop over the dataset multiple times running_loss = 0 data_size = 0 preds = [] labels = [] for data in lot_loader(trainset): X_lot, y_lot = data optimizer.zero_grad() for X_batch, y_batch in batch_loader(TensorDataset(X_lot, y_lot)): optimizer.zero_grad_keep_accum_grads() pred = net(X_batch) loss = criterion(pred, y_batch.to(torch.int64)) loss.backward() optimizer.update_accum_grads() running_loss += loss.item() data_size += X_batch.shape[0] preds.append(pred) labels.append(y_batch) optimizer.step() preds = torch.cat(preds) labels = torch.cat(labels) print(f"epoch {epoch}: loss is {running_loss/data_size}") print( f"epoch {epoch}: accuracy is {accuracy_score(np.array(torch.argmax(preds, axis=1)), np.array(labels))}" ) print(f"final epsilon is {accountant.get_epsilon(delta=delta)}") return net def attack(net): input_shape = (1, 1, 112, 92) target_label_1 = 1 target_label_2 = 10 lam = 0.1 num_itr = 100 print("start model inversion") mi = MI_FACE(net, input_shape) print("finish model inversion") print("reconstruct images ....") x_result_1, _ = mi.attack(target_label_1, lam, num_itr) x_result_2, _ = mi.attack(target_label_2, lam, num_itr) _, axes = plt.subplots(nrows=2, ncols=2, figsize=(4, 5)) axes[0][0].imshow(cv2.imread(BASE + "s2/1.pgm", 0), cmap="gray") axes[0][0].axis("off") axes[0][0].set_title("original image") axes[0][1].imshow(x_result_1[0][0], cmap="gray") axes[0][1].axis("off") axes[0][1].set_title("extracted image") axes[1][0].imshow(cv2.imread(BASE + "s11/1.pgm", 0), cmap="gray") axes[1][0].axis("off") axes[1][0].set_title("original image") axes[1][1].imshow(x_result_2[0][0], cmap="gray") axes[1][1].axis("off") axes[1][1].set_title("extracted image") plt.savefig("reconstructed.png") if __name__ == "__main__": model = train() attack(model)
example/model_inversion/mi_face_differential_privacy.py
import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as transforms from matplotlib import pyplot as plt from sklearn.metrics import accuracy_score from torch.utils.data import TensorDataset from aijack.attack import MI_FACE from aijack.defense import GeneralMomentAccountant, PrivacyManager from aijack.utils import NumpyDataset # INPUT PATHS: BASE = "data/" lot_size = 40 batch_size = 1 iterations = 10 sigma = 0.5 l2_norm_clip = 1 delta = 1e-5 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fla = nn.Flatten() self.fc = nn.Linear(112 * 92, 40) def forward(self, x): x = self.fla(x) x = self.fc(x) x = F.softmax(x, dim=1) return x def prepare_dataset(): imgs = [] labels = [] for i in range(1, 41): for j in range(1, 11): img = cv2.imread(BASE + f"s{i}/{j}.pgm", 0) imgs.append(img) labels.append(i - 1) X = np.stack(imgs) y = np.array(labels) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))] ) trainset = NumpyDataset(X, y, transform=transform) return trainset def train(): trainset = prepare_dataset() accountant = GeneralMomentAccountant( noise_type="Gaussian", search="ternary", precision=0.001, order_max=1, order_min=72, max_iterations=1000, bound_type="rdp_upperbound_closedformula", backend="python", ) privacy_manager = PrivacyManager( accountant, optim.SGD, l2_norm_clip=l2_norm_clip, dataset=trainset, lot_size=lot_size, batch_size=batch_size, iterations=iterations, ) accountant.reset_step_info() accountant.add_step_info( {"sigma": sigma}, lot_size / len(trainset), iterations * (len(trainset) / lot_size), ) estimated_epsilon = accountant.get_epsilon(delta=delta) print(f"estimated epsilon is {estimated_epsilon}") accountant.reset_step_info() dpoptimizer_cls, lot_loader, batch_loader = privacy_manager.privatize( noise_multiplier=sigma ) net = Net() criterion = nn.CrossEntropyLoss() optimizer = dpoptimizer_cls(net.parameters(), lr=0.05, momentum=0.9) for epoch in range(iterations): # loop over the dataset multiple times running_loss = 0 data_size = 0 preds = [] labels = [] for data in lot_loader(trainset): X_lot, y_lot = data optimizer.zero_grad() for X_batch, y_batch in batch_loader(TensorDataset(X_lot, y_lot)): optimizer.zero_grad_keep_accum_grads() pred = net(X_batch) loss = criterion(pred, y_batch.to(torch.int64)) loss.backward() optimizer.update_accum_grads() running_loss += loss.item() data_size += X_batch.shape[0] preds.append(pred) labels.append(y_batch) optimizer.step() preds = torch.cat(preds) labels = torch.cat(labels) print(f"epoch {epoch}: loss is {running_loss/data_size}") print( f"epoch {epoch}: accuracy is {accuracy_score(np.array(torch.argmax(preds, axis=1)), np.array(labels))}" ) print(f"final epsilon is {accountant.get_epsilon(delta=delta)}") return net def attack(net): input_shape = (1, 1, 112, 92) target_label_1 = 1 target_label_2 = 10 lam = 0.1 num_itr = 100 print("start model inversion") mi = MI_FACE(net, input_shape) print("finish model inversion") print("reconstruct images ....") x_result_1, _ = mi.attack(target_label_1, lam, num_itr) x_result_2, _ = mi.attack(target_label_2, lam, num_itr) _, axes = plt.subplots(nrows=2, ncols=2, figsize=(4, 5)) axes[0][0].imshow(cv2.imread(BASE + "s2/1.pgm", 0), cmap="gray") axes[0][0].axis("off") axes[0][0].set_title("original image") axes[0][1].imshow(x_result_1[0][0], cmap="gray") axes[0][1].axis("off") axes[0][1].set_title("extracted image") axes[1][0].imshow(cv2.imread(BASE + "s11/1.pgm", 0), cmap="gray") axes[1][0].axis("off") axes[1][0].set_title("original image") axes[1][1].imshow(x_result_2[0][0], cmap="gray") axes[1][1].axis("off") axes[1][1].set_title("extracted image") plt.savefig("reconstructed.png") if __name__ == "__main__": model = train() attack(model)
0.925196
0.490785
import json try: import pika except Exception as e: print("Some modules are missing!", e) class RabbitMqConfig(object): """ This class configures the rabbit mq """ def __init__(self, host='localhost', queue='Hello'): """ This method is used to initialise the server name and queue from where the data is received """ self.host = host self.queue = queue # To clear the contents of a file or create # the file if it doesn't already exist open('sensor1.txt', 'w').close() open('SensorData.CSV', 'w').close() open('TimeElapsed.CSV', 'w').close() class RabbitMqServer(object): """ Initialise the server properties. - Local host tells that we are connected to a broker on local machine To connect to a broker on different machine we need to mention the IP Address or its name - Before sending we need to make sure the recipient queue exists. If we send a message to non-existing location, RabbitMQ will just drop the message. """ def __init__(self, server): self.server = server # Step1: Establish Connection with RabbitMQ server self._connection = pika.BlockingConnection( pika.ConnectionParameters(host=self.server.host)) self._channel = self._connection.channel() # Step2: Create a queue called 'hello' where msg would be delivered self._tem = self._channel.queue_declare(queue=self.server.queue) message = {} # Step3: Receiving message from queue requires # subscribing a callback function to a queue. @staticmethod def callback(ch, method, properties, body): """ Whenever we receive a message, this callback function is called by the Pika library. In our case this function will print on the screen the contents of the message. """ message = body.decode("utf-8") print(f"Received ") # message = json.loads(str(message)) message = message.replace('\'', '\"') data = json.loads(message) # iterating through the contents of a single packet # sent from GUI and saving it in a file for i in range(len(data['sensor1Data'])): with open('SensorData.CSV', 'a+', newline='') as f: m = "{},{}\n".format( data['sensor1Data'][i], data['sensor2Data'][i]) f.write(m) # print(f"time: {data['oilTime_hrs']}") with open('TimeElapsed.CSV', 'w', newline='') as f: m = f"{data['oilTime_hrs']},{data['tire_dist_kms']}" f.write(m) with open('parameters.txt', 'w', newline='') as f: params = {"category1": data['category1'], "category2": data['category2'], "email": data['email']} f.write(str(params)) def start_server(self): """ For that command to succeed we must be sure that a queue which we want to subscribe to exists. Fortunately we're confident about that ‒ we've created a queue above ‒ using queue_declare. """ # Step4: Tell RabbitMQ that this particular callback # function should receive messages from our hello queue self._channel.basic_consume(queue=self.server.queue, on_message_callback=self.callback, auto_ack=True) print('Waiting for messages: ') self._channel.start_consuming() if __name__ == "__main__": print("Receiver open") server_config = RabbitMqConfig(host='localhost', queue='Hello') server = RabbitMqServer(server_config) server.start_server()
Source/GUI_2/receiver.py
import json try: import pika except Exception as e: print("Some modules are missing!", e) class RabbitMqConfig(object): """ This class configures the rabbit mq """ def __init__(self, host='localhost', queue='Hello'): """ This method is used to initialise the server name and queue from where the data is received """ self.host = host self.queue = queue # To clear the contents of a file or create # the file if it doesn't already exist open('sensor1.txt', 'w').close() open('SensorData.CSV', 'w').close() open('TimeElapsed.CSV', 'w').close() class RabbitMqServer(object): """ Initialise the server properties. - Local host tells that we are connected to a broker on local machine To connect to a broker on different machine we need to mention the IP Address or its name - Before sending we need to make sure the recipient queue exists. If we send a message to non-existing location, RabbitMQ will just drop the message. """ def __init__(self, server): self.server = server # Step1: Establish Connection with RabbitMQ server self._connection = pika.BlockingConnection( pika.ConnectionParameters(host=self.server.host)) self._channel = self._connection.channel() # Step2: Create a queue called 'hello' where msg would be delivered self._tem = self._channel.queue_declare(queue=self.server.queue) message = {} # Step3: Receiving message from queue requires # subscribing a callback function to a queue. @staticmethod def callback(ch, method, properties, body): """ Whenever we receive a message, this callback function is called by the Pika library. In our case this function will print on the screen the contents of the message. """ message = body.decode("utf-8") print(f"Received ") # message = json.loads(str(message)) message = message.replace('\'', '\"') data = json.loads(message) # iterating through the contents of a single packet # sent from GUI and saving it in a file for i in range(len(data['sensor1Data'])): with open('SensorData.CSV', 'a+', newline='') as f: m = "{},{}\n".format( data['sensor1Data'][i], data['sensor2Data'][i]) f.write(m) # print(f"time: {data['oilTime_hrs']}") with open('TimeElapsed.CSV', 'w', newline='') as f: m = f"{data['oilTime_hrs']},{data['tire_dist_kms']}" f.write(m) with open('parameters.txt', 'w', newline='') as f: params = {"category1": data['category1'], "category2": data['category2'], "email": data['email']} f.write(str(params)) def start_server(self): """ For that command to succeed we must be sure that a queue which we want to subscribe to exists. Fortunately we're confident about that ‒ we've created a queue above ‒ using queue_declare. """ # Step4: Tell RabbitMQ that this particular callback # function should receive messages from our hello queue self._channel.basic_consume(queue=self.server.queue, on_message_callback=self.callback, auto_ack=True) print('Waiting for messages: ') self._channel.start_consuming() if __name__ == "__main__": print("Receiver open") server_config = RabbitMqConfig(host='localhost', queue='Hello') server = RabbitMqServer(server_config) server.start_server()
0.481941
0.274461
from orochi.website.models import UserPlugin from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.generic import RedirectView, DetailView from django.shortcuts import get_object_or_404 from django.contrib import messages User = get_user_model() class UserYaraView(LoginRequiredMixin, DetailView): queryset = User.objects.prefetch_related("rules").all() slug_field = "username" slug_url_kwarg = "username" template_name = "users/user_rules.html" user_yara_view = UserYaraView.as_view() class UserPluginView(LoginRequiredMixin, DetailView): queryset = User.objects.prefetch_related("plugins__plugin").all() slug_field = "username" slug_url_kwarg = "username" template_name = "users/user_plugins.html" def post(self, request, *args, **kwargs): action = request.POST.get("action") plugin_ids = request.POST.getlist("id[]") for plugin in plugin_ids: up = get_object_or_404(UserPlugin, pk=plugin, user=request.user) up.automatic = bool(action == "enable") up.save() self.object = self.get_object() context = self.get_context_data(object=self.object) messages.add_message( request, messages.SUCCESS if action == "enable" else messages.ERROR, "{} plugins {}d".format(len(plugin_ids), action), ) return self.render_to_response(context) user_plugins_view = UserPluginView.as_view() class UserBookmarksView(LoginRequiredMixin, DetailView): queryset = User.objects.prefetch_related("bookmarks").all() slug_field = "username" slug_url_kwarg = "username" template_name = "users/user_bookmarks.html" user_bookmarks_view = UserBookmarksView.as_view() class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): return reverse( "users:bookmarks", kwargs={"username": self.request.user.username} ) user_redirect_view = UserRedirectView.as_view()
orochi/users/views.py
from orochi.website.models import UserPlugin from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.generic import RedirectView, DetailView from django.shortcuts import get_object_or_404 from django.contrib import messages User = get_user_model() class UserYaraView(LoginRequiredMixin, DetailView): queryset = User.objects.prefetch_related("rules").all() slug_field = "username" slug_url_kwarg = "username" template_name = "users/user_rules.html" user_yara_view = UserYaraView.as_view() class UserPluginView(LoginRequiredMixin, DetailView): queryset = User.objects.prefetch_related("plugins__plugin").all() slug_field = "username" slug_url_kwarg = "username" template_name = "users/user_plugins.html" def post(self, request, *args, **kwargs): action = request.POST.get("action") plugin_ids = request.POST.getlist("id[]") for plugin in plugin_ids: up = get_object_or_404(UserPlugin, pk=plugin, user=request.user) up.automatic = bool(action == "enable") up.save() self.object = self.get_object() context = self.get_context_data(object=self.object) messages.add_message( request, messages.SUCCESS if action == "enable" else messages.ERROR, "{} plugins {}d".format(len(plugin_ids), action), ) return self.render_to_response(context) user_plugins_view = UserPluginView.as_view() class UserBookmarksView(LoginRequiredMixin, DetailView): queryset = User.objects.prefetch_related("bookmarks").all() slug_field = "username" slug_url_kwarg = "username" template_name = "users/user_bookmarks.html" user_bookmarks_view = UserBookmarksView.as_view() class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): return reverse( "users:bookmarks", kwargs={"username": self.request.user.username} ) user_redirect_view = UserRedirectView.as_view()
0.416797
0.075007
import torch import torch.nn as nn import numpy as np import os import matplotlib if os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') matplotlib.use('Agg') import matplotlib.pyplot as plt # The squash function specified in Dynamic Routing Between Capsules # x: input tensor def squash(x, dim=-1): norm_squared = (x ** 2).sum(dim, keepdim=True) part1 = norm_squared / (1 + norm_squared) part2 = x / torch.sqrt(norm_squared+ 1e-16) output = part1 * part2 return output def weights_init_xavier(m): classname = m.__class__.__name__ ignore_modules = [ "SmallNorbConvReconstructionModule", "ConvReconstructionModule", "ConvLayer" ] if classname.find('Conv') != -1 and classname not in ignore_modules: nn.init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('Linear') != -1: nn.init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('BatchNorm2d') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0.0) elif classname == 'ClassCapsules': nn.init.xavier_normal_(m.W.data, gain=0.002) nn.init.xavier_normal_(m.bias.data, gain=0.002) def initialize_weights(capsnet): capsnet.apply(weights_init_xavier) def denormalize(image): image = image - image.min() image = image / image.max() return image def get_path(SAVE_DIR, filename): if not os.path.isdir(SAVE_DIR): os.makedirs(SAVE_DIR) path = os.path.join(SAVE_DIR, filename) return path def save_images(SAVE_DIR, filename, images, reconstructions, num_images = 100, imsize=28): if len(images) < num_images or len(reconstructions) < num_images: print("Not enough images to save.") return big_image = np.ones((imsize*10, imsize*20+1)) images = denormalize(images).view(-1, imsize, imsize) reconstructions = denormalize(reconstructions).view(-1, imsize, imsize) images = images.data.cpu().numpy() reconstructions = reconstructions.data.cpu().numpy() for i in range(num_images): image = images[i] rec = reconstructions[i] j = i % 10 i = i // 10 big_image[i*imsize:(i+1)*imsize, j*imsize:(j+1)*imsize] = image j += 10 big_image[i*imsize:(i+1)*imsize, j*imsize+1:(j+1)*imsize+1] = rec path = get_path(SAVE_DIR, filename) plt.imsave(path, big_image, cmap="gray") def save_images_cifar10(SAVE_DIR, filename, images, reconstructions, num_images = 100): if len(images) < num_images or len(reconstructions) < num_images: print("Not enough images to save.") return big_image = np.ones((3,32*10, 32*20+1)) #print('Images : ',big_image.T.shape,',',reconstructions.size()) images = denormalize(images).view(-1, 3 ,32, 32) reconstructions = denormalize(reconstructions).view(-1, 3 ,32, 32) images = images.data.cpu().numpy() reconstructions = reconstructions.data.cpu().numpy() for i in range(num_images): image = images[i] rec = reconstructions[i] j = i % 10 i = i // 10 big_image[:,i*32:(i+1)*32, j*32:(j+1)*32] = image j += 10 big_image[:,i*32:(i+1)*32, j*32+1:(j+1)*32+1] = rec path = get_path(SAVE_DIR, filename) plt.imsave(path, big_image.T)
tools.py
import torch import torch.nn as nn import numpy as np import os import matplotlib if os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') matplotlib.use('Agg') import matplotlib.pyplot as plt # The squash function specified in Dynamic Routing Between Capsules # x: input tensor def squash(x, dim=-1): norm_squared = (x ** 2).sum(dim, keepdim=True) part1 = norm_squared / (1 + norm_squared) part2 = x / torch.sqrt(norm_squared+ 1e-16) output = part1 * part2 return output def weights_init_xavier(m): classname = m.__class__.__name__ ignore_modules = [ "SmallNorbConvReconstructionModule", "ConvReconstructionModule", "ConvLayer" ] if classname.find('Conv') != -1 and classname not in ignore_modules: nn.init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('Linear') != -1: nn.init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('BatchNorm2d') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0.0) elif classname == 'ClassCapsules': nn.init.xavier_normal_(m.W.data, gain=0.002) nn.init.xavier_normal_(m.bias.data, gain=0.002) def initialize_weights(capsnet): capsnet.apply(weights_init_xavier) def denormalize(image): image = image - image.min() image = image / image.max() return image def get_path(SAVE_DIR, filename): if not os.path.isdir(SAVE_DIR): os.makedirs(SAVE_DIR) path = os.path.join(SAVE_DIR, filename) return path def save_images(SAVE_DIR, filename, images, reconstructions, num_images = 100, imsize=28): if len(images) < num_images or len(reconstructions) < num_images: print("Not enough images to save.") return big_image = np.ones((imsize*10, imsize*20+1)) images = denormalize(images).view(-1, imsize, imsize) reconstructions = denormalize(reconstructions).view(-1, imsize, imsize) images = images.data.cpu().numpy() reconstructions = reconstructions.data.cpu().numpy() for i in range(num_images): image = images[i] rec = reconstructions[i] j = i % 10 i = i // 10 big_image[i*imsize:(i+1)*imsize, j*imsize:(j+1)*imsize] = image j += 10 big_image[i*imsize:(i+1)*imsize, j*imsize+1:(j+1)*imsize+1] = rec path = get_path(SAVE_DIR, filename) plt.imsave(path, big_image, cmap="gray") def save_images_cifar10(SAVE_DIR, filename, images, reconstructions, num_images = 100): if len(images) < num_images or len(reconstructions) < num_images: print("Not enough images to save.") return big_image = np.ones((3,32*10, 32*20+1)) #print('Images : ',big_image.T.shape,',',reconstructions.size()) images = denormalize(images).view(-1, 3 ,32, 32) reconstructions = denormalize(reconstructions).view(-1, 3 ,32, 32) images = images.data.cpu().numpy() reconstructions = reconstructions.data.cpu().numpy() for i in range(num_images): image = images[i] rec = reconstructions[i] j = i % 10 i = i // 10 big_image[:,i*32:(i+1)*32, j*32:(j+1)*32] = image j += 10 big_image[:,i*32:(i+1)*32, j*32+1:(j+1)*32+1] = rec path = get_path(SAVE_DIR, filename) plt.imsave(path, big_image.T)
0.628635
0.449936
import unittest def rotate_matrix(matrix): """ Swap layer by layer, from outside to inside. Observe the way i and j change to have a appropriate formula :param matrix: :return: """ if not matrix: return n = len(matrix) for i in range(n // 2): for j in range(i, n - i - 1): temp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] matrix[j][n - i - 1] = temp class Test(unittest.TestCase): def test_rotate_matrix(self): matrix = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36] ] expected = [ [31, 25, 19, 13, 7, 1], [32, 26, 20, 14, 8, 2], [33, 27, 21, 15, 9, 3], [34, 28, 22, 16, 10, 4], [35, 29, 23, 17, 11, 5], [36, 30, 24, 18, 12, 6] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] expected = [ [21, 16, 11, 6, 1], [22, 17, 12, 7, 2], [23, 18, 13, 8, 3], [24, 19, 14, 9, 4], [25, 20, 15, 10, 5] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] expected = [ [13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [4, 5, 2], [8, 9, 11], [9, 15, 100] ] expected = [ [9, 8, 4], [15, 9, 5], [100, 11, 2] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [1] ] expected = [ [1] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [] expected = [] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return empty matrix if input matrix is empty")
ArraysAndStrings/1_7_RotateMatrix.py
import unittest def rotate_matrix(matrix): """ Swap layer by layer, from outside to inside. Observe the way i and j change to have a appropriate formula :param matrix: :return: """ if not matrix: return n = len(matrix) for i in range(n // 2): for j in range(i, n - i - 1): temp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] matrix[j][n - i - 1] = temp class Test(unittest.TestCase): def test_rotate_matrix(self): matrix = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36] ] expected = [ [31, 25, 19, 13, 7, 1], [32, 26, 20, 14, 8, 2], [33, 27, 21, 15, 9, 3], [34, 28, 22, 16, 10, 4], [35, 29, 23, 17, 11, 5], [36, 30, 24, 18, 12, 6] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] expected = [ [21, 16, 11, 6, 1], [22, 17, 12, 7, 2], [23, 18, 13, 8, 3], [24, 19, 14, 9, 4], [25, 20, 15, 10, 5] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] expected = [ [13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [4, 5, 2], [8, 9, 11], [9, 15, 100] ] expected = [ [9, 8, 4], [15, 9, 5], [100, 11, 2] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [ [1] ] expected = [ [1] ] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return correct rotated matrix") matrix = [] expected = [] rotate_matrix(matrix) self.assertEqual(expected, matrix, "Should return empty matrix if input matrix is empty")
0.735357
0.796925
from __future__ import annotations import subprocess as sp from ..environment import ( Environment, Dependency, HeaderDependency, LibraryDependency, ProgramDependency, Installer, GNUInstaller, GurobiInstaller, ) from ...errors import InstallError, UninstallError mipverify_runner = """#!/bin/bash export GUROBI_HOME={gurobi_home} cd {venv_path} ./julia --project=. $@ """ class MIPVerifyInstaller(Installer): def run(self, env: Environment, dependency: Dependency): commit_hash = "36fd890" cache_dir = env.cache_dir / f"mipverify-{commit_hash}" cache_dir.mkdir(exist_ok=True, parents=True) verifier_venv_path = env.env_dir / "verifier_virtualenvs" / "mipverify" verifier_venv_path.parent.mkdir(exist_ok=True, parents=True) installation_path = env.env_dir / "bin" installation_path.mkdir(exist_ok=True, parents=True) libjulia_path = LibraryDependency("libjulia").get_path(env) assert libjulia_path is not None julia_dir = libjulia_path.parent.parent envvars = env.vars() commands = [ "set -ex", f"cd {verifier_venv_path.parent}", "rm -rf mipverify", "mkdir mipverify", "cd mipverify", f"cp -r {julia_dir} .", f"ln -s {julia_dir}/bin/julia julia", './julia --project=. -e \'using Pkg; Pkg.add("Gurobi"); Pkg.build("Gurobi")\'', './julia --project=. -e \'using Pkg; Pkg.add("MathOptInterface"); Pkg.build("MathOptInterface")\'', './julia --project=. -e \'using Pkg; Pkg.add("JuMP"); Pkg.build("JuMP")\'', './julia --project=. -e \'using Pkg; Pkg.add("MAT"); Pkg.build("MAT")\'', f'./julia --project=. -e \'using Pkg; Pkg.add(PackageSpec(url="https://github.com/vtjeng/MIPVerify.jl", rev="{commit_hash}"))\'', "./julia --project=. -e 'using Pkg; Pkg.update(); Pkg.precompile()'", ] install_script = "; ".join(commands) proc = sp.run(install_script, shell=True, env=envvars) if proc.returncode != 0: raise InstallError(f"Installation of MIPVerify failed") with open(installation_path / "mipverify", "w+") as f: f.write( mipverify_runner.format( venv_path=verifier_venv_path, gurobi_home=envvars.get("GUROBI_HOME", "."), ) ) (installation_path / "mipverify").chmod(0o700) class JuliaInstaller(Installer): def run(self, env: Environment, dependency: Dependency): version = "1.6.1" major_minor = ".".join(version.split(".")[:2]) cache_dir = env.cache_dir / f"julia-{version}" cache_dir.mkdir(exist_ok=True, parents=True) env.paths.append(cache_dir / f"julia-{version}" / "bin") env.include_paths.append(cache_dir / f"julia-{version}" / "include") env.ld_library_paths.append(cache_dir / f"julia-{version}" / "lib") if dependency.is_installed(env): return commands = [ "set -ex", f"cd {cache_dir}", f"curl -o julia-{version}.tar.gz -L https://julialang-s3.julialang.org/bin/linux/x64/{major_minor}/julia-{version}-linux-x86_64.tar.gz", f"tar xf julia-{version}.tar.gz", ] install_script = "; ".join(commands) proc = sp.run(install_script, shell=True, env=env.vars()) if proc.returncode != 0: raise InstallError(f"Installation of julia failed") def install(env: Environment): zlib_installer = GNUInstaller( "zlib", "1.2.11", "https://www.zlib.net/zlib-1.2.11.tar.xz" ) gurobi_installer = GurobiInstaller("9.1.2") env.ensure_dependencies( ProgramDependency( "mipverify", installer=MIPVerifyInstaller(), dependencies=( ProgramDependency("julia", installer=JuliaInstaller()), ProgramDependency("git"), HeaderDependency("zlib.h", installer=zlib_installer), LibraryDependency("libz", installer=zlib_installer), HeaderDependency("gurobi_c.h", installer=gurobi_installer), LibraryDependency("libgurobi91", installer=gurobi_installer), ProgramDependency("grbgetkey", installer=gurobi_installer), ), ) ) def uninstall(env: Environment): exe_path = env.env_dir / "bin" / "mipverify" verifier_venv_path = env.env_dir / "verifier_virtualenvs" / "mipverify" commands = [ f"rm -f {exe_path}", f"rm -rf {verifier_venv_path}", ] install_script = "; ".join(commands) proc = sp.run(install_script, shell=True, env=env.vars()) if proc.returncode != 0: raise UninstallError("Uninstallation of planet failed") __all__ = ["install", "uninstall"]
dnnv/_manage/linux/verifiers/mipverify.py
from __future__ import annotations import subprocess as sp from ..environment import ( Environment, Dependency, HeaderDependency, LibraryDependency, ProgramDependency, Installer, GNUInstaller, GurobiInstaller, ) from ...errors import InstallError, UninstallError mipverify_runner = """#!/bin/bash export GUROBI_HOME={gurobi_home} cd {venv_path} ./julia --project=. $@ """ class MIPVerifyInstaller(Installer): def run(self, env: Environment, dependency: Dependency): commit_hash = "36fd890" cache_dir = env.cache_dir / f"mipverify-{commit_hash}" cache_dir.mkdir(exist_ok=True, parents=True) verifier_venv_path = env.env_dir / "verifier_virtualenvs" / "mipverify" verifier_venv_path.parent.mkdir(exist_ok=True, parents=True) installation_path = env.env_dir / "bin" installation_path.mkdir(exist_ok=True, parents=True) libjulia_path = LibraryDependency("libjulia").get_path(env) assert libjulia_path is not None julia_dir = libjulia_path.parent.parent envvars = env.vars() commands = [ "set -ex", f"cd {verifier_venv_path.parent}", "rm -rf mipverify", "mkdir mipverify", "cd mipverify", f"cp -r {julia_dir} .", f"ln -s {julia_dir}/bin/julia julia", './julia --project=. -e \'using Pkg; Pkg.add("Gurobi"); Pkg.build("Gurobi")\'', './julia --project=. -e \'using Pkg; Pkg.add("MathOptInterface"); Pkg.build("MathOptInterface")\'', './julia --project=. -e \'using Pkg; Pkg.add("JuMP"); Pkg.build("JuMP")\'', './julia --project=. -e \'using Pkg; Pkg.add("MAT"); Pkg.build("MAT")\'', f'./julia --project=. -e \'using Pkg; Pkg.add(PackageSpec(url="https://github.com/vtjeng/MIPVerify.jl", rev="{commit_hash}"))\'', "./julia --project=. -e 'using Pkg; Pkg.update(); Pkg.precompile()'", ] install_script = "; ".join(commands) proc = sp.run(install_script, shell=True, env=envvars) if proc.returncode != 0: raise InstallError(f"Installation of MIPVerify failed") with open(installation_path / "mipverify", "w+") as f: f.write( mipverify_runner.format( venv_path=verifier_venv_path, gurobi_home=envvars.get("GUROBI_HOME", "."), ) ) (installation_path / "mipverify").chmod(0o700) class JuliaInstaller(Installer): def run(self, env: Environment, dependency: Dependency): version = "1.6.1" major_minor = ".".join(version.split(".")[:2]) cache_dir = env.cache_dir / f"julia-{version}" cache_dir.mkdir(exist_ok=True, parents=True) env.paths.append(cache_dir / f"julia-{version}" / "bin") env.include_paths.append(cache_dir / f"julia-{version}" / "include") env.ld_library_paths.append(cache_dir / f"julia-{version}" / "lib") if dependency.is_installed(env): return commands = [ "set -ex", f"cd {cache_dir}", f"curl -o julia-{version}.tar.gz -L https://julialang-s3.julialang.org/bin/linux/x64/{major_minor}/julia-{version}-linux-x86_64.tar.gz", f"tar xf julia-{version}.tar.gz", ] install_script = "; ".join(commands) proc = sp.run(install_script, shell=True, env=env.vars()) if proc.returncode != 0: raise InstallError(f"Installation of julia failed") def install(env: Environment): zlib_installer = GNUInstaller( "zlib", "1.2.11", "https://www.zlib.net/zlib-1.2.11.tar.xz" ) gurobi_installer = GurobiInstaller("9.1.2") env.ensure_dependencies( ProgramDependency( "mipverify", installer=MIPVerifyInstaller(), dependencies=( ProgramDependency("julia", installer=JuliaInstaller()), ProgramDependency("git"), HeaderDependency("zlib.h", installer=zlib_installer), LibraryDependency("libz", installer=zlib_installer), HeaderDependency("gurobi_c.h", installer=gurobi_installer), LibraryDependency("libgurobi91", installer=gurobi_installer), ProgramDependency("grbgetkey", installer=gurobi_installer), ), ) ) def uninstall(env: Environment): exe_path = env.env_dir / "bin" / "mipverify" verifier_venv_path = env.env_dir / "verifier_virtualenvs" / "mipverify" commands = [ f"rm -f {exe_path}", f"rm -rf {verifier_venv_path}", ] install_script = "; ".join(commands) proc = sp.run(install_script, shell=True, env=env.vars()) if proc.returncode != 0: raise UninstallError("Uninstallation of planet failed") __all__ = ["install", "uninstall"]
0.446253
0.116136
from flask_restful_swagger import swagger from flask_restful import fields @swagger.model class HumanSerializer: resource_fields = { 'reanimators_count': fields.Integer, 'need_staff': fields.Integer, } @swagger.model class BedSerializer: resource_fields = { 'covid_available': fields.Integer, 'covid_used': fields.Integer, 'other_available': fields.Integer, 'other_used': fields.Integer, 'conventional_count': fields.Integer, 'continue_care_count': fields.Integer, 'reanimation_count': fields.Integer, 'post_urgency_count': fields.Integer, 'other_count': fields.Integer, } @swagger.model class SupplySerializer: resource_fields = { 'reanimators_count': fields.Integer, 'efp2_masks_count': fields.Integer, 'chir_masks_count': fields.Integer, 'blouses_count': fields.Integer, 'gowns_count': fields.Integer, } @swagger.model class ContactSerializer: resource_fields = { 'id': fields.Integer, 'firstname': fields.String, 'lastname': fields.String, 'phone_number': fields.String, 'email': fields.String, 'comment': fields.String, } @swagger.model @swagger.nested(bed=BedSerializer.__name__, supply=SupplySerializer.__name__, human=HumanSerializer.__name__, contact=ContactSerializer.__name__) class ResourceSerializer: resource_fields = { 'date': fields.DateTime, 'etablissement_id': fields.Integer, 'functional_unit': fields.String, 'bed': fields.List(fields.Nested(BedSerializer.resource_fields)), 'supply': fields.List(fields.Nested(SupplySerializer.resource_fields)), 'human': fields.List(fields.Nested(HumanSerializer.resource_fields)), 'contact': fields.List(fields.Nested(ContactSerializer.resource_fields)) } required = ["date", 'etablissement_id'] @swagger.model @swagger.nested(results=ResourceSerializer.__name__) class ResourceListResponseSerializer: resource_fields = { 'total': fields.Integer, 'page': fields.Integer, 'size': fields.Integer, 'results': fields.List(fields.Nested(ResourceSerializer.resource_fields)), } required = ['total', "page", 'size', 'results'] @swagger.model class ResourceCreationResponseSerializer: resource_fields = { 'id': fields.Integer } required = ['id']
app/covidbed/serializer/resource.py
from flask_restful_swagger import swagger from flask_restful import fields @swagger.model class HumanSerializer: resource_fields = { 'reanimators_count': fields.Integer, 'need_staff': fields.Integer, } @swagger.model class BedSerializer: resource_fields = { 'covid_available': fields.Integer, 'covid_used': fields.Integer, 'other_available': fields.Integer, 'other_used': fields.Integer, 'conventional_count': fields.Integer, 'continue_care_count': fields.Integer, 'reanimation_count': fields.Integer, 'post_urgency_count': fields.Integer, 'other_count': fields.Integer, } @swagger.model class SupplySerializer: resource_fields = { 'reanimators_count': fields.Integer, 'efp2_masks_count': fields.Integer, 'chir_masks_count': fields.Integer, 'blouses_count': fields.Integer, 'gowns_count': fields.Integer, } @swagger.model class ContactSerializer: resource_fields = { 'id': fields.Integer, 'firstname': fields.String, 'lastname': fields.String, 'phone_number': fields.String, 'email': fields.String, 'comment': fields.String, } @swagger.model @swagger.nested(bed=BedSerializer.__name__, supply=SupplySerializer.__name__, human=HumanSerializer.__name__, contact=ContactSerializer.__name__) class ResourceSerializer: resource_fields = { 'date': fields.DateTime, 'etablissement_id': fields.Integer, 'functional_unit': fields.String, 'bed': fields.List(fields.Nested(BedSerializer.resource_fields)), 'supply': fields.List(fields.Nested(SupplySerializer.resource_fields)), 'human': fields.List(fields.Nested(HumanSerializer.resource_fields)), 'contact': fields.List(fields.Nested(ContactSerializer.resource_fields)) } required = ["date", 'etablissement_id'] @swagger.model @swagger.nested(results=ResourceSerializer.__name__) class ResourceListResponseSerializer: resource_fields = { 'total': fields.Integer, 'page': fields.Integer, 'size': fields.Integer, 'results': fields.List(fields.Nested(ResourceSerializer.resource_fields)), } required = ['total', "page", 'size', 'results'] @swagger.model class ResourceCreationResponseSerializer: resource_fields = { 'id': fields.Integer } required = ['id']
0.733261
0.135546
import logging from typing import List, Optional, Union from xml.etree.ElementTree import Element from jmeter_api.basics.config.elements import BasicConfig from jmeter_api.basics.utils import Renderable, FileEncoding, tree_to_str class Header(Renderable): TEMPLATE = 'header.xml' root_element_name = 'elementProp' def __init__(self, *, name: str, value: str): self.name = name self.value = value @property def name(self) -> str: return self._name @name.setter def name(self, value): if not isinstance(value, str): raise TypeError( f'name must be str. {type(value).__name__} was given') self._name = value @property def value(self) -> str: return self._value @value.setter def value(self, value): if not isinstance(value, str): raise TypeError( f'value must be str. {type(value).__name__} was given') self._value = value def to_xml(self) -> str: xml_tree: Optional[Element] = super().get_template() element_root = xml_tree.find(self.root_element_name) element_root.attrib['name'] = self.name for element in list(element_root): try: if element.attrib['name'] == 'Header.name': element.text = self.name elif element.attrib['name'] == 'Header.value': element.text = self.value except KeyError: logging.error( f'Unable to properly convert {self.__class__} to xml.') return tree_to_str(xml_tree) class HTTPHeaderManager(BasicConfig, Renderable): root_element_name = 'HeaderManager' def __init__(self, *, headers: Union[List[Header],dict] = [], name: str = 'HTTP Header Manager', comments: str = '', is_enabled: bool = True): self.headers = headers super().__init__(name=name, comments=comments, is_enabled=is_enabled) @property def headers(self) -> str: return self._headers @headers.setter def headers(self, value): if not isinstance(value, List): raise TypeError( f'headers must be List. {type(value).__name__} was given') for i in range(len(value)): if not isinstance(value[i], (Header, dict)): raise TypeError( f'headers must contain Header or dict. {type(value).__name__} was given') if isinstance(value[i], dict): if not len(value[i]) == 1: raise ValueError('dict must be like "header":"value"') h = list(value[i])[0] v = value[i][h] value[i] = Header(name=h, value=v) self._headers = value def to_xml(self) -> str: element_root, xml_tree = super()._add_basics() for element in list(element_root): try: if element.attrib['name'] == 'HeaderManager.headers': element.text = '' for arg in self.headers: element.text += arg.to_xml() except KeyError: logging.error( f'Unable to properly convert {self.__class__} to xml.') return tree_to_str(xml_tree)
jmeter_api/configs/http_header_manager/elements.py
import logging from typing import List, Optional, Union from xml.etree.ElementTree import Element from jmeter_api.basics.config.elements import BasicConfig from jmeter_api.basics.utils import Renderable, FileEncoding, tree_to_str class Header(Renderable): TEMPLATE = 'header.xml' root_element_name = 'elementProp' def __init__(self, *, name: str, value: str): self.name = name self.value = value @property def name(self) -> str: return self._name @name.setter def name(self, value): if not isinstance(value, str): raise TypeError( f'name must be str. {type(value).__name__} was given') self._name = value @property def value(self) -> str: return self._value @value.setter def value(self, value): if not isinstance(value, str): raise TypeError( f'value must be str. {type(value).__name__} was given') self._value = value def to_xml(self) -> str: xml_tree: Optional[Element] = super().get_template() element_root = xml_tree.find(self.root_element_name) element_root.attrib['name'] = self.name for element in list(element_root): try: if element.attrib['name'] == 'Header.name': element.text = self.name elif element.attrib['name'] == 'Header.value': element.text = self.value except KeyError: logging.error( f'Unable to properly convert {self.__class__} to xml.') return tree_to_str(xml_tree) class HTTPHeaderManager(BasicConfig, Renderable): root_element_name = 'HeaderManager' def __init__(self, *, headers: Union[List[Header],dict] = [], name: str = 'HTTP Header Manager', comments: str = '', is_enabled: bool = True): self.headers = headers super().__init__(name=name, comments=comments, is_enabled=is_enabled) @property def headers(self) -> str: return self._headers @headers.setter def headers(self, value): if not isinstance(value, List): raise TypeError( f'headers must be List. {type(value).__name__} was given') for i in range(len(value)): if not isinstance(value[i], (Header, dict)): raise TypeError( f'headers must contain Header or dict. {type(value).__name__} was given') if isinstance(value[i], dict): if not len(value[i]) == 1: raise ValueError('dict must be like "header":"value"') h = list(value[i])[0] v = value[i][h] value[i] = Header(name=h, value=v) self._headers = value def to_xml(self) -> str: element_root, xml_tree = super()._add_basics() for element in list(element_root): try: if element.attrib['name'] == 'HeaderManager.headers': element.text = '' for arg in self.headers: element.text += arg.to_xml() except KeyError: logging.error( f'Unable to properly convert {self.__class__} to xml.') return tree_to_str(xml_tree)
0.770508
0.190799
import asyncio import logging import threading from datetime import timedelta from typing import Optional import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.event import async_track_time_interval from pymodbus.client.sync import ModbusTcpClient from pymodbus.constants import Endian from pymodbus.exceptions import ConnectionException from pymodbus.payload import BinaryPayloadDecoder from .const import ( DEFAULT_NAME, DEFAULT_SCAN_INTERVAL, DOMAIN, CONF_READ_GEN2X1, CONF_READ_GEN3X1, CONF_READ_GEN3X3, CONF_READ_X1_EPS, CONF_READ_X3_EPS, DEFAULT_READ_GEN2X1, DEFAULT_READ_GEN3X1, DEFAULT_READ_GEN3X3, DEFAULT_READ_X1_EPS, DEFAULT_READ_X3_EPS, ) _LOGGER = logging.getLogger(__name__) SOLAX_MODBUS_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PORT): cv.string, vol.Optional(CONF_READ_GEN2X1, default=DEFAULT_READ_GEN2X1): cv.boolean, vol.Optional(CONF_READ_GEN3X1, default=DEFAULT_READ_GEN3X1): cv.boolean, vol.Optional(CONF_READ_GEN3X3, default=DEFAULT_READ_GEN3X3): cv.boolean, vol.Optional(CONF_READ_X1_EPS, default=DEFAULT_READ_X1_EPS): cv.boolean, vol.Optional(CONF_READ_X3_EPS, default=DEFAULT_READ_X3_EPS): cv.boolean, vol.Optional( CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL ): cv.positive_int, } ) CONFIG_SCHEMA = vol.Schema( {DOMAIN: vol.Schema({cv.slug: SOLAX_MODBUS_SCHEMA})}, extra=vol.ALLOW_EXTRA ) PLATFORMS = ["number", "select", "sensor"] async def async_setup(hass, config): """Set up the SolaX modbus component.""" hass.data[DOMAIN] = {} return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up a SolaX mobus.""" host = entry.data[CONF_HOST] name = entry.data[CONF_NAME] port = entry.data[CONF_PORT] scan_interval = entry.data[CONF_SCAN_INTERVAL] read_gen2x1 = entry.data.get(CONF_READ_GEN2X1, False) read_gen3x1 = entry.data.get(CONF_READ_GEN3X1, False) read_gen3x3 = entry.data.get(CONF_READ_GEN3X3, False) read_x1_eps = entry.data.get(CONF_READ_X1_EPS, False) read_x3_eps = entry.data.get(CONF_READ_X3_EPS, False) _LOGGER.debug("Setup %s.%s", DOMAIN, name) hub = SolaXModbusHub(hass, name, host, port, scan_interval, read_gen2x1, read_gen3x1, read_gen3x3, read_x1_eps, read_x3_eps) """Register the hub.""" hass.data[DOMAIN][name] = {"hub": hub} for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True async def async_unload_entry(hass, entry): """Unload SolaX mobus entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if not unload_ok: return False hass.data[DOMAIN].pop(entry.data["name"]) return True class SolaXModbusHub: """Thread safe wrapper class for pymodbus.""" def __init__( self, hass, name, host, port, scan_interval, read_gen2x1=False, read_gen3x1=False, read_gen3x3=False, read_x1_eps=False, read_x3_eps=False, ): """Initialize the Modbus hub.""" self._hass = hass self._client = ModbusTcpClient(host=host, port=port, timeout=5) self._lock = threading.Lock() self._name = name self.read_gen2x1 = read_gen2x1 self.read_gen3x1 = read_gen3x1 self.read_gen3x3 = read_gen3x3 self.read_x1_eps = read_x1_eps self.read_x3_eps = read_x3_eps self._scan_interval = timedelta(seconds=scan_interval) self._unsub_interval_method = None self._sensors = [] self.data = {} @callback def async_add_solax_modbus_sensor(self, update_callback): """Listen for data updates.""" # This is the first sensor, set up interval. if not self._sensors: self.connect() self._unsub_interval_method = async_track_time_interval( self._hass, self.async_refresh_modbus_data, self._scan_interval ) self._sensors.append(update_callback) @callback def async_remove_solax_modbus_sensor(self, update_callback): """Remove data update.""" self._sensors.remove(update_callback) if not self._sensors: """stop the interval timer upon removal of last sensor""" self._unsub_interval_method() self._unsub_interval_method = None self.close() async def async_refresh_modbus_data(self, _now: Optional[int] = None) -> None: """Time to update.""" if not self._sensors: return update_result = self.read_modbus_data() if update_result: for update_callback in self._sensors: update_callback() @property def name(self): """Return the name of this hub.""" return self._name def close(self): """Disconnect client.""" with self._lock: self._client.close() def connect(self): """Connect client.""" with self._lock: self._client.connect() def read_holding_registers(self, unit, address, count): """Read holding registers.""" with self._lock: kwargs = {"unit": unit} if unit else {} return self._client.read_holding_registers(address, count, **kwargs) def read_input_registers(self, unit, address, count): """Read input registers.""" with self._lock: kwargs = {"unit": unit} if unit else {} return self._client.read_input_registers(address, count, **kwargs) def write_register(self, unit, address, payload): """Write registers.""" with self._lock: kwargs = {"unit": unit} if unit else {} return self._client.write_register(address, payload, **kwargs) def read_modbus_data(self): try: return self.read_modbus_holding_registers_0() and self.read_modbus_holding_registers_1() and self.read_modbus_holding_registers_2() and self.read_modbus_input_registers_0() and self.read_modbus_input_registers_1() except ConnectionException as ex: _LOGGER.error("Reading data failed! Inverter is offline.") return True def read_modbus_holding_registers_0(self): inverter_data = self.read_holding_registers(unit=1, address=0x0, count=21) if inverter_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( inverter_data.registers, byteorder=Endian.Big ) seriesnumber = decoder.decode_string(14).decode("ascii") self.data["seriesnumber"] = str(seriesnumber) factoryname = decoder.decode_string(14).decode("ascii") self.data["factoryname"] = str(factoryname) modulename = decoder.decode_string(14).decode("ascii") self.data["modulename"] = str(modulename) return True def read_modbus_holding_registers_1(self): if self.read_gen2x1 == True: mult = 0.01 else: mult = 0.1 inverter_data = self.read_holding_registers(unit=1, address=0x7d, count=64) if inverter_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( inverter_data.registers, byteorder=Endian.Big ) firmwareversion_invertermaster = decoder.decode_16bit_uint() self.data["firmwareversion_invertermaster"] = firmwareversion_invertermaster decoder.skip_bytes(6) firmwareversion_modbustcp_major = decoder.decode_16bit_uint() self.data["firmwareversion_modbustcp_major"] = firmwareversion_modbustcp_major firmwareversion_modbustcp_minor = decoder.decode_16bit_uint() self.data["firmwareversion_modbustcp_minor"] = firmwareversion_modbustcp_minor firmwareversion_manager = decoder.decode_16bit_uint() self.data["firmwareversion_manager"] = firmwareversion_manager myaddress = decoder.decode_16bit_uint() self.data["myaddress"] = myaddress rtc_seconds = decoder.decode_16bit_uint() self.data["rtc_seconds"] = rtc_seconds rtc_minutes = decoder.decode_16bit_uint() rtc_hours = decoder.decode_16bit_uint() rtc_days = decoder.decode_16bit_uint() rtc_months = decoder.decode_16bit_uint() rtc_years = decoder.decode_16bit_uint() self.data["rtc"] = f"{rtc_hours}:{rtc_minutes}:{rtc_seconds} {rtc_days}/{rtc_months}/{rtc_years}" charger_use_modes = decoder.decode_16bit_uint() if charger_use_modes == 0: self.data["charger_use_mode"] = "Self Use Mode" elif charger_use_modes == 1: self.data["charger_use_mode"] = "Force Time Use" elif charger_use_modes == 2: self.data["charger_use_mode"] = "Back Up Mode" elif charger_use_modes == 3: self.data["charger_use_mode"] = "Feedin Priority" else: self.data["charger_use_mode"] = "Unknown" battery_min_capacity = decoder.decode_16bit_uint() self.data["battery_min_capacity"] = battery_min_capacity battery_types = decoder.decode_16bit_uint() if battery_types == 0: self.data["battery_type"] = "Lead Acid" elif battery_types == 1: self.data["battery_type"] = "Lithium" else: self.data["battery_type"] = "Unknown" battery_charge_float_voltage = decoder.decode_16bit_uint() self.data["battery_charge_float_voltage"] = round(battery_charge_float_voltage * 0.1, 1) battery_discharge_cut_off_voltage = decoder.decode_16bit_uint() self.data["battery_discharge_cut_off_voltage"] = round(battery_discharge_cut_off_voltage * 0.1, 1) battery_charge_max_current = decoder.decode_16bit_uint() self.data["battery_charge_max_current"] = round(battery_charge_max_current * mult, 1) battery_discharge_max_current = decoder.decode_16bit_uint() self.data["battery_discharge_max_current"] = round(battery_discharge_max_current * mult, 1) charger_start_time_1_h = decoder.decode_16bit_uint() charger_start_time_1_m = decoder.decode_16bit_uint() self.data["charger_start_time_1"] = f"{charger_start_time_1_h}:{charger_start_time_1_m}" charger_end_time_1_h = decoder.decode_16bit_uint() charger_end_time_1_m = decoder.decode_16bit_uint() self.data["charger_end_time_1"] = f"{charger_end_time_1_h}:{charger_end_time_1_m}" decoder.skip_bytes(8) charger_start_time_2_h = decoder.decode_16bit_uint() charger_start_time_2_m = decoder.decode_16bit_uint() self.data["charger_start_time_2"] = f"{charger_start_time_2_h}:{charger_start_time_2_m}" charger_end_time_2_h = decoder.decode_16bit_uint() charger_end_time_2_m = decoder.decode_16bit_uint() self.data["charger_end_time_2"] = f"{charger_end_time_2_h}:{charger_end_time_2_m}" decoder.skip_bytes(34) registration_code = decoder.decode_string(10).decode("ascii") self.data["registration_code"] = str(registration_code) allow_grid_charges = decoder.decode_16bit_uint() if allow_grid_charges == 0: self.data["allow_grid_charge"] = "Forbidden" elif allow_grid_charges == 1: self.data["allow_grid_charge"] = "Charger Time 1" elif allow_grid_charges == 2: self.data["allow_grid_charge"] = "Charger Time 2" elif allow_grid_charges == 3: self.data["allow_grid_charge"] = "Both Charger Time's" else: self.data["allow_grid_charge"] = "Unknown" export_control_factory_limit = decoder.decode_16bit_uint() self.data["export_control_factory_limit"] = round(export_control_factory_limit * 0.1, 1) export_control_user_limit = decoder.decode_16bit_uint() self.data["export_control_user_limit"] = round(export_control_user_limit * 0.1, 1) eps_mutes = decoder.decode_16bit_uint() if eps_mutes == 0: self.data["eps_mute"] = "Off" elif eps_mutes == 1: self.data["eps_mute"] = "On" else: self.data["eps_mute"] = "Unknown" eps_set_frequencys = decoder.decode_16bit_uint() if eps_set_frequencys == 0: self.data["eps_set_frequency"] = "50Hz" elif eps_set_frequencys == 1: self.data["eps_set_frequency"] = "60Hz" else: self.data["eps_set_frequency"] = "Unknown" decoder.skip_bytes(2) inverter_rate_power = decoder.decode_16bit_uint() self.data["inverter_rate_power"] = inverter_rate_power languages = decoder.decode_16bit_uint() if languages == 0: self.data["language"] = "English" elif languages == 1: self.data["language"] = "Deutsche" elif languages == 2: self.data["language"] = "Francais" elif languages == 3: self.data["language"] = "Polskie" else: self.data["language"] = languages return True def read_modbus_holding_registers_2(self): inverter_data = self.read_holding_registers(unit=1, address=0xfd, count=25) if inverter_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( inverter_data.registers, byteorder=Endian.Big ) backup_gridcharge_s = decoder.decode_16bit_uint() if backup_gridcharge_s == 0: self.data["backup_gridcharge"] = "Disabled" elif backup_gridcharge_s == 1: self.data["backup_gridcharge"] = "Enabled" else: self.data["backup_gridcharge"] = "Unknown" backup_charge_start_h = decoder.decode_16bit_uint() backup_charge_start_m = decoder.decode_16bit_uint() self.data["backup_charge_start"] = f"{backup_charge_start_h}:{backup_charge_start_m}" backup_charge_end_h = decoder.decode_16bit_uint() backup_charge_end_m = decoder.decode_16bit_uint() self.data["backup_charge_end"] = f"{backup_charge_end_h}:{backup_charge_end_m}" was4777_power_manager_s = decoder.decode_16bit_uint() if was4777_power_manager_s == 0: self.data["was4777_power_manager"] = "Disabled" elif was4777_power_manager_s == 1: self.data["was4777_power_manager"] = "Enabled" else: self.data["was4777_power_manager"] = "Unknown" cloud_control_s = decoder.decode_16bit_uint() if cloud_control_s == 0: self.data["cloud_control"] = "Disabled" elif cloud_control_s == 1: self.data["cloud_control"] = "Enabled" else: self.data["cloud_control"] = "Unknown" global_mppt_function_s = decoder.decode_16bit_uint() if global_mppt_function_s == 0: self.data["global_mppt_function"] = "Disabled" elif global_mppt_function_s == 1: self.data["global_mppt_function"] = "Enabled" else: self.data["global_mppt_function"] = "Unknown" grid_service_x3_s = decoder.decode_16bit_uint() if grid_service_x3_s == 0: self.data["grid_service_x3"] = "Disabled" elif grid_service_x3_s == 1: self.data["grid_service_x3"] = "Enabled" else: self.data["grid_service_x3"] = "Unknown" phase_power_balance_x3_s = decoder.decode_16bit_uint() if phase_power_balance_x3_s == 0: self.data["phase_power_balance_x3"] = "Disabled" elif phase_power_balance_x3_s == 1: self.data["phase_power_balance_x3"] = "Enabled" else: self.data["phase_power_balance_x3"] = "Unknown" machine_style_s = decoder.decode_16bit_uint() if machine_style_s == 0: self.data["machine_style"] = "X-Hybrid" elif machine_style_s == 1: self.data["machine_style"] = "X-Retro Fit" else: self.data["machine_style"] = "Unknown" meter_function_s = decoder.decode_16bit_uint() if meter_function_s == 0: self.data["meter_function"] = "Disabled" elif meter_function_s == 1: self.data["meter_function"] = "Enabled" else: self.data["meter_function"] = "Unknown" meter_1_id = decoder.decode_16bit_uint() self.data["meter_1_id"] = meter_1_id meter_2_id = decoder.decode_16bit_uint() self.data["meter_2_id"] = meter_2_id power_control_timeout = decoder.decode_16bit_uint() self.data["power_control_timeout"] = power_control_timeout eps_auto_restart_s = decoder.decode_16bit_uint() if eps_auto_restart_s == 0: self.data["eps_auto_restart"] = "Disabled" elif eps_auto_restart_s == 1: self.data["eps_auto_restart"] = "Enabled" else: self.data["eps_auto_restart"] = "Unknown" eps_min_esc_voltage = decoder.decode_16bit_uint() self.data["eps_min_esc_voltage"] = eps_min_esc_voltage eps_min_esc_soc = decoder.decode_16bit_uint() self.data["eps_min_esc_soc"] = eps_min_esc_soc forcetime_period_1_max_capacity = decoder.decode_16bit_uint() self.data["forcetime_period_1_max_capacity"] = forcetime_period_1_max_capacity forcetime_period_2_max_capacity = decoder.decode_16bit_uint() self.data["forcetime_period_2_max_capacity"] = forcetime_period_2_max_capacity disch_cut_off_point_different_s = decoder.decode_16bit_uint() if disch_cut_off_point_different_s == 0: self.data["disch_cut_off_point_different"] = "Disabled" elif disch_cut_off_point_different_s == 1: self.data["disch_cut_off_point_different"] = "Enabled" else: self.data["disch_cut_off_point_different"] = "Unknown" disch_cut_off_capacity_grid_mode = decoder.decode_16bit_uint() self.data["disch_cut_off_capacity_grid_mode"] = disch_cut_off_capacity_grid_mode disch_cut_off_voltage_grid_mode = decoder.decode_16bit_uint() self.data["disch_cut_off_voltage_grid_mode"] = round(disch_cut_off_voltage_grid_mode * 0.1, 1) earth_detect_x3_s = decoder.decode_16bit_uint() if earth_detect_x3_s == 0: self.data["earth_detect_x3"] = "Disabled" elif earth_detect_x3_s == 1: self.data["earth_detect_x3"] = "Enabled" else: self.data["earth_detect_x3"] = "Unknown" ct_meter_setting_s = decoder.decode_16bit_uint() if ct_meter_setting_s == 0: self.data["ct_meter_setting"] = "Meter" elif ct_meter_setting_s == 1: self.data["ct_meter_setting"] = "CT" else: self.data["ct_meter_setting"] = "Unknown" return True def read_modbus_input_registers_0(self): if self.read_gen2x1 == True: mult = 0.01 else: mult = 0.1 realtime_data = self.read_input_registers(unit=1, address=0x0, count=86) if realtime_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( realtime_data.registers, byteorder=Endian.Big ) inverter_voltage = decoder.decode_16bit_uint() self.data["inverter_voltage"] = round(inverter_voltage * 0.1, 1) inverter_current = decoder.decode_16bit_int() self.data["inverter_current"] = round(inverter_current * 0.1, 1) inverter_load = decoder.decode_16bit_int() self.data["inverter_load"] = inverter_load pv_voltage_1 = decoder.decode_16bit_uint() self.data["pv_voltage_1"] = round(pv_voltage_1 * 0.1, 1) pv_voltage_2 = decoder.decode_16bit_uint() self.data["pv_voltage_2"] = round(pv_voltage_2 * 0.1, 1) pv_current_1 = decoder.decode_16bit_uint() self.data["pv_current_1"] = round(pv_current_1 * 0.1, 1) pv_current_2 = decoder.decode_16bit_uint() self.data["pv_current_2"] = round(pv_current_2 * 0.1, 1) grid_frequency = decoder.decode_16bit_uint() self.data["grid_frequency"] = round(grid_frequency * 0.01, 2) inverter_temperature = decoder.decode_16bit_int() self.data["inverter_temperature"] = inverter_temperature run_modes = decoder.decode_16bit_uint() if run_modes == 0: self.data["run_mode"] = "Waiting" elif run_modes == 1: self.data["run_mode"] = "Checking" elif run_modes == 2: self.data["run_mode"] = "Normal Mode" elif run_modes == 3: self.data["run_mode"] = "Feedin Priority" elif run_modes == 4: self.data["run_mode"] = "Pemanent Fault Mode" elif run_modes == 5: self.data["run_mode"] = "Update Mode" elif run_modes == 6: self.data["run_mode"] = "EPS Check Mode" elif run_modes == 7: self.data["run_mode"] = "EPS Mode" elif run_modes == 8: self.data["run_mode"] = "Self Test" elif run_modes == 9: self.data["run_mode"] = "Idle Mode" else: self.data["run_mode"] = "Unknown" pv_power_1 = decoder.decode_16bit_uint() self.data["pv_power_1"] = pv_power_1 pv_power_2 = decoder.decode_16bit_uint() self.data["pv_power_2"] = pv_power_2 self.data["pv_total_power"] = pv_power_1 + pv_power_2 decoder.skip_bytes(14) time_count_down = decoder.decode_16bit_uint() self.data["time_count_down"] = round(time_count_down * 0.001, 0) battery_voltage_charge = decoder.decode_16bit_int() self.data["battery_voltage_charge"] = round(battery_voltage_charge * mult, 1) battery_current_charge = decoder.decode_16bit_int() self.data["battery_current_charge"] = round(battery_current_charge * mult, 1) battery_power_charge = decoder.decode_16bit_int() self.data["battery_power_charge"] = battery_power_charge bms_connect_states = decoder.decode_16bit_uint() if bms_connect_states == 0: self.data["bms_connect_state"] = "Disconnected" elif bms_connect_states == 1: self.data["bms_connect_state"] = "Connected" else: self.data["bms_connect_state"] = "Unknown" battery_temperature = decoder.decode_16bit_int() self.data["battery_temperature"] = battery_temperature decoder.skip_bytes(6) battery_capacity_charge = decoder.decode_16bit_uint() self.data["battery_capacity_charge"] = battery_capacity_charge output_energy_charge_lsb = decoder.decode_16bit_uint() self.data["output_energy_charge_lsb"] = round(output_energy_charge_lsb * 0.1, 1) output_energy_charge_msb = decoder.decode_16bit_uint() self.data["output_energy_charge_msb"] = round(output_energy_charge_msb * 0.1, 1) bms_warning_lsb = decoder.decode_16bit_uint() self.data["bms_warning_lsb"] = bms_warning_lsb output_energy_charge_today = decoder.decode_16bit_uint() self.data["output_energy_charge_today"] = round(output_energy_charge_today * 0.1, 1) input_energy_charge_lsb = decoder.decode_16bit_uint() self.data["input_energy_charge_lsb"] = round(input_energy_charge_lsb * 0.1, 1) input_energy_charge_msb = decoder.decode_16bit_uint() self.data["input_energy_charge_msb"] = round(input_energy_charge_msb * 0.1, 1) input_energy_charge_today = decoder.decode_16bit_uint() self.data["input_energy_charge_today"] = round(input_energy_charge_today * 0.1, 1) bms_charge_max_current = decoder.decode_16bit_uint() self.data["BMS Charge Max Current"] = round(bms_charge_max_current * 0.1, 1) bms_discharge_max_current = decoder.decode_16bit_uint() self.data["BMS Discharge Max Current"] = round(bms_discharge_max_current * 0.1, 1) bms_warning_msb = decoder.decode_16bit_uint() self.data["bms_warning_msb"] = bms_warning_msb decoder.skip_bytes(62) feedin_power = decoder.decode_16bit_int() self.data["feedin_power"] = feedin_power if feedin_power > 0: self.data["grid_export"] = feedin_power else: self.data["grid_export"] = 0 if feedin_power < 0: self.data["grid_import"] = abs(feedin_power) else: self.data["grid_import"] = 0 self.data["house_load"] = inverter_load - feedin_power feedin_energy_total = decoder.decode_16bit_uint() self.data["feedin_energy_total"] = round(feedin_energy_total * 0.01, 1) decoder.skip_bytes(2) consumed_energy_total = decoder.decode_16bit_uint() self.data["consumed_energy_total"] = round(consumed_energy_total * 0.01, 1) decoder.skip_bytes(2) eps_volatge = decoder.decode_16bit_uint() self.data["eps_volatge"] = round(eps_volatge * 0.1, 1) eps_current = decoder.decode_16bit_uint() self.data["eps_current"] = round(eps_current * 0.1, 1) eps_power = decoder.decode_16bit_uint() self.data["eps_power"] = eps_power eps_current = decoder.decode_16bit_uint() self.data["eps_current"] = round(eps_current * 0.1, 1) eps_frequency = decoder.decode_16bit_uint() self.data["eps_frequency"] = round(eps_frequency * 0.01, 2) energy_today = decoder.decode_16bit_uint() self.data["energy_today"] = round(energy_today * 0.1, 1) decoder.skip_bytes(2) total_energy_to_grid = decoder.decode_16bit_uint() self.data["total_energy_to_grid"] = round(total_energy_to_grid * 0.001, 1) decoder.skip_bytes(2) lock_states = decoder.decode_16bit_uint() if lock_states == 0: self.data["lock_state"] = "Locked" elif lock_states == 1: self.data["lock_state"] = "Unlocked" else: self.data["lock_state"] = "Unknown" return True def read_modbus_input_registers_1(self): realtime_data = self.read_input_registers(unit=1, address=0x66, count=54) if realtime_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( realtime_data.registers, byteorder=Endian.Big ) bus_volt = decoder.decode_16bit_uint() self.data["bus_volt"] = round(bus_volt * 0.1, 1) dc_fault_val = decoder.decode_16bit_uint() self.data["dc_fault_val"] = round(dc_fault_val * 0.1, 1) overload_fault_val = decoder.decode_16bit_uint() self.data["overload_fault_val"] = overload_fault_val battery_volt_fault_val = decoder.decode_16bit_uint() self.data["battery_volt_fault_val"] = round(battery_volt_fault_val * 0.1, 1) grid_voltage_r = decoder.decode_16bit_uint() self.data["grid_voltage_r"] = round(grid_voltage_r * 0.1, 1) grid_current_r = decoder.decode_16bit_int() self.data["grid_current_r"] = round(grid_current_r * 0.1, 1) # @todo Rename variable as it this is the invertor power on phase R, not the grid power. # The grid power is currently named as feedin_power_(rst) # (Measured Power), this quantity means what is Solax measuring via smart meter. grid_power_r = decoder.decode_16bit_int() self.data["grid_power_r"] = round(grid_power_r, 1) grid_frequency_r = decoder.decode_16bit_uint() self.data["grid_frequency_r"] = round(grid_frequency_r * 0.01, 1) grid_voltage_s = decoder.decode_16bit_uint() self.data["grid_voltage_s"] = round(grid_voltage_s * 0.1, 1) grid_current_s = decoder.decode_16bit_int() self.data["grid_current_s"] = round(grid_current_s * 0.1, 1) # @todo Rename variable. grid_power_s = decoder.decode_16bit_int() self.data["grid_power_s"] = round(grid_power_s, 1) grid_frequency_s = decoder.decode_16bit_uint() self.data["grid_frequency_s"] = round(grid_frequency_s * 0.01, 1) grid_voltage_t = decoder.decode_16bit_uint() self.data["grid_voltage_t"] = round(grid_voltage_t * 0.1, 1) grid_current_t = decoder.decode_16bit_int() self.data["grid_current_t"] = round(grid_current_t * 0.1, 1) # @todo Rename variable. grid_power_t = decoder.decode_16bit_int() self.data["grid_power_t"] = round(grid_power_t, 1) grid_frequency_t = decoder.decode_16bit_uint() self.data["grid_frequency_t"] = round(grid_frequency_t * 0.01, 1) eps_voltage_r = decoder.decode_16bit_uint() self.data["eps_voltage_r"] = round(eps_voltage_r * 0.1, 1) eps_current_r = decoder.decode_16bit_uint() self.data["eps_current_r"] = round(eps_current_r * 0.1, 1) eps_power_active_r = decoder.decode_16bit_uint() self.data["eps_power_active_r"] = eps_power_active_r eps_power_r = decoder.decode_16bit_uint() self.data["eps_power_r"] = eps_power_r eps_voltage_s = decoder.decode_16bit_uint() self.data["eps_voltage_s"] = round(eps_voltage_s * 0.1, 1) eps_current_s = decoder.decode_16bit_uint() self.data["eps_current_s"] = round(eps_current_s * 0.1, 1) eps_power_active_s = decoder.decode_16bit_uint() self.data["eps_power_active_s"] = eps_power_active_s eps_power_s = decoder.decode_16bit_uint() self.data["eps_power_s"] = eps_power_s eps_voltage_t = decoder.decode_16bit_uint() self.data["eps_voltage_t"] = round(eps_voltage_t * 0.1, 1) eps_current_t = decoder.decode_16bit_uint() self.data["eps_current_t"] = round(eps_current_t * 0.1, 1) eps_power_active_t = decoder.decode_16bit_uint() self.data["eps_power_active_t"] = eps_power_active_t eps_power_t = decoder.decode_16bit_uint() self.data["eps_power_t"] = eps_power_t feedin_power_r = decoder.decode_16bit_int() self.data["feedin_power_r"] = feedin_power_r decoder.skip_bytes(2) feedin_power_s = decoder.decode_16bit_int() self.data["feedin_power_s"] = feedin_power_s decoder.skip_bytes(2) feedin_power_t = decoder.decode_16bit_int() self.data["feedin_power_t"] = feedin_power_t decoder.skip_bytes(2) grid_mode_runtime = decoder.decode_16bit_int() self.data["grid_mode_runtime"] = round(grid_mode_runtime * 0.1, 1) decoder.skip_bytes(2) eps_mode_runtime = decoder.decode_16bit_int() self.data["eps_mode_runtime"] = round(eps_mode_runtime * 0.1, 1) decoder.skip_bytes(2) normal_runtime = decoder.decode_16bit_int() self.data["normal_runtime"] = round(normal_runtime * 0.1, 1) decoder.skip_bytes(2) eps_yield_total = decoder.decode_16bit_uint() self.data["eps_yield_total"] = round(eps_yield_total * 0.1, 1) decoder.skip_bytes(2) eps_yield_today = decoder.decode_16bit_uint() self.data["eps_yield_today"] = round(eps_yield_today * 0.1, 1) e_charge_today = decoder.decode_16bit_uint() self.data["e_charge_today"] = e_charge_today e_charge_total = decoder.decode_16bit_uint() self.data["e_charge_total"] = e_charge_total decoder.skip_bytes(2) solar_energy_total = decoder.decode_16bit_uint() self.data["solar_energy_total"] = round(solar_energy_total * 0.1, 1) decoder.skip_bytes(2) solar_energy_today = decoder.decode_16bit_uint() self.data["solar_energy_today"] = round(solar_energy_today * 0.1, 1) decoder.skip_bytes(2) export_energy_today = decoder.decode_16bit_uint() self.data["export_energy_today"] = round(export_energy_today * 0.01, 2) decoder.skip_bytes(2) import_energy_today = decoder.decode_16bit_uint() self.data["import_energy_today"] = round(import_energy_today * 0.01, 2) return True
solax_modbus/__init__.py
import asyncio import logging import threading from datetime import timedelta from typing import Optional import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.event import async_track_time_interval from pymodbus.client.sync import ModbusTcpClient from pymodbus.constants import Endian from pymodbus.exceptions import ConnectionException from pymodbus.payload import BinaryPayloadDecoder from .const import ( DEFAULT_NAME, DEFAULT_SCAN_INTERVAL, DOMAIN, CONF_READ_GEN2X1, CONF_READ_GEN3X1, CONF_READ_GEN3X3, CONF_READ_X1_EPS, CONF_READ_X3_EPS, DEFAULT_READ_GEN2X1, DEFAULT_READ_GEN3X1, DEFAULT_READ_GEN3X3, DEFAULT_READ_X1_EPS, DEFAULT_READ_X3_EPS, ) _LOGGER = logging.getLogger(__name__) SOLAX_MODBUS_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PORT): cv.string, vol.Optional(CONF_READ_GEN2X1, default=DEFAULT_READ_GEN2X1): cv.boolean, vol.Optional(CONF_READ_GEN3X1, default=DEFAULT_READ_GEN3X1): cv.boolean, vol.Optional(CONF_READ_GEN3X3, default=DEFAULT_READ_GEN3X3): cv.boolean, vol.Optional(CONF_READ_X1_EPS, default=DEFAULT_READ_X1_EPS): cv.boolean, vol.Optional(CONF_READ_X3_EPS, default=DEFAULT_READ_X3_EPS): cv.boolean, vol.Optional( CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL ): cv.positive_int, } ) CONFIG_SCHEMA = vol.Schema( {DOMAIN: vol.Schema({cv.slug: SOLAX_MODBUS_SCHEMA})}, extra=vol.ALLOW_EXTRA ) PLATFORMS = ["number", "select", "sensor"] async def async_setup(hass, config): """Set up the SolaX modbus component.""" hass.data[DOMAIN] = {} return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up a SolaX mobus.""" host = entry.data[CONF_HOST] name = entry.data[CONF_NAME] port = entry.data[CONF_PORT] scan_interval = entry.data[CONF_SCAN_INTERVAL] read_gen2x1 = entry.data.get(CONF_READ_GEN2X1, False) read_gen3x1 = entry.data.get(CONF_READ_GEN3X1, False) read_gen3x3 = entry.data.get(CONF_READ_GEN3X3, False) read_x1_eps = entry.data.get(CONF_READ_X1_EPS, False) read_x3_eps = entry.data.get(CONF_READ_X3_EPS, False) _LOGGER.debug("Setup %s.%s", DOMAIN, name) hub = SolaXModbusHub(hass, name, host, port, scan_interval, read_gen2x1, read_gen3x1, read_gen3x3, read_x1_eps, read_x3_eps) """Register the hub.""" hass.data[DOMAIN][name] = {"hub": hub} for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True async def async_unload_entry(hass, entry): """Unload SolaX mobus entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if not unload_ok: return False hass.data[DOMAIN].pop(entry.data["name"]) return True class SolaXModbusHub: """Thread safe wrapper class for pymodbus.""" def __init__( self, hass, name, host, port, scan_interval, read_gen2x1=False, read_gen3x1=False, read_gen3x3=False, read_x1_eps=False, read_x3_eps=False, ): """Initialize the Modbus hub.""" self._hass = hass self._client = ModbusTcpClient(host=host, port=port, timeout=5) self._lock = threading.Lock() self._name = name self.read_gen2x1 = read_gen2x1 self.read_gen3x1 = read_gen3x1 self.read_gen3x3 = read_gen3x3 self.read_x1_eps = read_x1_eps self.read_x3_eps = read_x3_eps self._scan_interval = timedelta(seconds=scan_interval) self._unsub_interval_method = None self._sensors = [] self.data = {} @callback def async_add_solax_modbus_sensor(self, update_callback): """Listen for data updates.""" # This is the first sensor, set up interval. if not self._sensors: self.connect() self._unsub_interval_method = async_track_time_interval( self._hass, self.async_refresh_modbus_data, self._scan_interval ) self._sensors.append(update_callback) @callback def async_remove_solax_modbus_sensor(self, update_callback): """Remove data update.""" self._sensors.remove(update_callback) if not self._sensors: """stop the interval timer upon removal of last sensor""" self._unsub_interval_method() self._unsub_interval_method = None self.close() async def async_refresh_modbus_data(self, _now: Optional[int] = None) -> None: """Time to update.""" if not self._sensors: return update_result = self.read_modbus_data() if update_result: for update_callback in self._sensors: update_callback() @property def name(self): """Return the name of this hub.""" return self._name def close(self): """Disconnect client.""" with self._lock: self._client.close() def connect(self): """Connect client.""" with self._lock: self._client.connect() def read_holding_registers(self, unit, address, count): """Read holding registers.""" with self._lock: kwargs = {"unit": unit} if unit else {} return self._client.read_holding_registers(address, count, **kwargs) def read_input_registers(self, unit, address, count): """Read input registers.""" with self._lock: kwargs = {"unit": unit} if unit else {} return self._client.read_input_registers(address, count, **kwargs) def write_register(self, unit, address, payload): """Write registers.""" with self._lock: kwargs = {"unit": unit} if unit else {} return self._client.write_register(address, payload, **kwargs) def read_modbus_data(self): try: return self.read_modbus_holding_registers_0() and self.read_modbus_holding_registers_1() and self.read_modbus_holding_registers_2() and self.read_modbus_input_registers_0() and self.read_modbus_input_registers_1() except ConnectionException as ex: _LOGGER.error("Reading data failed! Inverter is offline.") return True def read_modbus_holding_registers_0(self): inverter_data = self.read_holding_registers(unit=1, address=0x0, count=21) if inverter_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( inverter_data.registers, byteorder=Endian.Big ) seriesnumber = decoder.decode_string(14).decode("ascii") self.data["seriesnumber"] = str(seriesnumber) factoryname = decoder.decode_string(14).decode("ascii") self.data["factoryname"] = str(factoryname) modulename = decoder.decode_string(14).decode("ascii") self.data["modulename"] = str(modulename) return True def read_modbus_holding_registers_1(self): if self.read_gen2x1 == True: mult = 0.01 else: mult = 0.1 inverter_data = self.read_holding_registers(unit=1, address=0x7d, count=64) if inverter_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( inverter_data.registers, byteorder=Endian.Big ) firmwareversion_invertermaster = decoder.decode_16bit_uint() self.data["firmwareversion_invertermaster"] = firmwareversion_invertermaster decoder.skip_bytes(6) firmwareversion_modbustcp_major = decoder.decode_16bit_uint() self.data["firmwareversion_modbustcp_major"] = firmwareversion_modbustcp_major firmwareversion_modbustcp_minor = decoder.decode_16bit_uint() self.data["firmwareversion_modbustcp_minor"] = firmwareversion_modbustcp_minor firmwareversion_manager = decoder.decode_16bit_uint() self.data["firmwareversion_manager"] = firmwareversion_manager myaddress = decoder.decode_16bit_uint() self.data["myaddress"] = myaddress rtc_seconds = decoder.decode_16bit_uint() self.data["rtc_seconds"] = rtc_seconds rtc_minutes = decoder.decode_16bit_uint() rtc_hours = decoder.decode_16bit_uint() rtc_days = decoder.decode_16bit_uint() rtc_months = decoder.decode_16bit_uint() rtc_years = decoder.decode_16bit_uint() self.data["rtc"] = f"{rtc_hours}:{rtc_minutes}:{rtc_seconds} {rtc_days}/{rtc_months}/{rtc_years}" charger_use_modes = decoder.decode_16bit_uint() if charger_use_modes == 0: self.data["charger_use_mode"] = "Self Use Mode" elif charger_use_modes == 1: self.data["charger_use_mode"] = "Force Time Use" elif charger_use_modes == 2: self.data["charger_use_mode"] = "Back Up Mode" elif charger_use_modes == 3: self.data["charger_use_mode"] = "Feedin Priority" else: self.data["charger_use_mode"] = "Unknown" battery_min_capacity = decoder.decode_16bit_uint() self.data["battery_min_capacity"] = battery_min_capacity battery_types = decoder.decode_16bit_uint() if battery_types == 0: self.data["battery_type"] = "Lead Acid" elif battery_types == 1: self.data["battery_type"] = "Lithium" else: self.data["battery_type"] = "Unknown" battery_charge_float_voltage = decoder.decode_16bit_uint() self.data["battery_charge_float_voltage"] = round(battery_charge_float_voltage * 0.1, 1) battery_discharge_cut_off_voltage = decoder.decode_16bit_uint() self.data["battery_discharge_cut_off_voltage"] = round(battery_discharge_cut_off_voltage * 0.1, 1) battery_charge_max_current = decoder.decode_16bit_uint() self.data["battery_charge_max_current"] = round(battery_charge_max_current * mult, 1) battery_discharge_max_current = decoder.decode_16bit_uint() self.data["battery_discharge_max_current"] = round(battery_discharge_max_current * mult, 1) charger_start_time_1_h = decoder.decode_16bit_uint() charger_start_time_1_m = decoder.decode_16bit_uint() self.data["charger_start_time_1"] = f"{charger_start_time_1_h}:{charger_start_time_1_m}" charger_end_time_1_h = decoder.decode_16bit_uint() charger_end_time_1_m = decoder.decode_16bit_uint() self.data["charger_end_time_1"] = f"{charger_end_time_1_h}:{charger_end_time_1_m}" decoder.skip_bytes(8) charger_start_time_2_h = decoder.decode_16bit_uint() charger_start_time_2_m = decoder.decode_16bit_uint() self.data["charger_start_time_2"] = f"{charger_start_time_2_h}:{charger_start_time_2_m}" charger_end_time_2_h = decoder.decode_16bit_uint() charger_end_time_2_m = decoder.decode_16bit_uint() self.data["charger_end_time_2"] = f"{charger_end_time_2_h}:{charger_end_time_2_m}" decoder.skip_bytes(34) registration_code = decoder.decode_string(10).decode("ascii") self.data["registration_code"] = str(registration_code) allow_grid_charges = decoder.decode_16bit_uint() if allow_grid_charges == 0: self.data["allow_grid_charge"] = "Forbidden" elif allow_grid_charges == 1: self.data["allow_grid_charge"] = "Charger Time 1" elif allow_grid_charges == 2: self.data["allow_grid_charge"] = "Charger Time 2" elif allow_grid_charges == 3: self.data["allow_grid_charge"] = "Both Charger Time's" else: self.data["allow_grid_charge"] = "Unknown" export_control_factory_limit = decoder.decode_16bit_uint() self.data["export_control_factory_limit"] = round(export_control_factory_limit * 0.1, 1) export_control_user_limit = decoder.decode_16bit_uint() self.data["export_control_user_limit"] = round(export_control_user_limit * 0.1, 1) eps_mutes = decoder.decode_16bit_uint() if eps_mutes == 0: self.data["eps_mute"] = "Off" elif eps_mutes == 1: self.data["eps_mute"] = "On" else: self.data["eps_mute"] = "Unknown" eps_set_frequencys = decoder.decode_16bit_uint() if eps_set_frequencys == 0: self.data["eps_set_frequency"] = "50Hz" elif eps_set_frequencys == 1: self.data["eps_set_frequency"] = "60Hz" else: self.data["eps_set_frequency"] = "Unknown" decoder.skip_bytes(2) inverter_rate_power = decoder.decode_16bit_uint() self.data["inverter_rate_power"] = inverter_rate_power languages = decoder.decode_16bit_uint() if languages == 0: self.data["language"] = "English" elif languages == 1: self.data["language"] = "Deutsche" elif languages == 2: self.data["language"] = "Francais" elif languages == 3: self.data["language"] = "Polskie" else: self.data["language"] = languages return True def read_modbus_holding_registers_2(self): inverter_data = self.read_holding_registers(unit=1, address=0xfd, count=25) if inverter_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( inverter_data.registers, byteorder=Endian.Big ) backup_gridcharge_s = decoder.decode_16bit_uint() if backup_gridcharge_s == 0: self.data["backup_gridcharge"] = "Disabled" elif backup_gridcharge_s == 1: self.data["backup_gridcharge"] = "Enabled" else: self.data["backup_gridcharge"] = "Unknown" backup_charge_start_h = decoder.decode_16bit_uint() backup_charge_start_m = decoder.decode_16bit_uint() self.data["backup_charge_start"] = f"{backup_charge_start_h}:{backup_charge_start_m}" backup_charge_end_h = decoder.decode_16bit_uint() backup_charge_end_m = decoder.decode_16bit_uint() self.data["backup_charge_end"] = f"{backup_charge_end_h}:{backup_charge_end_m}" was4777_power_manager_s = decoder.decode_16bit_uint() if was4777_power_manager_s == 0: self.data["was4777_power_manager"] = "Disabled" elif was4777_power_manager_s == 1: self.data["was4777_power_manager"] = "Enabled" else: self.data["was4777_power_manager"] = "Unknown" cloud_control_s = decoder.decode_16bit_uint() if cloud_control_s == 0: self.data["cloud_control"] = "Disabled" elif cloud_control_s == 1: self.data["cloud_control"] = "Enabled" else: self.data["cloud_control"] = "Unknown" global_mppt_function_s = decoder.decode_16bit_uint() if global_mppt_function_s == 0: self.data["global_mppt_function"] = "Disabled" elif global_mppt_function_s == 1: self.data["global_mppt_function"] = "Enabled" else: self.data["global_mppt_function"] = "Unknown" grid_service_x3_s = decoder.decode_16bit_uint() if grid_service_x3_s == 0: self.data["grid_service_x3"] = "Disabled" elif grid_service_x3_s == 1: self.data["grid_service_x3"] = "Enabled" else: self.data["grid_service_x3"] = "Unknown" phase_power_balance_x3_s = decoder.decode_16bit_uint() if phase_power_balance_x3_s == 0: self.data["phase_power_balance_x3"] = "Disabled" elif phase_power_balance_x3_s == 1: self.data["phase_power_balance_x3"] = "Enabled" else: self.data["phase_power_balance_x3"] = "Unknown" machine_style_s = decoder.decode_16bit_uint() if machine_style_s == 0: self.data["machine_style"] = "X-Hybrid" elif machine_style_s == 1: self.data["machine_style"] = "X-Retro Fit" else: self.data["machine_style"] = "Unknown" meter_function_s = decoder.decode_16bit_uint() if meter_function_s == 0: self.data["meter_function"] = "Disabled" elif meter_function_s == 1: self.data["meter_function"] = "Enabled" else: self.data["meter_function"] = "Unknown" meter_1_id = decoder.decode_16bit_uint() self.data["meter_1_id"] = meter_1_id meter_2_id = decoder.decode_16bit_uint() self.data["meter_2_id"] = meter_2_id power_control_timeout = decoder.decode_16bit_uint() self.data["power_control_timeout"] = power_control_timeout eps_auto_restart_s = decoder.decode_16bit_uint() if eps_auto_restart_s == 0: self.data["eps_auto_restart"] = "Disabled" elif eps_auto_restart_s == 1: self.data["eps_auto_restart"] = "Enabled" else: self.data["eps_auto_restart"] = "Unknown" eps_min_esc_voltage = decoder.decode_16bit_uint() self.data["eps_min_esc_voltage"] = eps_min_esc_voltage eps_min_esc_soc = decoder.decode_16bit_uint() self.data["eps_min_esc_soc"] = eps_min_esc_soc forcetime_period_1_max_capacity = decoder.decode_16bit_uint() self.data["forcetime_period_1_max_capacity"] = forcetime_period_1_max_capacity forcetime_period_2_max_capacity = decoder.decode_16bit_uint() self.data["forcetime_period_2_max_capacity"] = forcetime_period_2_max_capacity disch_cut_off_point_different_s = decoder.decode_16bit_uint() if disch_cut_off_point_different_s == 0: self.data["disch_cut_off_point_different"] = "Disabled" elif disch_cut_off_point_different_s == 1: self.data["disch_cut_off_point_different"] = "Enabled" else: self.data["disch_cut_off_point_different"] = "Unknown" disch_cut_off_capacity_grid_mode = decoder.decode_16bit_uint() self.data["disch_cut_off_capacity_grid_mode"] = disch_cut_off_capacity_grid_mode disch_cut_off_voltage_grid_mode = decoder.decode_16bit_uint() self.data["disch_cut_off_voltage_grid_mode"] = round(disch_cut_off_voltage_grid_mode * 0.1, 1) earth_detect_x3_s = decoder.decode_16bit_uint() if earth_detect_x3_s == 0: self.data["earth_detect_x3"] = "Disabled" elif earth_detect_x3_s == 1: self.data["earth_detect_x3"] = "Enabled" else: self.data["earth_detect_x3"] = "Unknown" ct_meter_setting_s = decoder.decode_16bit_uint() if ct_meter_setting_s == 0: self.data["ct_meter_setting"] = "Meter" elif ct_meter_setting_s == 1: self.data["ct_meter_setting"] = "CT" else: self.data["ct_meter_setting"] = "Unknown" return True def read_modbus_input_registers_0(self): if self.read_gen2x1 == True: mult = 0.01 else: mult = 0.1 realtime_data = self.read_input_registers(unit=1, address=0x0, count=86) if realtime_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( realtime_data.registers, byteorder=Endian.Big ) inverter_voltage = decoder.decode_16bit_uint() self.data["inverter_voltage"] = round(inverter_voltage * 0.1, 1) inverter_current = decoder.decode_16bit_int() self.data["inverter_current"] = round(inverter_current * 0.1, 1) inverter_load = decoder.decode_16bit_int() self.data["inverter_load"] = inverter_load pv_voltage_1 = decoder.decode_16bit_uint() self.data["pv_voltage_1"] = round(pv_voltage_1 * 0.1, 1) pv_voltage_2 = decoder.decode_16bit_uint() self.data["pv_voltage_2"] = round(pv_voltage_2 * 0.1, 1) pv_current_1 = decoder.decode_16bit_uint() self.data["pv_current_1"] = round(pv_current_1 * 0.1, 1) pv_current_2 = decoder.decode_16bit_uint() self.data["pv_current_2"] = round(pv_current_2 * 0.1, 1) grid_frequency = decoder.decode_16bit_uint() self.data["grid_frequency"] = round(grid_frequency * 0.01, 2) inverter_temperature = decoder.decode_16bit_int() self.data["inverter_temperature"] = inverter_temperature run_modes = decoder.decode_16bit_uint() if run_modes == 0: self.data["run_mode"] = "Waiting" elif run_modes == 1: self.data["run_mode"] = "Checking" elif run_modes == 2: self.data["run_mode"] = "Normal Mode" elif run_modes == 3: self.data["run_mode"] = "Feedin Priority" elif run_modes == 4: self.data["run_mode"] = "Pemanent Fault Mode" elif run_modes == 5: self.data["run_mode"] = "Update Mode" elif run_modes == 6: self.data["run_mode"] = "EPS Check Mode" elif run_modes == 7: self.data["run_mode"] = "EPS Mode" elif run_modes == 8: self.data["run_mode"] = "Self Test" elif run_modes == 9: self.data["run_mode"] = "Idle Mode" else: self.data["run_mode"] = "Unknown" pv_power_1 = decoder.decode_16bit_uint() self.data["pv_power_1"] = pv_power_1 pv_power_2 = decoder.decode_16bit_uint() self.data["pv_power_2"] = pv_power_2 self.data["pv_total_power"] = pv_power_1 + pv_power_2 decoder.skip_bytes(14) time_count_down = decoder.decode_16bit_uint() self.data["time_count_down"] = round(time_count_down * 0.001, 0) battery_voltage_charge = decoder.decode_16bit_int() self.data["battery_voltage_charge"] = round(battery_voltage_charge * mult, 1) battery_current_charge = decoder.decode_16bit_int() self.data["battery_current_charge"] = round(battery_current_charge * mult, 1) battery_power_charge = decoder.decode_16bit_int() self.data["battery_power_charge"] = battery_power_charge bms_connect_states = decoder.decode_16bit_uint() if bms_connect_states == 0: self.data["bms_connect_state"] = "Disconnected" elif bms_connect_states == 1: self.data["bms_connect_state"] = "Connected" else: self.data["bms_connect_state"] = "Unknown" battery_temperature = decoder.decode_16bit_int() self.data["battery_temperature"] = battery_temperature decoder.skip_bytes(6) battery_capacity_charge = decoder.decode_16bit_uint() self.data["battery_capacity_charge"] = battery_capacity_charge output_energy_charge_lsb = decoder.decode_16bit_uint() self.data["output_energy_charge_lsb"] = round(output_energy_charge_lsb * 0.1, 1) output_energy_charge_msb = decoder.decode_16bit_uint() self.data["output_energy_charge_msb"] = round(output_energy_charge_msb * 0.1, 1) bms_warning_lsb = decoder.decode_16bit_uint() self.data["bms_warning_lsb"] = bms_warning_lsb output_energy_charge_today = decoder.decode_16bit_uint() self.data["output_energy_charge_today"] = round(output_energy_charge_today * 0.1, 1) input_energy_charge_lsb = decoder.decode_16bit_uint() self.data["input_energy_charge_lsb"] = round(input_energy_charge_lsb * 0.1, 1) input_energy_charge_msb = decoder.decode_16bit_uint() self.data["input_energy_charge_msb"] = round(input_energy_charge_msb * 0.1, 1) input_energy_charge_today = decoder.decode_16bit_uint() self.data["input_energy_charge_today"] = round(input_energy_charge_today * 0.1, 1) bms_charge_max_current = decoder.decode_16bit_uint() self.data["BMS Charge Max Current"] = round(bms_charge_max_current * 0.1, 1) bms_discharge_max_current = decoder.decode_16bit_uint() self.data["BMS Discharge Max Current"] = round(bms_discharge_max_current * 0.1, 1) bms_warning_msb = decoder.decode_16bit_uint() self.data["bms_warning_msb"] = bms_warning_msb decoder.skip_bytes(62) feedin_power = decoder.decode_16bit_int() self.data["feedin_power"] = feedin_power if feedin_power > 0: self.data["grid_export"] = feedin_power else: self.data["grid_export"] = 0 if feedin_power < 0: self.data["grid_import"] = abs(feedin_power) else: self.data["grid_import"] = 0 self.data["house_load"] = inverter_load - feedin_power feedin_energy_total = decoder.decode_16bit_uint() self.data["feedin_energy_total"] = round(feedin_energy_total * 0.01, 1) decoder.skip_bytes(2) consumed_energy_total = decoder.decode_16bit_uint() self.data["consumed_energy_total"] = round(consumed_energy_total * 0.01, 1) decoder.skip_bytes(2) eps_volatge = decoder.decode_16bit_uint() self.data["eps_volatge"] = round(eps_volatge * 0.1, 1) eps_current = decoder.decode_16bit_uint() self.data["eps_current"] = round(eps_current * 0.1, 1) eps_power = decoder.decode_16bit_uint() self.data["eps_power"] = eps_power eps_current = decoder.decode_16bit_uint() self.data["eps_current"] = round(eps_current * 0.1, 1) eps_frequency = decoder.decode_16bit_uint() self.data["eps_frequency"] = round(eps_frequency * 0.01, 2) energy_today = decoder.decode_16bit_uint() self.data["energy_today"] = round(energy_today * 0.1, 1) decoder.skip_bytes(2) total_energy_to_grid = decoder.decode_16bit_uint() self.data["total_energy_to_grid"] = round(total_energy_to_grid * 0.001, 1) decoder.skip_bytes(2) lock_states = decoder.decode_16bit_uint() if lock_states == 0: self.data["lock_state"] = "Locked" elif lock_states == 1: self.data["lock_state"] = "Unlocked" else: self.data["lock_state"] = "Unknown" return True def read_modbus_input_registers_1(self): realtime_data = self.read_input_registers(unit=1, address=0x66, count=54) if realtime_data.isError(): return False decoder = BinaryPayloadDecoder.fromRegisters( realtime_data.registers, byteorder=Endian.Big ) bus_volt = decoder.decode_16bit_uint() self.data["bus_volt"] = round(bus_volt * 0.1, 1) dc_fault_val = decoder.decode_16bit_uint() self.data["dc_fault_val"] = round(dc_fault_val * 0.1, 1) overload_fault_val = decoder.decode_16bit_uint() self.data["overload_fault_val"] = overload_fault_val battery_volt_fault_val = decoder.decode_16bit_uint() self.data["battery_volt_fault_val"] = round(battery_volt_fault_val * 0.1, 1) grid_voltage_r = decoder.decode_16bit_uint() self.data["grid_voltage_r"] = round(grid_voltage_r * 0.1, 1) grid_current_r = decoder.decode_16bit_int() self.data["grid_current_r"] = round(grid_current_r * 0.1, 1) # @todo Rename variable as it this is the invertor power on phase R, not the grid power. # The grid power is currently named as feedin_power_(rst) # (Measured Power), this quantity means what is Solax measuring via smart meter. grid_power_r = decoder.decode_16bit_int() self.data["grid_power_r"] = round(grid_power_r, 1) grid_frequency_r = decoder.decode_16bit_uint() self.data["grid_frequency_r"] = round(grid_frequency_r * 0.01, 1) grid_voltage_s = decoder.decode_16bit_uint() self.data["grid_voltage_s"] = round(grid_voltage_s * 0.1, 1) grid_current_s = decoder.decode_16bit_int() self.data["grid_current_s"] = round(grid_current_s * 0.1, 1) # @todo Rename variable. grid_power_s = decoder.decode_16bit_int() self.data["grid_power_s"] = round(grid_power_s, 1) grid_frequency_s = decoder.decode_16bit_uint() self.data["grid_frequency_s"] = round(grid_frequency_s * 0.01, 1) grid_voltage_t = decoder.decode_16bit_uint() self.data["grid_voltage_t"] = round(grid_voltage_t * 0.1, 1) grid_current_t = decoder.decode_16bit_int() self.data["grid_current_t"] = round(grid_current_t * 0.1, 1) # @todo Rename variable. grid_power_t = decoder.decode_16bit_int() self.data["grid_power_t"] = round(grid_power_t, 1) grid_frequency_t = decoder.decode_16bit_uint() self.data["grid_frequency_t"] = round(grid_frequency_t * 0.01, 1) eps_voltage_r = decoder.decode_16bit_uint() self.data["eps_voltage_r"] = round(eps_voltage_r * 0.1, 1) eps_current_r = decoder.decode_16bit_uint() self.data["eps_current_r"] = round(eps_current_r * 0.1, 1) eps_power_active_r = decoder.decode_16bit_uint() self.data["eps_power_active_r"] = eps_power_active_r eps_power_r = decoder.decode_16bit_uint() self.data["eps_power_r"] = eps_power_r eps_voltage_s = decoder.decode_16bit_uint() self.data["eps_voltage_s"] = round(eps_voltage_s * 0.1, 1) eps_current_s = decoder.decode_16bit_uint() self.data["eps_current_s"] = round(eps_current_s * 0.1, 1) eps_power_active_s = decoder.decode_16bit_uint() self.data["eps_power_active_s"] = eps_power_active_s eps_power_s = decoder.decode_16bit_uint() self.data["eps_power_s"] = eps_power_s eps_voltage_t = decoder.decode_16bit_uint() self.data["eps_voltage_t"] = round(eps_voltage_t * 0.1, 1) eps_current_t = decoder.decode_16bit_uint() self.data["eps_current_t"] = round(eps_current_t * 0.1, 1) eps_power_active_t = decoder.decode_16bit_uint() self.data["eps_power_active_t"] = eps_power_active_t eps_power_t = decoder.decode_16bit_uint() self.data["eps_power_t"] = eps_power_t feedin_power_r = decoder.decode_16bit_int() self.data["feedin_power_r"] = feedin_power_r decoder.skip_bytes(2) feedin_power_s = decoder.decode_16bit_int() self.data["feedin_power_s"] = feedin_power_s decoder.skip_bytes(2) feedin_power_t = decoder.decode_16bit_int() self.data["feedin_power_t"] = feedin_power_t decoder.skip_bytes(2) grid_mode_runtime = decoder.decode_16bit_int() self.data["grid_mode_runtime"] = round(grid_mode_runtime * 0.1, 1) decoder.skip_bytes(2) eps_mode_runtime = decoder.decode_16bit_int() self.data["eps_mode_runtime"] = round(eps_mode_runtime * 0.1, 1) decoder.skip_bytes(2) normal_runtime = decoder.decode_16bit_int() self.data["normal_runtime"] = round(normal_runtime * 0.1, 1) decoder.skip_bytes(2) eps_yield_total = decoder.decode_16bit_uint() self.data["eps_yield_total"] = round(eps_yield_total * 0.1, 1) decoder.skip_bytes(2) eps_yield_today = decoder.decode_16bit_uint() self.data["eps_yield_today"] = round(eps_yield_today * 0.1, 1) e_charge_today = decoder.decode_16bit_uint() self.data["e_charge_today"] = e_charge_today e_charge_total = decoder.decode_16bit_uint() self.data["e_charge_total"] = e_charge_total decoder.skip_bytes(2) solar_energy_total = decoder.decode_16bit_uint() self.data["solar_energy_total"] = round(solar_energy_total * 0.1, 1) decoder.skip_bytes(2) solar_energy_today = decoder.decode_16bit_uint() self.data["solar_energy_today"] = round(solar_energy_today * 0.1, 1) decoder.skip_bytes(2) export_energy_today = decoder.decode_16bit_uint() self.data["export_energy_today"] = round(export_energy_today * 0.01, 2) decoder.skip_bytes(2) import_energy_today = decoder.decode_16bit_uint() self.data["import_energy_today"] = round(import_energy_today * 0.01, 2) return True
0.787114
0.119562
import torch import torch.nn as nn from torch import optim from torch.utils.data import DataLoader from torch.utils.data.dataset import Dataset import numpy as np class Classification_Dataloader(Dataset): def __init__(self, hands_lines): super(Classification_Dataloader, self).__init__() self.hands_lines = hands_lines def __len__(self): return len(self.hands_lines) def __getitem__(self, index): hands_lines = self.hands_lines hand_steam = hands_lines[index][:-1] tmp_target = torch.tensor([int(hands_lines[index][-1])]) tmp_hand = torch.tensor(hand_steam).reshape((10, 14, 2)) return tmp_hand, tmp_target def classification_collate(batch): '''此时batch为1''' hands = [] # targets = [] for hand, target in batch: hand = torch.split(hand, 1, dim=-1) hand = torch.stack((torch.squeeze(hand[0]), torch.squeeze(hand[1])), dim=0) hands.append(hand) targets = target # targets.append(target) hands = torch.stack(hands) # hands = torch.squeeze(hands.permute(0, 1, 3, 2)) hands = torch.squeeze(hands) # targets = torch.stack(targets) return hands, targets class Classification(nn.Module): def __init__(self): super(Classification, self).__init__() self.conv1 = nn.Sequential(nn.Conv1d(10, 100, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(100), nn.ReLU(True)) self.conv2 = nn.Sequential(nn.Conv1d(100, 100, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(100), nn.ReLU(True)) self.conv3 = nn.Sequential(nn.Conv1d(100, 160, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(160), nn.ReLU(True)) self.conv4 = nn.Sequential(nn.Conv1d(160, 160, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(160), nn.ReLU(True)) self.avepooling = nn.AvgPool1d(2, stride=1) self.maxpooling = nn.MaxPool1d(5, stride=1) self.dropout = nn.Dropout(p=0.5) self.fc = nn.Sequential(nn.Linear(320, 5), nn.Softmax(dim=0)) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.maxpooling(x) x = self.conv3(x) x = self.conv4(x) x = self.avepooling(x) x = x.reshape(320) x = self.dropout(x) # x = x.view(x.size(0), -1) x = self.fc(x) return x def train_model(self, data, batch, learning_rate, num_epoches, save=True): '''训练模型并保存''' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') dataset = Classification_Dataloader(data) train_dataset = DataLoader(dataset, batch_size=batch, shuffle=True, collate_fn=classification_collate) model = Classification().to(device) model.train(mode=True) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) total_step = len(train_dataset) for epoch in range(num_epoches): for i, hands in enumerate(train_dataset): hand, label = hands hand = hand.to(device) label = label.to(device) optimizer.zero_grad() outputs = model(hand) outputs = outputs.unsqueeze(dim=0) loss = criterion(outputs, label) loss.backward() optimizer.step() if (i + 1) % 50 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss:{:.4f}'.format(epoch + 1, num_epoches, i + 1, total_step, loss.item())) print('outputs:{}'.format(outputs.tolist())) if i+1 == 100: b=1 if save: # summary(model, (2, 5, 42)) torch.save(model.state_dict(), 'num_{}_batch_{}_lr_{}_ep_{}.pth'.format(1, batch, learning_rate, num_epoches)) def predict(self, hand, file): '''加载模型进行推理''' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') hands = torch.tensor(hand).reshape((10, 14, 2)) hands = torch.split(hands, 1, dim=-1) hands = torch.stack((torch.squeeze(hands[0]), torch.squeeze(hands[1])), dim=0) # hands = hands.permute(0, 2, 1) # hands = hands.reshape((1, 2, 5, 42)) hands = hands.to(device) model = Classification().to(device) model.load_state_dict(torch.load(file,map_location='cpu')) model.eval() result = model(hands) return result # # troch.nn.RNN(input_size,hidden_size,num_layers) # rnn = nn.RNN(10, 20, 2) # # input1 = (L,N,H) tensor containing input features where H =input_size and L represents a sequence length. # input = torch.randn(5, 3, 10) # # input2 = (S,N,H) tensor containing the initial hidden state for each element in the batch. H=hidden_size Defaults to zero if not provided. where S=num_layers∗num_directions If the RNN is bidirectional, num_directions should be 2, else it should be 1. # h0 = torch.randn(2, 3, 20) # # output1 = (L,N,H) where H = num_directions * hidden_size # # output2 = (S,N,H) tensor containing the next hidden state for each element in the batch # output, hn = rnn(input, h0) # a = 1
classification.py
import torch import torch.nn as nn from torch import optim from torch.utils.data import DataLoader from torch.utils.data.dataset import Dataset import numpy as np class Classification_Dataloader(Dataset): def __init__(self, hands_lines): super(Classification_Dataloader, self).__init__() self.hands_lines = hands_lines def __len__(self): return len(self.hands_lines) def __getitem__(self, index): hands_lines = self.hands_lines hand_steam = hands_lines[index][:-1] tmp_target = torch.tensor([int(hands_lines[index][-1])]) tmp_hand = torch.tensor(hand_steam).reshape((10, 14, 2)) return tmp_hand, tmp_target def classification_collate(batch): '''此时batch为1''' hands = [] # targets = [] for hand, target in batch: hand = torch.split(hand, 1, dim=-1) hand = torch.stack((torch.squeeze(hand[0]), torch.squeeze(hand[1])), dim=0) hands.append(hand) targets = target # targets.append(target) hands = torch.stack(hands) # hands = torch.squeeze(hands.permute(0, 1, 3, 2)) hands = torch.squeeze(hands) # targets = torch.stack(targets) return hands, targets class Classification(nn.Module): def __init__(self): super(Classification, self).__init__() self.conv1 = nn.Sequential(nn.Conv1d(10, 100, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(100), nn.ReLU(True)) self.conv2 = nn.Sequential(nn.Conv1d(100, 100, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(100), nn.ReLU(True)) self.conv3 = nn.Sequential(nn.Conv1d(100, 160, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(160), nn.ReLU(True)) self.conv4 = nn.Sequential(nn.Conv1d(160, 160, kernel_size=3, stride=1, padding=0), nn.BatchNorm1d(160), nn.ReLU(True)) self.avepooling = nn.AvgPool1d(2, stride=1) self.maxpooling = nn.MaxPool1d(5, stride=1) self.dropout = nn.Dropout(p=0.5) self.fc = nn.Sequential(nn.Linear(320, 5), nn.Softmax(dim=0)) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.maxpooling(x) x = self.conv3(x) x = self.conv4(x) x = self.avepooling(x) x = x.reshape(320) x = self.dropout(x) # x = x.view(x.size(0), -1) x = self.fc(x) return x def train_model(self, data, batch, learning_rate, num_epoches, save=True): '''训练模型并保存''' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') dataset = Classification_Dataloader(data) train_dataset = DataLoader(dataset, batch_size=batch, shuffle=True, collate_fn=classification_collate) model = Classification().to(device) model.train(mode=True) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) total_step = len(train_dataset) for epoch in range(num_epoches): for i, hands in enumerate(train_dataset): hand, label = hands hand = hand.to(device) label = label.to(device) optimizer.zero_grad() outputs = model(hand) outputs = outputs.unsqueeze(dim=0) loss = criterion(outputs, label) loss.backward() optimizer.step() if (i + 1) % 50 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss:{:.4f}'.format(epoch + 1, num_epoches, i + 1, total_step, loss.item())) print('outputs:{}'.format(outputs.tolist())) if i+1 == 100: b=1 if save: # summary(model, (2, 5, 42)) torch.save(model.state_dict(), 'num_{}_batch_{}_lr_{}_ep_{}.pth'.format(1, batch, learning_rate, num_epoches)) def predict(self, hand, file): '''加载模型进行推理''' device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') hands = torch.tensor(hand).reshape((10, 14, 2)) hands = torch.split(hands, 1, dim=-1) hands = torch.stack((torch.squeeze(hands[0]), torch.squeeze(hands[1])), dim=0) # hands = hands.permute(0, 2, 1) # hands = hands.reshape((1, 2, 5, 42)) hands = hands.to(device) model = Classification().to(device) model.load_state_dict(torch.load(file,map_location='cpu')) model.eval() result = model(hands) return result # # troch.nn.RNN(input_size,hidden_size,num_layers) # rnn = nn.RNN(10, 20, 2) # # input1 = (L,N,H) tensor containing input features where H =input_size and L represents a sequence length. # input = torch.randn(5, 3, 10) # # input2 = (S,N,H) tensor containing the initial hidden state for each element in the batch. H=hidden_size Defaults to zero if not provided. where S=num_layers∗num_directions If the RNN is bidirectional, num_directions should be 2, else it should be 1. # h0 = torch.randn(2, 3, 20) # # output1 = (L,N,H) where H = num_directions * hidden_size # # output2 = (S,N,H) tensor containing the next hidden state for each element in the batch # output, hn = rnn(input, h0) # a = 1
0.844922
0.604516
import random import pandas as pd import io import json from dateutil import parser from collections import OrderedDict import time import csv import difflib import matplotlib import numpy as np import matplotlib.pyplot as plt import os import sys, traceback from matplotlib.legend_handler import HandlerLine2D import graphlab as gl import argparse import logging import ConfigParser import configparser from utils import general_utils import shutil from termcolor import colored import matplotlib.pyplot as plt from experiments import experiment_utils import math import powerlaw def h1_h2(df_checkins): results = OrderedDict({}) N = float(sum(df_checkins.R)) n = float(len(df_checkins.R)) # lat_sign = np.sign(np.average(df_checkins.venue_lat)) # long_sign = np.sign(np.average(df_checkins.venue_long)) # df_checkins.venue_lat = np.abs(df_checkins.venue_lat) # df_checkins.venue_long = np.abs(df_checkins.venue_long) lat_sum = 1 / N * sum(df_checkins.apply(lambda x: x.R * x.venue_lat, axis=1)) lat_squared_diff = 1 / N * sum(df_checkins.apply(lambda x: pow((x.R * x.venue_lat) - lat_sum, 2), axis=1)) h1 = 1.06 * pow(n, -.2) * math.sqrt(lat_squared_diff) long_sum = 1 / N * sum(df_checkins.apply(lambda x: x.R * x.venue_long, axis=1)) long_squared_diff = 1 / N * sum(df_checkins.apply(lambda x: pow((x.R * x.venue_long) - long_sum, 2), axis=1)) h2 = 1.06 * pow(n, -.2) * math.sqrt(long_squared_diff) results["h1"] = h1 results["h2"] = h2 return pd.Series(results) def kh(l, li, h1, h2): lat = pow(l.venue_lat - li.venue_lat,2) / (2 * pow(h1,2)) lon = pow(l.venue_long - li.venue_long,2) / (2 * pow(h2,2)) res = 1 / (2 * math.pi * h1 * h2) * math.exp(-lat-lon) assert res > 0 return res def fgeo(l, N, df_checkins, h1, h2): s = sum(df_checkins.apply(lambda li: li.R * kh(l, li, h1, h2), axis=1)) res = (1.0/N) * s assert res > 0 return res def g(fgeo_li): return np.power(np.prod(fgeo_li), 1.0/len(fgeo_li)) + .00000001 def fgeo_group(df_checkins): df_checkins["fgeo"] = df_checkins.apply(lambda l: fgeo(l, l.N, df_checkins, l.h1, l.h2), axis=1) return df_checkins def h(checkin, alpha): return pow(pow(checkin["g"],-1) * checkin["fgeo"], -alpha) def khh(l, li, h1, h2, hi): lat = pow(l.venue_lat - li.venue_lat,2) / (2 * pow(h1,2) * pow(hi,2)) lon = pow(l.venue_long - li.venue_long,2) / (2 * pow(h2,2) * pow(hi,2)) return 1 / (2 * math.pi * h1 * h2 * pow(h1,2)) * math.exp(-lat-lon) def main_fgeo(l, df_checkins): N = df_checkins.head(1).N.values[0] s = sum(df_checkins.apply(lambda li: li.R * khh(l, li, li.h1, li.h2, li.hi), axis=1)) return (1.0/N) * s class Geo: """ This class models the Geo part of GeoSoCa """ def __init__(self, data_dic, using_key, alpha): assert using_key in ["user_id", "group_id"], "The key should be either user_id or group_id" self.using_key = using_key self.alpha = alpha self.df_checkins_train = data_dic["train"] self.df_checkins_test = data_dic["test"] self.df_venues_categories = data_dic["df_venues_categories"] self.df_venues = data_dic["df_venues"] self.df_venues_content = data_dic["df_venues_content"] self.df_checkin_group = data_dic["df_checkin_group"] self.df_checkins = data_dic["df_checkins"] self.df_all_groups = data_dic["df_all_groups"] self.df_users = data_dic["df_users"] self.rul = None self.df_fgeo = None def fit(self): # Step 0: Init step rul = self.df_checkins_train.groupby([self.using_key, "venue_id"]).count()[["checkin_id"]].reset_index() rul = rul.merge(self.df_venues[["venue_id", "venue_lat", "venue_long"]], on="venue_id") rul = rul.rename(columns={"checkin_id": "R"}) df_h1h2 = rul.groupby(self.using_key).apply(h1_h2) df_h1h2 = df_h1h2.reset_index().drop_duplicates() rul = rul.merge(df_h1h2, on=self.using_key) df_n = rul.groupby(self.using_key).sum()[["R"]].reset_index().rename(columns={"R": "N"}) rul = rul.merge(df_n, on=self.using_key) self.rul = rul # Step 1: df_fgeo = self.rul.query("h1 != 0").groupby(self.using_key).apply(fgeo_group) # Step 2 # Compute G df_g = pd.DataFrame(df_fgeo.groupby(self.using_key)["fgeo"].aggregate(lambda x: g(x))).reset_index() df_g = df_g.rename(columns={"fgeo": "g"}) df_fgeo = df_fgeo.merge(df_g, on="user_id") # Compute H alpha = .5 df_fgeo["hi"] = df_fgeo.apply(lambda x: h(x, alpha), axis=1) self.df_fgeo = df_fgeo def score_sample(self, key, df_candidates): assert not self.rul is None and not self.df_fgeo is None, "Before scoring use the fit() method." # Compute Geo df_fgeo_users = self.df_fgeo.set_index(self.using_key) df_fgeo_user = df_fgeo_users.loc[key] df_candidates["geo"] = df_candidates.apply(lambda l: main_fgeo(l, df_fgeo_user), axis=1) return df_candidates
experiments/models/geo.py
import random import pandas as pd import io import json from dateutil import parser from collections import OrderedDict import time import csv import difflib import matplotlib import numpy as np import matplotlib.pyplot as plt import os import sys, traceback from matplotlib.legend_handler import HandlerLine2D import graphlab as gl import argparse import logging import ConfigParser import configparser from utils import general_utils import shutil from termcolor import colored import matplotlib.pyplot as plt from experiments import experiment_utils import math import powerlaw def h1_h2(df_checkins): results = OrderedDict({}) N = float(sum(df_checkins.R)) n = float(len(df_checkins.R)) # lat_sign = np.sign(np.average(df_checkins.venue_lat)) # long_sign = np.sign(np.average(df_checkins.venue_long)) # df_checkins.venue_lat = np.abs(df_checkins.venue_lat) # df_checkins.venue_long = np.abs(df_checkins.venue_long) lat_sum = 1 / N * sum(df_checkins.apply(lambda x: x.R * x.venue_lat, axis=1)) lat_squared_diff = 1 / N * sum(df_checkins.apply(lambda x: pow((x.R * x.venue_lat) - lat_sum, 2), axis=1)) h1 = 1.06 * pow(n, -.2) * math.sqrt(lat_squared_diff) long_sum = 1 / N * sum(df_checkins.apply(lambda x: x.R * x.venue_long, axis=1)) long_squared_diff = 1 / N * sum(df_checkins.apply(lambda x: pow((x.R * x.venue_long) - long_sum, 2), axis=1)) h2 = 1.06 * pow(n, -.2) * math.sqrt(long_squared_diff) results["h1"] = h1 results["h2"] = h2 return pd.Series(results) def kh(l, li, h1, h2): lat = pow(l.venue_lat - li.venue_lat,2) / (2 * pow(h1,2)) lon = pow(l.venue_long - li.venue_long,2) / (2 * pow(h2,2)) res = 1 / (2 * math.pi * h1 * h2) * math.exp(-lat-lon) assert res > 0 return res def fgeo(l, N, df_checkins, h1, h2): s = sum(df_checkins.apply(lambda li: li.R * kh(l, li, h1, h2), axis=1)) res = (1.0/N) * s assert res > 0 return res def g(fgeo_li): return np.power(np.prod(fgeo_li), 1.0/len(fgeo_li)) + .00000001 def fgeo_group(df_checkins): df_checkins["fgeo"] = df_checkins.apply(lambda l: fgeo(l, l.N, df_checkins, l.h1, l.h2), axis=1) return df_checkins def h(checkin, alpha): return pow(pow(checkin["g"],-1) * checkin["fgeo"], -alpha) def khh(l, li, h1, h2, hi): lat = pow(l.venue_lat - li.venue_lat,2) / (2 * pow(h1,2) * pow(hi,2)) lon = pow(l.venue_long - li.venue_long,2) / (2 * pow(h2,2) * pow(hi,2)) return 1 / (2 * math.pi * h1 * h2 * pow(h1,2)) * math.exp(-lat-lon) def main_fgeo(l, df_checkins): N = df_checkins.head(1).N.values[0] s = sum(df_checkins.apply(lambda li: li.R * khh(l, li, li.h1, li.h2, li.hi), axis=1)) return (1.0/N) * s class Geo: """ This class models the Geo part of GeoSoCa """ def __init__(self, data_dic, using_key, alpha): assert using_key in ["user_id", "group_id"], "The key should be either user_id or group_id" self.using_key = using_key self.alpha = alpha self.df_checkins_train = data_dic["train"] self.df_checkins_test = data_dic["test"] self.df_venues_categories = data_dic["df_venues_categories"] self.df_venues = data_dic["df_venues"] self.df_venues_content = data_dic["df_venues_content"] self.df_checkin_group = data_dic["df_checkin_group"] self.df_checkins = data_dic["df_checkins"] self.df_all_groups = data_dic["df_all_groups"] self.df_users = data_dic["df_users"] self.rul = None self.df_fgeo = None def fit(self): # Step 0: Init step rul = self.df_checkins_train.groupby([self.using_key, "venue_id"]).count()[["checkin_id"]].reset_index() rul = rul.merge(self.df_venues[["venue_id", "venue_lat", "venue_long"]], on="venue_id") rul = rul.rename(columns={"checkin_id": "R"}) df_h1h2 = rul.groupby(self.using_key).apply(h1_h2) df_h1h2 = df_h1h2.reset_index().drop_duplicates() rul = rul.merge(df_h1h2, on=self.using_key) df_n = rul.groupby(self.using_key).sum()[["R"]].reset_index().rename(columns={"R": "N"}) rul = rul.merge(df_n, on=self.using_key) self.rul = rul # Step 1: df_fgeo = self.rul.query("h1 != 0").groupby(self.using_key).apply(fgeo_group) # Step 2 # Compute G df_g = pd.DataFrame(df_fgeo.groupby(self.using_key)["fgeo"].aggregate(lambda x: g(x))).reset_index() df_g = df_g.rename(columns={"fgeo": "g"}) df_fgeo = df_fgeo.merge(df_g, on="user_id") # Compute H alpha = .5 df_fgeo["hi"] = df_fgeo.apply(lambda x: h(x, alpha), axis=1) self.df_fgeo = df_fgeo def score_sample(self, key, df_candidates): assert not self.rul is None and not self.df_fgeo is None, "Before scoring use the fit() method." # Compute Geo df_fgeo_users = self.df_fgeo.set_index(self.using_key) df_fgeo_user = df_fgeo_users.loc[key] df_candidates["geo"] = df_candidates.apply(lambda l: main_fgeo(l, df_fgeo_user), axis=1) return df_candidates
0.455199
0.346928
import argparse import tensorflow as tf import tensorrt as trt import uff import graphsurgeon as gs import converter_util def setup_args(parser): parser.add_argument("--input", "-i", help="Path to input file", required=True, type=str) parser.add_argument("--input_dims", "-id", help="Dimensions of input tensor", type=int, nargs='+') parser.add_argument("--output_dir", "-o", help="Output dir and filename.", default="./converted_model") def add_tensorrt_arguments(parser): parser.add_argument("--debug", "-d", help="Debug flag", action='store_true') parser.add_argument("--no_cuda", help="Disables script components that require the CUDA runtime.", action='store_true') def add_plugin(graph, input_dims, graph_chars=None): graph_def = graph.as_graph_def() if graph_chars is None: graph_chars = converter_util.GraphCharacteristics(graph_def) num_classes = converter_util.get_num_classes(graph_def, graph_chars=graph_chars) input_order = converter_util.get_NMS_input_order(graph_def, "Postprocessor", graph_chars=graph_chars) if any(x == -1 for x in input_order): print("NMS input order error: {} Aborting".format(input_order)) exit(1) if args.debug: print("Detected number of classes: ", num_classes) print("Detected NMS input order: ", input_order) assert_nodes = graph.find_nodes_by_op("Assert") graph.remove(assert_nodes, remove_exclusive_dependencies=True) identity_nodes = graph.find_nodes_by_op("Identity") graph.forward_inputs(identity_nodes) Input = gs.create_plugin_node( name="Input", op="Placeholder", shape=(1,) + input_dims ) # TODO: Consider automation of parameters PriorBox = gs.create_plugin_node( name="MultipleGridAnchorGenerator", op="GridAnchor_TRT", minSize=0.2, maxSize=0.95, aspectRatios=[1.0, 2.0, 0.5, 3.0, 0.33], variance=[0.1, 0.1, 0.2, 0.2], featureMapShapes=[19, 10, 5, 3, 2, 1], numLayers=6 ) NMS = gs.create_plugin_node( name="NMS", op="NMS_TRT", shareLocation=1, varianceEncodedInTarget=0, backgroundLabelId=0, confidenceThreshold=0.3, nmsThreshold=0.6, topK=100, keepTopK=100, numClasses=num_classes, inputOrder=input_order, confSigmoid=1, isNormalized=1 ) concat_box_loc = gs.create_plugin_node( "concat_box_loc", op="FlattenConcat_TRT", axis=1, ignoreBatch=0 ) concat_box_conf = gs.create_plugin_node( "concat_box_conf", op="FlattenConcat_TRT", axis=1, ignoreBatch=0 ) concat_priorbox = gs.create_node( "concat_priorbox", op="ConcatV2", axis=2 ) namespace_map = { "MultipleGridAnchorGenerator": PriorBox, "Preprocessor": Input, "ToFloat": Input, "Cast": Input, "image_tensor": Input, "Postprocessor": NMS, "concat": concat_box_loc, "concat_1": concat_box_conf, "Concatenate": concat_priorbox, "MultipleGridAnchorGenerator/Concatenate": concat_priorbox, "SecondStagePostprocessor": NMS } graph.collapse_namespaces(namespace_map) graph.remove(graph.graph_outputs, remove_exclusive_dependencies=False) if graph.find_nodes_by_op("NMS_TRT"): if "Input" in graph.find_nodes_by_op("NMS_TRT")[0].input: graph.find_nodes_by_op("NMS_TRT")[0].input.remove("Input") if "image_tensor:0" in graph.find_nodes_by_name("Input")[0].input: graph.find_nodes_by_name("Input")[0].input.remove("image_tensor:0") if "image_tensor" in graph.find_nodes_by_name("Input")[0].input: graph.find_nodes_by_name("Input")[0].input.remove("image_tensor") if graph.find_nodes_by_name("ToFloat_3"): if "image_tensor:0" in graph.find_nodes_by_name("ToFloat_3")[0].input: graph.find_nodes_by_name("ToFloat_3")[0].input.remove("image_tensor:0") return graph def convert_to_tensorrt(args, input_dims, graph_chars=None): TRT_LOGGER = trt.Logger(trt.Logger.INFO) trt.init_libnvinfer_plugins(TRT_LOGGER, '') input_dims_corrected = (input_dims[3], input_dims[1], input_dims[2]) graph = add_plugin(gs.DynamicGraph(args.input), input_dims_corrected, graph_chars=graph_chars) print(graph.find_nodes_by_name("image_tensor")) try: uff.from_tensorflow( graph.as_graph_def(), output_nodes=['NMS'], output_filename=(args.output_dir + ".uff"), text=args.debug, write_preprocessed=args.debug, debug_mode=args.debug) except TypeError as e: if e.__str__() == "Cannot convert value 0 to a TensorFlow DType.": raise EnvironmentError("Please modify your graphsurgeon package according to the following:\n" "https://github.com/AastaNV/TRT_object_detection#update-graphsurgeon-converter") if args.no_cuda: exit(0) with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network, trt.UffParser() as parser: builder.max_workspace_size = 1 << 28 builder.max_batch_size = 1 builder.fp16_mode = True parser.register_input('Input', input_dims_corrected) parser.register_output('MarkOutput_0') parser.parse(args.output_dir + ".uff", network) engine = builder.build_cuda_engine(network) buf = engine.serialize() with open(args.output_dir + '_tensorrt.bin', 'wb') as f: f.write(buf) if __name__ == '__main__': parser = argparse.ArgumentParser() setup_args(parser) add_tensorrt_arguments(parser) args = parser.parse_args() with tf.compat.v1.gfile.GFile(args.input, "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) # Get graph data graph_chars = converter_util.GraphCharacteristics(graph_def) # Set input dimensions input_dims = converter_util.get_input_dims(args, graph_chars.input_nodes[0]) convert_to_tensorrt(args, input_dims, graph_chars=graph_chars)
tensorrt_converter.py
import argparse import tensorflow as tf import tensorrt as trt import uff import graphsurgeon as gs import converter_util def setup_args(parser): parser.add_argument("--input", "-i", help="Path to input file", required=True, type=str) parser.add_argument("--input_dims", "-id", help="Dimensions of input tensor", type=int, nargs='+') parser.add_argument("--output_dir", "-o", help="Output dir and filename.", default="./converted_model") def add_tensorrt_arguments(parser): parser.add_argument("--debug", "-d", help="Debug flag", action='store_true') parser.add_argument("--no_cuda", help="Disables script components that require the CUDA runtime.", action='store_true') def add_plugin(graph, input_dims, graph_chars=None): graph_def = graph.as_graph_def() if graph_chars is None: graph_chars = converter_util.GraphCharacteristics(graph_def) num_classes = converter_util.get_num_classes(graph_def, graph_chars=graph_chars) input_order = converter_util.get_NMS_input_order(graph_def, "Postprocessor", graph_chars=graph_chars) if any(x == -1 for x in input_order): print("NMS input order error: {} Aborting".format(input_order)) exit(1) if args.debug: print("Detected number of classes: ", num_classes) print("Detected NMS input order: ", input_order) assert_nodes = graph.find_nodes_by_op("Assert") graph.remove(assert_nodes, remove_exclusive_dependencies=True) identity_nodes = graph.find_nodes_by_op("Identity") graph.forward_inputs(identity_nodes) Input = gs.create_plugin_node( name="Input", op="Placeholder", shape=(1,) + input_dims ) # TODO: Consider automation of parameters PriorBox = gs.create_plugin_node( name="MultipleGridAnchorGenerator", op="GridAnchor_TRT", minSize=0.2, maxSize=0.95, aspectRatios=[1.0, 2.0, 0.5, 3.0, 0.33], variance=[0.1, 0.1, 0.2, 0.2], featureMapShapes=[19, 10, 5, 3, 2, 1], numLayers=6 ) NMS = gs.create_plugin_node( name="NMS", op="NMS_TRT", shareLocation=1, varianceEncodedInTarget=0, backgroundLabelId=0, confidenceThreshold=0.3, nmsThreshold=0.6, topK=100, keepTopK=100, numClasses=num_classes, inputOrder=input_order, confSigmoid=1, isNormalized=1 ) concat_box_loc = gs.create_plugin_node( "concat_box_loc", op="FlattenConcat_TRT", axis=1, ignoreBatch=0 ) concat_box_conf = gs.create_plugin_node( "concat_box_conf", op="FlattenConcat_TRT", axis=1, ignoreBatch=0 ) concat_priorbox = gs.create_node( "concat_priorbox", op="ConcatV2", axis=2 ) namespace_map = { "MultipleGridAnchorGenerator": PriorBox, "Preprocessor": Input, "ToFloat": Input, "Cast": Input, "image_tensor": Input, "Postprocessor": NMS, "concat": concat_box_loc, "concat_1": concat_box_conf, "Concatenate": concat_priorbox, "MultipleGridAnchorGenerator/Concatenate": concat_priorbox, "SecondStagePostprocessor": NMS } graph.collapse_namespaces(namespace_map) graph.remove(graph.graph_outputs, remove_exclusive_dependencies=False) if graph.find_nodes_by_op("NMS_TRT"): if "Input" in graph.find_nodes_by_op("NMS_TRT")[0].input: graph.find_nodes_by_op("NMS_TRT")[0].input.remove("Input") if "image_tensor:0" in graph.find_nodes_by_name("Input")[0].input: graph.find_nodes_by_name("Input")[0].input.remove("image_tensor:0") if "image_tensor" in graph.find_nodes_by_name("Input")[0].input: graph.find_nodes_by_name("Input")[0].input.remove("image_tensor") if graph.find_nodes_by_name("ToFloat_3"): if "image_tensor:0" in graph.find_nodes_by_name("ToFloat_3")[0].input: graph.find_nodes_by_name("ToFloat_3")[0].input.remove("image_tensor:0") return graph def convert_to_tensorrt(args, input_dims, graph_chars=None): TRT_LOGGER = trt.Logger(trt.Logger.INFO) trt.init_libnvinfer_plugins(TRT_LOGGER, '') input_dims_corrected = (input_dims[3], input_dims[1], input_dims[2]) graph = add_plugin(gs.DynamicGraph(args.input), input_dims_corrected, graph_chars=graph_chars) print(graph.find_nodes_by_name("image_tensor")) try: uff.from_tensorflow( graph.as_graph_def(), output_nodes=['NMS'], output_filename=(args.output_dir + ".uff"), text=args.debug, write_preprocessed=args.debug, debug_mode=args.debug) except TypeError as e: if e.__str__() == "Cannot convert value 0 to a TensorFlow DType.": raise EnvironmentError("Please modify your graphsurgeon package according to the following:\n" "https://github.com/AastaNV/TRT_object_detection#update-graphsurgeon-converter") if args.no_cuda: exit(0) with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network, trt.UffParser() as parser: builder.max_workspace_size = 1 << 28 builder.max_batch_size = 1 builder.fp16_mode = True parser.register_input('Input', input_dims_corrected) parser.register_output('MarkOutput_0') parser.parse(args.output_dir + ".uff", network) engine = builder.build_cuda_engine(network) buf = engine.serialize() with open(args.output_dir + '_tensorrt.bin', 'wb') as f: f.write(buf) if __name__ == '__main__': parser = argparse.ArgumentParser() setup_args(parser) add_tensorrt_arguments(parser) args = parser.parse_args() with tf.compat.v1.gfile.GFile(args.input, "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) # Get graph data graph_chars = converter_util.GraphCharacteristics(graph_def) # Set input dimensions input_dims = converter_util.get_input_dims(args, graph_chars.input_nodes[0]) convert_to_tensorrt(args, input_dims, graph_chars=graph_chars)
0.31363
0.314524
from pygroupsig.common_build import ffibuilder ffibuilder.cdef(""" typedef struct { uint8_t scheme; void *sig; } groupsig_signature_t; """) ffibuilder.cdef(""" typedef groupsig_signature_t* (*groupsig_signature_init_f)(void); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_free_f)(groupsig_signature_t *signature); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_copy_f)( groupsig_signature_t *dst, groupsig_signature_t *src); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_get_size_f)( groupsig_signature_t *sig); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_export_f)( unsigned char **bytes, uint32_t *size, groupsig_signature_t *signature); """) ffibuilder.cdef(""" typedef groupsig_signature_t* (*groupsig_signature_import_f)( unsigned char *source, uint32_t size); """) ffibuilder.cdef(""" typedef char* (*groupsig_signature_to_string_f)( groupsig_signature_t *signature); """) ffibuilder.cdef(""" typedef struct { uint8_t scheme; groupsig_signature_init_f init; groupsig_signature_free_f free; groupsig_signature_copy_f copy; groupsig_signature_get_size_f get_size; groupsig_signature_export_f gexport; groupsig_signature_import_f gimport; groupsig_signature_to_string_f to_string; } groupsig_signature_handle_t; """) ffibuilder.cdef(""" const groupsig_signature_handle_t* groupsig_signature_handle_from_code(uint8_t code); """) ffibuilder.cdef(""" groupsig_signature_t* groupsig_signature_init(uint8_t code) ;""") ffibuilder.cdef(""" int groupsig_signature_free(groupsig_signature_t *sig); """) ffibuilder.cdef(""" int groupsig_signature_copy( groupsig_signature_t *dst, groupsig_signature_t *src); """) ffibuilder.cdef(""" int groupsig_signature_get_size( groupsig_signature_t *sig); """) ffibuilder.cdef(""" int groupsig_signature_export( unsigned char **bytes, uint32_t *size, groupsig_signature_t *sig); """) ffibuilder.cdef(""" groupsig_signature_t* groupsig_signature_import( uint8_t code, unsigned char *source, uint32_t size); """) ffibuilder.cdef(""" char* groupsig_signature_to_string(groupsig_signature_t *sig); """)
src/wrappers/python/pygroupsig/signature_build.py
from pygroupsig.common_build import ffibuilder ffibuilder.cdef(""" typedef struct { uint8_t scheme; void *sig; } groupsig_signature_t; """) ffibuilder.cdef(""" typedef groupsig_signature_t* (*groupsig_signature_init_f)(void); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_free_f)(groupsig_signature_t *signature); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_copy_f)( groupsig_signature_t *dst, groupsig_signature_t *src); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_get_size_f)( groupsig_signature_t *sig); """) ffibuilder.cdef(""" typedef int (*groupsig_signature_export_f)( unsigned char **bytes, uint32_t *size, groupsig_signature_t *signature); """) ffibuilder.cdef(""" typedef groupsig_signature_t* (*groupsig_signature_import_f)( unsigned char *source, uint32_t size); """) ffibuilder.cdef(""" typedef char* (*groupsig_signature_to_string_f)( groupsig_signature_t *signature); """) ffibuilder.cdef(""" typedef struct { uint8_t scheme; groupsig_signature_init_f init; groupsig_signature_free_f free; groupsig_signature_copy_f copy; groupsig_signature_get_size_f get_size; groupsig_signature_export_f gexport; groupsig_signature_import_f gimport; groupsig_signature_to_string_f to_string; } groupsig_signature_handle_t; """) ffibuilder.cdef(""" const groupsig_signature_handle_t* groupsig_signature_handle_from_code(uint8_t code); """) ffibuilder.cdef(""" groupsig_signature_t* groupsig_signature_init(uint8_t code) ;""") ffibuilder.cdef(""" int groupsig_signature_free(groupsig_signature_t *sig); """) ffibuilder.cdef(""" int groupsig_signature_copy( groupsig_signature_t *dst, groupsig_signature_t *src); """) ffibuilder.cdef(""" int groupsig_signature_get_size( groupsig_signature_t *sig); """) ffibuilder.cdef(""" int groupsig_signature_export( unsigned char **bytes, uint32_t *size, groupsig_signature_t *sig); """) ffibuilder.cdef(""" groupsig_signature_t* groupsig_signature_import( uint8_t code, unsigned char *source, uint32_t size); """) ffibuilder.cdef(""" char* groupsig_signature_to_string(groupsig_signature_t *sig); """)
0.541894
0.051702
import pandas as pd import logging from dowhy.do_why import CausalModel import dowhy.do_samplers as do_samplers class CausalDataFrame(pd.DataFrame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._causal_model = None self._sampler = None self._identified_estimand = None def attach_causal_model(self, model): self._causal_model = model def reset(self): self._causal_model = None self._identified_estimand = None self._sampler = None @pd.api.extensions.register_dataframe_accessor("causal") class CausalAccessor(object): def __init__(self, pandas_obj): self._obj = pandas_obj def do(self, x, method=None, num_cores=1, variable_types={}, outcome=None, params=None, dot_graph=None, common_causes=None, instruments=None, estimand_type='ate', proceed_when_unidentifiable=False, keep_original_treatment=False, use_previous_sampler=False): if not method: raise Exception("You must specify a do sampling method.") if not self._obj._causal_model or not use_previous_sampler: self._obj._causal_model = CausalModel(self._obj, [xi for xi in x.keys()][0], outcome, graph=dot_graph, common_causes=common_causes, instruments=instruments, estimand_type=estimand_type, proceed_when_unidentifiable=proceed_when_unidentifiable) self._obj._identified_estimand = self._obj._causal_model.identify_effect() do_sampler_class = do_samplers.get_class_object(method + "_sampler") if not self._obj._sampler or not use_previous_sampler: self._obj._sampler = do_sampler_class(self._obj, self._obj._identified_estimand, self._obj._causal_model._treatment, self._obj._causal_model._outcome, params=params, variable_types=variable_types, num_cores=num_cores, causal_model=self._obj._causal_model, keep_original_treatment=keep_original_treatment) return self._obj._sampler.do_sample(x)
dowhy/api/causal_data_frame.py
import pandas as pd import logging from dowhy.do_why import CausalModel import dowhy.do_samplers as do_samplers class CausalDataFrame(pd.DataFrame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._causal_model = None self._sampler = None self._identified_estimand = None def attach_causal_model(self, model): self._causal_model = model def reset(self): self._causal_model = None self._identified_estimand = None self._sampler = None @pd.api.extensions.register_dataframe_accessor("causal") class CausalAccessor(object): def __init__(self, pandas_obj): self._obj = pandas_obj def do(self, x, method=None, num_cores=1, variable_types={}, outcome=None, params=None, dot_graph=None, common_causes=None, instruments=None, estimand_type='ate', proceed_when_unidentifiable=False, keep_original_treatment=False, use_previous_sampler=False): if not method: raise Exception("You must specify a do sampling method.") if not self._obj._causal_model or not use_previous_sampler: self._obj._causal_model = CausalModel(self._obj, [xi for xi in x.keys()][0], outcome, graph=dot_graph, common_causes=common_causes, instruments=instruments, estimand_type=estimand_type, proceed_when_unidentifiable=proceed_when_unidentifiable) self._obj._identified_estimand = self._obj._causal_model.identify_effect() do_sampler_class = do_samplers.get_class_object(method + "_sampler") if not self._obj._sampler or not use_previous_sampler: self._obj._sampler = do_sampler_class(self._obj, self._obj._identified_estimand, self._obj._causal_model._treatment, self._obj._causal_model._outcome, params=params, variable_types=variable_types, num_cores=num_cores, causal_model=self._obj._causal_model, keep_original_treatment=keep_original_treatment) return self._obj._sampler.do_sample(x)
0.557123
0.092319
from rest_framework.views import APIView from rest_framework.exceptions import APIException, NotFound from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from returntoclinicstation.models import * from datetime import * from django.core import serializers from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound import numbers from common.decorators import * import json import sys class ReturnToClinicStationView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def stateToDb(self, state): ret = None if state == "created": ret = '1' elif state == "scheduled_dest": ret = '2' elif state == "checked_out_dest": ret = '3' elif state == "scheduled_return": ret = '4' return ret def dbToState(self, db): ret = None if db == '1': ret = "created" elif db == '2': ret = "scheduled_dest" elif db == '3': ret = "checked_out_dest" elif db == '4': ret = "scheduled_return" return ret @log_request def get(self, request, returntoclinicstation_id=None, format=None): notFound = False badRequest = False returntoclinicstation = None if returntoclinicstation_id: try: returntoclinicstation = ReturnToClinicStation.objects.get(id = returntoclinicstation_id) except: returntoclinicstation = None else: kwargs = {} try: clinicid = request.GET.get('clinic', '') if clinicid != '': clinicid = int(clinicid) try: aClinic = Clinic.objects.get(id=clinicid) kwargs["clinic"] = aClinic except: notFound = True except: pass try: patientid = request.GET.get('patient', '') if patientid != '': patientid = int(patientid) try: aPatient = Patient.objects.get(id=patientid) kwargs["patient"] = aPatient except: notFound = True except: pass try: stationid = request.GET.get('station', '') if stationid != '': stationid = int(stationid) try: aStation = Station.objects.get(id=stationid) kwargs["station"] = aStation except: notFound = True except: pass try: requestingclinicstationid = request.GET.get('requestingclinicstation', '') if requestingclinicstationid != '': requestingclinicstationid = int(requestingclinicstationid) try: aRequestingClinicStation = ClinicStation.objects.get(id=requestingclinicstationid) kwargs["requestingclinicstation"] = aRequestingClinicStation except: notFound = True except: pass try: state = request.GET.get('state', '') if state != '': stateDb = self.stateToDb(state) if stateDb == None: badRequest = True else: kwargs["state"] = stateDb except: pass if (not badRequest) and (not notFound) and (len(kwargs) == 0): returntoclinicstation = ReturnToClinicStation.objects.all() elif not badRequest and not notFound: try: returntoclinicstation = ReturnToClinicStation.objects.filter(**kwargs) except: returntoclinicstation = None if notFound or not returntoclinicstation: raise NotFound elif badRequest: raise BadRequest elif returntoclinicstation_id: ret = {} x = returntoclinicstation ret["clinic"] = x.clinic.id ret["patient"] = x.patient.id ret["station"] = x.station.id ret["requestingclinicstation"] = x.requestingclinicstation.id ret["createtime"] = x.createtime ret["statechangetime"] = x.statechangetime ret["state"] = self.dbToState(x.state) ret["id"] = x.id else: ret = [] for x in returntoclinicstation: m = {} m["id"] = x.id ret.append(m) return Response(ret) @log_request def put(self, request, id=None, format=None): badRequest = False implError = False notFound = False state = None data = json.loads(request.body) try: state = data["state"] except: pass if state == None: badRequest = True stateDb = self.stateToDb(state) if stateDb == None: badRequest = True if not badRequest: returntoclinicstation = None # see if the returntoclinicstation already exists try: returntoclinicstation = ReturnToClinicStation.objects.get(id=id) except: pass if not returntoclinicstation: notFound = True else: try: returntoclinicstation.state=stateDb returntoclinicstation.save() except: implError = True implMsg = sys.exc_info()[0] if badRequest: return HttpResponseBadRequest() if notFound: return HttpResponseNotFound() if implError: return HttpResponseServerError(implMsg) else: return Response({}) @log_request def post(self, request, format=None): badRequest = False notFound = False implError = False aClinic = None aPatient = None aStation = None aRequestingClinicStation = None state = None data = json.loads(request.body) try: clinic = data["clinic"] except: badRequest = True try: patient = data["patient"] except: badRequest = True try: station = data["station"] except: badRequest = True try: requestingclinicstation = data["requestingclinicstation"] except: badRequest = True if not badRequest: try: aClinic = Clinic.objects.get(id=clinic) except: aClinic = None try: aStation = Station.objects.get(id=station) except: aStation = None try: aRequestingClinicStation = ClinicStation.objects.get(id=requestingclinicstation) except: aRequestingClinicStation = None try: aPatient = Patient.objects.get(id=patient) except: aPatient = None if not aClinic or not aStation or not aPatient or not aRequestingClinicStation: notFound = True if not badRequest and not notFound: returntoclinicstation = None # see if the returntoclinicstation already exists try: returntoclinicstation = ReturnToClinicStation.objects.filter(clinic=aClinic, patient=aPatient, station=aStation, requestingclinicstation=aRequestingClinicStation) if not returntoclinicstation or len(returntoclinicstation) == 0: returntoclinicstation = None except: implMsg = "ReturnToClinicStation.objects.filter {} {}".format(sys.exc_info()[0], data) implError = True if not returntoclinicstation: try: returntoclinicstation = ReturnToClinicStation(clinic=aClinic, patient=aPatient, station=aStation, requestingclinicstation=aRequestingClinicStation, state='1') if returntoclinicstation: returntoclinicstation.save() else: implMsg = "Unable to create returntoclinicstation" implError = True except: implMsg = "ReturnToClinicStation create {} {}".format(sys.exc_info()[0], data) implError = True if badRequest: return HttpResponseBadRequest() if notFound: return HttpResponseNotFound() if implError: return HttpResponseServerError(implMsg) else: return Response({'id': returntoclinicstation.id}) @log_request def delete(self, request, returntoclinicstation_id=None, format=None): returntoclinicstation = None # see if the returntoclinicstation resource exists try: returntoclinicstation = ReturnToClinicStation.objects.get(id=returntoclinicstation_id) except: returntoclinicstation = None if not returntoclinicstation: raise NotFound else: returntoclinicstation.delete() return Response({})
returntoclinicstation/views.py
from rest_framework.views import APIView from rest_framework.exceptions import APIException, NotFound from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from returntoclinicstation.models import * from datetime import * from django.core import serializers from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotFound import numbers from common.decorators import * import json import sys class ReturnToClinicStationView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def stateToDb(self, state): ret = None if state == "created": ret = '1' elif state == "scheduled_dest": ret = '2' elif state == "checked_out_dest": ret = '3' elif state == "scheduled_return": ret = '4' return ret def dbToState(self, db): ret = None if db == '1': ret = "created" elif db == '2': ret = "scheduled_dest" elif db == '3': ret = "checked_out_dest" elif db == '4': ret = "scheduled_return" return ret @log_request def get(self, request, returntoclinicstation_id=None, format=None): notFound = False badRequest = False returntoclinicstation = None if returntoclinicstation_id: try: returntoclinicstation = ReturnToClinicStation.objects.get(id = returntoclinicstation_id) except: returntoclinicstation = None else: kwargs = {} try: clinicid = request.GET.get('clinic', '') if clinicid != '': clinicid = int(clinicid) try: aClinic = Clinic.objects.get(id=clinicid) kwargs["clinic"] = aClinic except: notFound = True except: pass try: patientid = request.GET.get('patient', '') if patientid != '': patientid = int(patientid) try: aPatient = Patient.objects.get(id=patientid) kwargs["patient"] = aPatient except: notFound = True except: pass try: stationid = request.GET.get('station', '') if stationid != '': stationid = int(stationid) try: aStation = Station.objects.get(id=stationid) kwargs["station"] = aStation except: notFound = True except: pass try: requestingclinicstationid = request.GET.get('requestingclinicstation', '') if requestingclinicstationid != '': requestingclinicstationid = int(requestingclinicstationid) try: aRequestingClinicStation = ClinicStation.objects.get(id=requestingclinicstationid) kwargs["requestingclinicstation"] = aRequestingClinicStation except: notFound = True except: pass try: state = request.GET.get('state', '') if state != '': stateDb = self.stateToDb(state) if stateDb == None: badRequest = True else: kwargs["state"] = stateDb except: pass if (not badRequest) and (not notFound) and (len(kwargs) == 0): returntoclinicstation = ReturnToClinicStation.objects.all() elif not badRequest and not notFound: try: returntoclinicstation = ReturnToClinicStation.objects.filter(**kwargs) except: returntoclinicstation = None if notFound or not returntoclinicstation: raise NotFound elif badRequest: raise BadRequest elif returntoclinicstation_id: ret = {} x = returntoclinicstation ret["clinic"] = x.clinic.id ret["patient"] = x.patient.id ret["station"] = x.station.id ret["requestingclinicstation"] = x.requestingclinicstation.id ret["createtime"] = x.createtime ret["statechangetime"] = x.statechangetime ret["state"] = self.dbToState(x.state) ret["id"] = x.id else: ret = [] for x in returntoclinicstation: m = {} m["id"] = x.id ret.append(m) return Response(ret) @log_request def put(self, request, id=None, format=None): badRequest = False implError = False notFound = False state = None data = json.loads(request.body) try: state = data["state"] except: pass if state == None: badRequest = True stateDb = self.stateToDb(state) if stateDb == None: badRequest = True if not badRequest: returntoclinicstation = None # see if the returntoclinicstation already exists try: returntoclinicstation = ReturnToClinicStation.objects.get(id=id) except: pass if not returntoclinicstation: notFound = True else: try: returntoclinicstation.state=stateDb returntoclinicstation.save() except: implError = True implMsg = sys.exc_info()[0] if badRequest: return HttpResponseBadRequest() if notFound: return HttpResponseNotFound() if implError: return HttpResponseServerError(implMsg) else: return Response({}) @log_request def post(self, request, format=None): badRequest = False notFound = False implError = False aClinic = None aPatient = None aStation = None aRequestingClinicStation = None state = None data = json.loads(request.body) try: clinic = data["clinic"] except: badRequest = True try: patient = data["patient"] except: badRequest = True try: station = data["station"] except: badRequest = True try: requestingclinicstation = data["requestingclinicstation"] except: badRequest = True if not badRequest: try: aClinic = Clinic.objects.get(id=clinic) except: aClinic = None try: aStation = Station.objects.get(id=station) except: aStation = None try: aRequestingClinicStation = ClinicStation.objects.get(id=requestingclinicstation) except: aRequestingClinicStation = None try: aPatient = Patient.objects.get(id=patient) except: aPatient = None if not aClinic or not aStation or not aPatient or not aRequestingClinicStation: notFound = True if not badRequest and not notFound: returntoclinicstation = None # see if the returntoclinicstation already exists try: returntoclinicstation = ReturnToClinicStation.objects.filter(clinic=aClinic, patient=aPatient, station=aStation, requestingclinicstation=aRequestingClinicStation) if not returntoclinicstation or len(returntoclinicstation) == 0: returntoclinicstation = None except: implMsg = "ReturnToClinicStation.objects.filter {} {}".format(sys.exc_info()[0], data) implError = True if not returntoclinicstation: try: returntoclinicstation = ReturnToClinicStation(clinic=aClinic, patient=aPatient, station=aStation, requestingclinicstation=aRequestingClinicStation, state='1') if returntoclinicstation: returntoclinicstation.save() else: implMsg = "Unable to create returntoclinicstation" implError = True except: implMsg = "ReturnToClinicStation create {} {}".format(sys.exc_info()[0], data) implError = True if badRequest: return HttpResponseBadRequest() if notFound: return HttpResponseNotFound() if implError: return HttpResponseServerError(implMsg) else: return Response({'id': returntoclinicstation.id}) @log_request def delete(self, request, returntoclinicstation_id=None, format=None): returntoclinicstation = None # see if the returntoclinicstation resource exists try: returntoclinicstation = ReturnToClinicStation.objects.get(id=returntoclinicstation_id) except: returntoclinicstation = None if not returntoclinicstation: raise NotFound else: returntoclinicstation.delete() return Response({})
0.344003
0.061621
import pytest import numpy as np from numpy.testing import assert_allclose import json import os import inspect # Importing auto_HU_NJ module from auto_HU_NJ import * # Current directory cur_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # Test input directory base_input_path = 'resources' def test_parse_BIM(): """ Testing the parse_BIM function. """ # Testing the ruleset for Hurricane-Prone Region (HPR) res = [] ref = [1, 0, 1, 0] for i in range(4): BIM_dir = os.path.join(cur_dir, base_input_path, 'BIM_Data', 'parse_BIM_test_' + str(i+1) + '.json') with open(BIM_dir) as f: BIM_input = json.load(f) BIM_output = parse_BIM(BIM_input['GI']) res.append(int(BIM_output['HPR'])) # Check assert_allclose(res, ref, atol=1e-5) # Testing the ruleset for Wind Borne Debris (WBD) res = [] ref = [0, 0, 0, 0, 1, 1, 1, 1] for i in range(8): BIM_dir = os.path.join(cur_dir, base_input_path, 'BIM_Data', 'parse_BIM_test_' + str(i+1) + '.json') with open(BIM_dir) as f: BIM_input = json.load(f) BIM_output = parse_BIM(BIM_input['GI']) res.append(int(BIM_output['WBD'])) # Check assert_allclose(res, ref, atol=1e-5) # Testing the ruleset for terrain res = [] ref = [3, 15, 35, 70, 3, 15, 35, 70] for i in range(8): BIM_dir = os.path.join(cur_dir, base_input_path, 'BIM_Data', 'parse_BIM_test_' + str(i+1) + '.json') with open(BIM_dir) as f: BIM_input = json.load(f) BIM_output = parse_BIM(BIM_input['GI']) res.append(int(BIM_output['terrain'])) # Check assert_allclose(res, ref, atol=1e-5) def test_building_class(): """ Testing the building class function. """ # Testing the ruleset for classifying Hazus building class res = [] ref_class = ['WSF', 'WMUH', 'SERB', 'SECB', 'SPMB', 'CERB', 'CECB', 'MSF', 'MERB', 'MECB', 'MLRI', 'MMUH', 'MLRM'] ref = np.ones(13) for i in range(13): data_dir = os.path.join(cur_dir, base_input_path, 'BuildingClass_Data', 'building_class_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = building_class(tmp) print(data_output) res.append(int(data_output == ref_class[i])) # Check assert_allclose(res, ref, atol=1e-5) def test_WSF_config(): """ Testing the WSF_config function. """ res = [] ref_class = ['WSF2_gab_0_8d_tnail_no', 'WSF2_gab_1_8d_tnail_no', 'WSF2_hip_1_8d_tnail_no', 'WSF2_hip_0_8d_tnail_no', '8s_strap_no', '8s_strap_no', '8s_tnail_no', '8s_strap_sup', '8d_strap_std', '8d_tnail_wkd', 'WSF1'] ref = np.ones(11) for i in range(11): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'wsf_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = WSF_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_WMUH_config(): """ Testing the WMUH_config function. """ res = [] ref_class = ['WMUH2_flt_spm_god_null', 'WMUH2_flt_spm_god_null', 'WMUH2_flt_spm_god_null', 'WMUH2_gab_null_null_1', 'WMUH2_hip_null_null_1', 'WMUH2_gab_null_null_0', 'WMUH2_hip_null_null_0', 'WMUH2_flt_spm_por_null', 'WMUH2_flt_bur_por_null', 'WMUH2_flt_spm_god_null_8s', 'WMUH2_flt_spm_god_null_8d', 'WMUH2_flt_spm_god_null_8s', 'WMUH2_flt_spm_god_null_8d', 'strap', 'tnail', 'tnail', 'tnail_1', 'WMUH3'] ref = np.ones(18) for i in range(18): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'wmuh_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = WMUH_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MSF_config(): """ Testing the MSF_config function. """ res = [] ref_class = ['nav_1', 'nav_0', '8s', '8d', '8s', '8d', 'MSF2'] ref = np.ones(7) for i in range(7): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'msf_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MSF_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MMUH_config(): """ Testing the MMUH_config function. """ res = [] ref_class = ['flt_1_spm_god', 'flt_1_spm_por', 'flt_1_bur_por', '8s_strap', '8d_strap', '8d_tnail', '8s_strap', '8d_tnail', 'MMUH3'] ref = np.ones(9) for i in range(9): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mmuh_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MMUH_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MLRM_config(): """ Testing the MLRM_config function. """ res = [] ref_class = ['spm', 'bur', 'C', 'D', 'A', '6d_god', '6d_por', 'std', 'sup', 'A_1_sup', 'sgl', 'mlt'] ref = np.ones(12) for i in range(12): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mlrm_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MLRM_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MLRI_config(): """ Testing the MLRI_config function. """ res = [] ref_class = ['sup', 'std', 'god', 'por', 'god', 'por'] ref = np.ones(6) for i in range(6): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mlri_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MLRI_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MERB_config(): """ Testing the MERB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'MERBL', 'MERBM', 'MERBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'merb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MERB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MECB_config(): """ Testing the MECB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'MECBL', 'MECBM', 'MECBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mecb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MECB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_CECB_config(): """ Testing the CECB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'low', 'med', 'hig', 'CECBL', 'CECBM', 'CECBH'] ref = np.ones(12) for i in range(12): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'cecb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = CECB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_CERB_config(): """ Testing the CERB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'low', 'med', 'hig', 'CERBL', 'CERBM', 'CERBH'] ref = np.ones(12) for i in range(12): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'cerb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = CERB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_SPMB_config(): """ Testing the SPMB_config function. """ res = [] ref_class = ['god', 'por', 'std', 'sup', 'SPMBS', 'SPMBM', 'SPMBL'] ref = np.ones(7) for i in range(7): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'spmb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = SPMB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_SECB_config(): """ Testing the SECB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'SECBL', 'SECBM', 'SECBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'secb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = SECB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_SERB_config(): """ Testing the SERB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'SERBL', 'SERBM', 'SERBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'secb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = SERB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_FL_config(): """ Testing the FL_config function. """ res = [] ref_class = ['raz', 'cvz', 'sl', 'bn', 'bw'] ref = np.ones(5) for i in range(5): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'fl_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = FL_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_Assm_config(): """ Testing the Assm_config function. """ res = [] ref_class = ['raz', 'caz', 'cvz', '1', '0'] ref = np.ones(5) for i in range(5): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'assm_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) tmp2, data_output = Assm_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5)
pelicun/resources/auto_population/tests/test_auto_HU_NJ.py
import pytest import numpy as np from numpy.testing import assert_allclose import json import os import inspect # Importing auto_HU_NJ module from auto_HU_NJ import * # Current directory cur_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # Test input directory base_input_path = 'resources' def test_parse_BIM(): """ Testing the parse_BIM function. """ # Testing the ruleset for Hurricane-Prone Region (HPR) res = [] ref = [1, 0, 1, 0] for i in range(4): BIM_dir = os.path.join(cur_dir, base_input_path, 'BIM_Data', 'parse_BIM_test_' + str(i+1) + '.json') with open(BIM_dir) as f: BIM_input = json.load(f) BIM_output = parse_BIM(BIM_input['GI']) res.append(int(BIM_output['HPR'])) # Check assert_allclose(res, ref, atol=1e-5) # Testing the ruleset for Wind Borne Debris (WBD) res = [] ref = [0, 0, 0, 0, 1, 1, 1, 1] for i in range(8): BIM_dir = os.path.join(cur_dir, base_input_path, 'BIM_Data', 'parse_BIM_test_' + str(i+1) + '.json') with open(BIM_dir) as f: BIM_input = json.load(f) BIM_output = parse_BIM(BIM_input['GI']) res.append(int(BIM_output['WBD'])) # Check assert_allclose(res, ref, atol=1e-5) # Testing the ruleset for terrain res = [] ref = [3, 15, 35, 70, 3, 15, 35, 70] for i in range(8): BIM_dir = os.path.join(cur_dir, base_input_path, 'BIM_Data', 'parse_BIM_test_' + str(i+1) + '.json') with open(BIM_dir) as f: BIM_input = json.load(f) BIM_output = parse_BIM(BIM_input['GI']) res.append(int(BIM_output['terrain'])) # Check assert_allclose(res, ref, atol=1e-5) def test_building_class(): """ Testing the building class function. """ # Testing the ruleset for classifying Hazus building class res = [] ref_class = ['WSF', 'WMUH', 'SERB', 'SECB', 'SPMB', 'CERB', 'CECB', 'MSF', 'MERB', 'MECB', 'MLRI', 'MMUH', 'MLRM'] ref = np.ones(13) for i in range(13): data_dir = os.path.join(cur_dir, base_input_path, 'BuildingClass_Data', 'building_class_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = building_class(tmp) print(data_output) res.append(int(data_output == ref_class[i])) # Check assert_allclose(res, ref, atol=1e-5) def test_WSF_config(): """ Testing the WSF_config function. """ res = [] ref_class = ['WSF2_gab_0_8d_tnail_no', 'WSF2_gab_1_8d_tnail_no', 'WSF2_hip_1_8d_tnail_no', 'WSF2_hip_0_8d_tnail_no', '8s_strap_no', '8s_strap_no', '8s_tnail_no', '8s_strap_sup', '8d_strap_std', '8d_tnail_wkd', 'WSF1'] ref = np.ones(11) for i in range(11): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'wsf_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = WSF_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_WMUH_config(): """ Testing the WMUH_config function. """ res = [] ref_class = ['WMUH2_flt_spm_god_null', 'WMUH2_flt_spm_god_null', 'WMUH2_flt_spm_god_null', 'WMUH2_gab_null_null_1', 'WMUH2_hip_null_null_1', 'WMUH2_gab_null_null_0', 'WMUH2_hip_null_null_0', 'WMUH2_flt_spm_por_null', 'WMUH2_flt_bur_por_null', 'WMUH2_flt_spm_god_null_8s', 'WMUH2_flt_spm_god_null_8d', 'WMUH2_flt_spm_god_null_8s', 'WMUH2_flt_spm_god_null_8d', 'strap', 'tnail', 'tnail', 'tnail_1', 'WMUH3'] ref = np.ones(18) for i in range(18): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'wmuh_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = WMUH_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MSF_config(): """ Testing the MSF_config function. """ res = [] ref_class = ['nav_1', 'nav_0', '8s', '8d', '8s', '8d', 'MSF2'] ref = np.ones(7) for i in range(7): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'msf_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MSF_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MMUH_config(): """ Testing the MMUH_config function. """ res = [] ref_class = ['flt_1_spm_god', 'flt_1_spm_por', 'flt_1_bur_por', '8s_strap', '8d_strap', '8d_tnail', '8s_strap', '8d_tnail', 'MMUH3'] ref = np.ones(9) for i in range(9): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mmuh_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MMUH_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MLRM_config(): """ Testing the MLRM_config function. """ res = [] ref_class = ['spm', 'bur', 'C', 'D', 'A', '6d_god', '6d_por', 'std', 'sup', 'A_1_sup', 'sgl', 'mlt'] ref = np.ones(12) for i in range(12): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mlrm_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MLRM_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MLRI_config(): """ Testing the MLRI_config function. """ res = [] ref_class = ['sup', 'std', 'god', 'por', 'god', 'por'] ref = np.ones(6) for i in range(6): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mlri_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MLRI_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MERB_config(): """ Testing the MERB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'MERBL', 'MERBM', 'MERBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'merb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MERB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_MECB_config(): """ Testing the MECB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'MECBL', 'MECBM', 'MECBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'mecb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = MECB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_CECB_config(): """ Testing the CECB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'low', 'med', 'hig', 'CECBL', 'CECBM', 'CECBH'] ref = np.ones(12) for i in range(12): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'cecb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = CECB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_CERB_config(): """ Testing the CERB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'low', 'med', 'hig', 'CERBL', 'CERBM', 'CERBH'] ref = np.ones(12) for i in range(12): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'cerb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = CERB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_SPMB_config(): """ Testing the SPMB_config function. """ res = [] ref_class = ['god', 'por', 'std', 'sup', 'SPMBS', 'SPMBM', 'SPMBL'] ref = np.ones(7) for i in range(7): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'spmb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = SPMB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_SECB_config(): """ Testing the SECB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'SECBL', 'SECBM', 'SECBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'secb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = SECB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_SERB_config(): """ Testing the SERB_config function. """ res = [] ref_class = ['bur', 'spm', 'bur', 'C', 'D', 'A', 'std', 'sup', 'low', 'med', 'hig', 'SERBL', 'SERBM', 'SERBH'] ref = np.ones(14) for i in range(14): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'secb_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = SERB_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_FL_config(): """ Testing the FL_config function. """ res = [] ref_class = ['raz', 'cvz', 'sl', 'bn', 'bw'] ref = np.ones(5) for i in range(5): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'fl_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) data_output = FL_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5) def test_Assm_config(): """ Testing the Assm_config function. """ res = [] ref_class = ['raz', 'caz', 'cvz', '1', '0'] ref = np.ones(5) for i in range(5): data_dir = os.path.join(cur_dir, base_input_path, 'Config_Data', 'assm_test_' + str(i+1) + '.json') with open(data_dir) as f: data_input = json.load(f) tmp = parse_BIM(data_input['GI']) tmp2, data_output = Assm_config(tmp) print(data_output) res.append(int(ref_class[i] in data_output)) # Check assert_allclose(res, ref, atol=1e-5)
0.295636
0.320808
from django.db import migrations, transaction class Migration(migrations.Migration): dependencies = [ ("App", "0002_user_test_data"), ] def generate_data(apps, schema_editor): from App.models import Website, Profile from django.shortcuts import get_object_or_404 website_test_data = [ ( "Tel Aviv", "App/images/WebsitesLogos/test_data/Tel_Aviv/favicon.ico", "App/images/WebsitesLogos/test_data/Tel_Aviv/Tel_Aviv_Logo.png", 2, "#fff", "#4f5a62", "#3498db", "#fff", "#0009FF", 21, True, ), ( "Vegan", "App/images/WebsitesLogos/test_data/Vegan/favicon.ico", "App/images/WebsitesLogos/test_data/Vegan/Vegan_Logo.png", 2, "#fbff00", "#33A300", "#01FF42", "#B5E63F", "#33A300", 21, True, ), ( "Coffee", "App/images/WebsitesLogos/test_data/Coffee/favicon.ico", "App/images/WebsitesLogos/test_data/Coffee/Coffee_Logo.png", 2, "#FF8601", "#583100", "#3498db", "#fffdd0", "#FF8601", 22, True, ), ( "Electronics", "App/images/WebsitesLogos/test_data/Electronics/favicon.ico", "App/images/WebsitesLogos/test_data/Electronics/Electronics_Logo.png", 2, "#fff", "#4f5a62", "#E4EA01", "#fff", "#E4EA01", 22, True, ), ( "Carnibors", "App/images/WebsitesLogos/test_data/Carnibors/favicon.ico", "App/images/WebsitesLogos/test_data/Carnibors/Carnibors_Logo.png", 2, "#fff", "#BA0102", "#FF0103", "#fff", "#BA0102", 22, True, ), ( "Candies", "App/images/WebsitesLogos/test_data/Candies/favicon.ico", "App/images/WebsitesLogos/test_data/Candies/Candies_Logo.png", 2, "#01E8E6", "#FF01C6", "#FF017A", "#FF01C6", "#01E8E6", 22, True, ), ( "Fitness", "App/images/WebsitesLogos/test_data/Fitness/favicon.ico", "App/images/WebsitesLogos/test_data/Fitness/Fitness_Logo.png", 3, "#686868", "#41EE5C", "#7AFF01", "#fff", "#41EE5C", 22, True, ), ( "Craftig", "App/images/WebsitesLogos/test_data/Crafting/favicon.ico", "App/images/WebsitesLogos/test_data/Crafting/Crafting_Logo.png", 2, "#fff", "#EB01FF", "#FF01B5", "#fff", "#EB01FF", 22, True, ), ( "Dairy", "App/images/WebsitesLogos/test_data/Dairy/favicon.ico", "App/images/WebsitesLogos/test_data/Dairy/Dairy_Logo.png", 2, "#FEFFC8", "#4f5a62", "#3498db", "#fff", "#0009FF", 22, True, ), ] with transaction.atomic(): for ( website_name, favicon, logo, number_of_slides, navbar_background_color, navbar_text_color, navbar_hover_text_color, sliders_text_color, sliders_carsoul_color, user, is_admin, ) in website_test_data: website = Website( name=website_name, favicon=favicon, logo=logo, number_of_slides_in_main_page=number_of_slides, navbar_background_color=navbar_background_color, navbar_text_color=navbar_text_color, navbar_hover_text_color=navbar_hover_text_color, sliders_text_color=sliders_text_color, sliders_carsoul_color=sliders_carsoul_color, ) website.save() profile = get_object_or_404(Profile, pk=user) profile.match_website_to_profile(website, is_admin) operations = [ migrations.RunPython(generate_data), ]
App/migrations/0003_website_test_data.py
from django.db import migrations, transaction class Migration(migrations.Migration): dependencies = [ ("App", "0002_user_test_data"), ] def generate_data(apps, schema_editor): from App.models import Website, Profile from django.shortcuts import get_object_or_404 website_test_data = [ ( "Tel Aviv", "App/images/WebsitesLogos/test_data/Tel_Aviv/favicon.ico", "App/images/WebsitesLogos/test_data/Tel_Aviv/Tel_Aviv_Logo.png", 2, "#fff", "#4f5a62", "#3498db", "#fff", "#0009FF", 21, True, ), ( "Vegan", "App/images/WebsitesLogos/test_data/Vegan/favicon.ico", "App/images/WebsitesLogos/test_data/Vegan/Vegan_Logo.png", 2, "#fbff00", "#33A300", "#01FF42", "#B5E63F", "#33A300", 21, True, ), ( "Coffee", "App/images/WebsitesLogos/test_data/Coffee/favicon.ico", "App/images/WebsitesLogos/test_data/Coffee/Coffee_Logo.png", 2, "#FF8601", "#583100", "#3498db", "#fffdd0", "#FF8601", 22, True, ), ( "Electronics", "App/images/WebsitesLogos/test_data/Electronics/favicon.ico", "App/images/WebsitesLogos/test_data/Electronics/Electronics_Logo.png", 2, "#fff", "#4f5a62", "#E4EA01", "#fff", "#E4EA01", 22, True, ), ( "Carnibors", "App/images/WebsitesLogos/test_data/Carnibors/favicon.ico", "App/images/WebsitesLogos/test_data/Carnibors/Carnibors_Logo.png", 2, "#fff", "#BA0102", "#FF0103", "#fff", "#BA0102", 22, True, ), ( "Candies", "App/images/WebsitesLogos/test_data/Candies/favicon.ico", "App/images/WebsitesLogos/test_data/Candies/Candies_Logo.png", 2, "#01E8E6", "#FF01C6", "#FF017A", "#FF01C6", "#01E8E6", 22, True, ), ( "Fitness", "App/images/WebsitesLogos/test_data/Fitness/favicon.ico", "App/images/WebsitesLogos/test_data/Fitness/Fitness_Logo.png", 3, "#686868", "#41EE5C", "#7AFF01", "#fff", "#41EE5C", 22, True, ), ( "Craftig", "App/images/WebsitesLogos/test_data/Crafting/favicon.ico", "App/images/WebsitesLogos/test_data/Crafting/Crafting_Logo.png", 2, "#fff", "#EB01FF", "#FF01B5", "#fff", "#EB01FF", 22, True, ), ( "Dairy", "App/images/WebsitesLogos/test_data/Dairy/favicon.ico", "App/images/WebsitesLogos/test_data/Dairy/Dairy_Logo.png", 2, "#FEFFC8", "#4f5a62", "#3498db", "#fff", "#0009FF", 22, True, ), ] with transaction.atomic(): for ( website_name, favicon, logo, number_of_slides, navbar_background_color, navbar_text_color, navbar_hover_text_color, sliders_text_color, sliders_carsoul_color, user, is_admin, ) in website_test_data: website = Website( name=website_name, favicon=favicon, logo=logo, number_of_slides_in_main_page=number_of_slides, navbar_background_color=navbar_background_color, navbar_text_color=navbar_text_color, navbar_hover_text_color=navbar_hover_text_color, sliders_text_color=sliders_text_color, sliders_carsoul_color=sliders_carsoul_color, ) website.save() profile = get_object_or_404(Profile, pk=user) profile.match_website_to_profile(website, is_admin) operations = [ migrations.RunPython(generate_data), ]
0.33764
0.210502
import pytest from pyidxp.aws.s3 import S3 from boto.s3.connection import OrdinaryCallingFormat class FakeS3Connection: __ref__ = None def __init__(self, region, aws_access_key_id=None, aws_secret_access_key=None, calling_format=None): self.__class__.__ref__ = self self.conn_params = { 'region': region, 'access_key': aws_access_key_id, 'secret_key': aws_secret_access_key, 'calling_format': calling_format, } def get_all_buckets(self): class B: def __init__(self, name): self.name = name return [B('bucket1'), B('bucket2')] def get_bucket(self, name): return 'Get ' + name def create_bucket(self, name): return 'Created ' + name class TestS3: def get_configs(self): return { 'aws': { 'fakes3': False, 'region': 'region', 'access_key': 'access_key', 'secret_key': 'secret_key', } } @pytest.fixture(autouse=True) def mock_real_connection(self, monkeypatch): monkeypatch.setattr('pyidxp.aws.s3.s3_connect_to_region', FakeS3Connection) @pytest.fixture() def mock_fake_connection(self, monkeypatch): def mock(access_key, secret_key, is_secure=None, port=None, host=None, calling_format=None): self.fake_conn_params = { 'calling_format': calling_format, } return 's3_fake_conn' monkeypatch.setattr('pyidxp.aws.s3.S3Connection', mock) def test_connect_to_real_s3(self): configs = self.get_configs() assert S3(configs).conn.__class__ == FakeS3Connection def test_connection_params_to_real_s3(self): configs = self.get_configs() S3(configs) params = FakeS3Connection.__ref__.conn_params assert params['region'] == configs['aws']['region'] assert params['access_key'] == configs['aws']['access_key'] assert params['secret_key'] == configs['aws']['secret_key'] assert params['calling_format'].__class__ == OrdinaryCallingFormat def test_connect_to_fake_s3(self, mock_fake_connection): configs = self.get_configs() configs['aws']['fakes3'] = True assert S3(configs).conn == 's3_fake_conn' def test_connection_params_to_fake_s3(self, mock_fake_connection): configs = self.get_configs() configs['aws']['fakes3'] = True S3(configs) params = self.fake_conn_params assert params['calling_format'].__class__ == OrdinaryCallingFormat def test_get_bucket_that_exists(self): assert S3(self.get_configs()).get_bucket('bucket1') == 'Get bucket1' def test_create_bucket_that_does_not_exist(self): assert S3(self.get_configs()).get_bucket('asdasd') == 'Created asdasd'
tests/aws/test_s3.py
import pytest from pyidxp.aws.s3 import S3 from boto.s3.connection import OrdinaryCallingFormat class FakeS3Connection: __ref__ = None def __init__(self, region, aws_access_key_id=None, aws_secret_access_key=None, calling_format=None): self.__class__.__ref__ = self self.conn_params = { 'region': region, 'access_key': aws_access_key_id, 'secret_key': aws_secret_access_key, 'calling_format': calling_format, } def get_all_buckets(self): class B: def __init__(self, name): self.name = name return [B('bucket1'), B('bucket2')] def get_bucket(self, name): return 'Get ' + name def create_bucket(self, name): return 'Created ' + name class TestS3: def get_configs(self): return { 'aws': { 'fakes3': False, 'region': 'region', 'access_key': 'access_key', 'secret_key': 'secret_key', } } @pytest.fixture(autouse=True) def mock_real_connection(self, monkeypatch): monkeypatch.setattr('pyidxp.aws.s3.s3_connect_to_region', FakeS3Connection) @pytest.fixture() def mock_fake_connection(self, monkeypatch): def mock(access_key, secret_key, is_secure=None, port=None, host=None, calling_format=None): self.fake_conn_params = { 'calling_format': calling_format, } return 's3_fake_conn' monkeypatch.setattr('pyidxp.aws.s3.S3Connection', mock) def test_connect_to_real_s3(self): configs = self.get_configs() assert S3(configs).conn.__class__ == FakeS3Connection def test_connection_params_to_real_s3(self): configs = self.get_configs() S3(configs) params = FakeS3Connection.__ref__.conn_params assert params['region'] == configs['aws']['region'] assert params['access_key'] == configs['aws']['access_key'] assert params['secret_key'] == configs['aws']['secret_key'] assert params['calling_format'].__class__ == OrdinaryCallingFormat def test_connect_to_fake_s3(self, mock_fake_connection): configs = self.get_configs() configs['aws']['fakes3'] = True assert S3(configs).conn == 's3_fake_conn' def test_connection_params_to_fake_s3(self, mock_fake_connection): configs = self.get_configs() configs['aws']['fakes3'] = True S3(configs) params = self.fake_conn_params assert params['calling_format'].__class__ == OrdinaryCallingFormat def test_get_bucket_that_exists(self): assert S3(self.get_configs()).get_bucket('bucket1') == 'Get bucket1' def test_create_bucket_that_does_not_exist(self): assert S3(self.get_configs()).get_bucket('asdasd') == 'Created asdasd'
0.578686
0.128908
import json import traceback from django.http import JsonResponse from ..models import ApigeeMgmtLog from ..env import Env from ..utils import REQUEST_KEYS_NO_ARTIFACTS from ..validate import validate_payload, ValidationException from .sharedflows import migrate_shared_flows from .proxies import migrate_proxies from .specs import migrate_specs from .products import migrate_products """ structure of incoming request, for reference { "metadata": { // added by apigee "tenant-prefix": "", // maybe not? "username":"", // maybe? "userRoles": [], "ipAddr": "" }, "request": { "buildTags":"", "comment":"", "sharedflows":[ { 'name': 'ats-shared-flow' 'revision': '1' // OPTIONAL defaults to latest. however, if revision is supplied, existence will be validated } ], "proxies":[ { 'name': 'ats-proxy' 'revision': '2' // OPTIONAL defaults to latest. however, if revision is supplied, existence will be validated } ], "products":['ats-product-1', 'ats-product-2'], "specs":['ats-spec-1'] } } """ def migrate(migration_request: dict, target_env: Env = Env.STAGE): """ use Env.value as key in MIGRATION_MAP for apigee organizations for src and dest organizations create initial log with request capture IP address, too, and add that add tenant prefix / username, depending orchestrate calls to migrate different artifacts, aggregate responses, add that to log as response_text :param migration_request: :param target_env: :return: """ metadata = migration_request['metadata'] request_data = migration_request['request'] apigee_mgmt_log = ApigeeMgmtLog(tenant_prefix=metadata['tenant-prefix'], destination=metadata['destination'], ip_addr=metadata['ipAddr'], username=metadata['username'], created_by=metadata['username'], user_roles=metadata['userRoles'], request_text=json.dumps(request_data), build_tags=request_data['buildTags'], build_comment=request_data['comment'] ) # once logged, remove comment and buildTags for key in REQUEST_KEYS_NO_ARTIFACTS: del migration_request['request'][key] # how to handle failed validation? response_dict = { "result": {} } try: validation_dict, artifact_info_dict = validate_payload(migration_request, target_env) if validation_dict: response_dict['validationResults'] = validation_dict response_dict['artifactInfo'] = artifact_info_dict raise ValidationException("VALIDATION FAILED! - see validationResults for details") else: # validation passed; migrate all if 'sharedflows' in request_data and request_data['sharedflows']: response_dict['sharedflows'] = migrate_shared_flows(request_data['sharedflows'], target_env=target_env), if 'proxies' in request_data and request_data['proxies']: response_dict['proxies'] = migrate_proxies(request_data['proxies'], target_env=target_env), if 'specs' in request_data and request_data['specs']: response_dict['specs'] = migrate_specs(request_data['specs'], target_env=target_env), if 'products' in request_data and request_data['products']: response_dict['products'] = migrate_products(request_data['products'], target_env=target_env) response_dict['result'] = {"SUCCESS": "Successfully migrated payload"} apigee_mgmt_log.status = 'success' status_code = 200 except ValidationException as val_err: traceback.print_tb(val_err.__traceback__) response_dict["result"] = {"ERROR": f"{val_err}"} apigee_mgmt_log.status = 'invalid' status_code = 400 except Exception as err: traceback.print_tb(err.__traceback__) response_dict["result"] = {"ERROR": f"{err}"} apigee_mgmt_log.status = 'error' status_code = 500 finally: # add aggregated response to log and persist it apigee_mgmt_log.response_text = json.dumps(response_dict) apigee_mgmt_log.save() return JsonResponse(data=response_dict, status=status_code)
api/migrate/migrate.py
import json import traceback from django.http import JsonResponse from ..models import ApigeeMgmtLog from ..env import Env from ..utils import REQUEST_KEYS_NO_ARTIFACTS from ..validate import validate_payload, ValidationException from .sharedflows import migrate_shared_flows from .proxies import migrate_proxies from .specs import migrate_specs from .products import migrate_products """ structure of incoming request, for reference { "metadata": { // added by apigee "tenant-prefix": "", // maybe not? "username":"", // maybe? "userRoles": [], "ipAddr": "" }, "request": { "buildTags":"", "comment":"", "sharedflows":[ { 'name': 'ats-shared-flow' 'revision': '1' // OPTIONAL defaults to latest. however, if revision is supplied, existence will be validated } ], "proxies":[ { 'name': 'ats-proxy' 'revision': '2' // OPTIONAL defaults to latest. however, if revision is supplied, existence will be validated } ], "products":['ats-product-1', 'ats-product-2'], "specs":['ats-spec-1'] } } """ def migrate(migration_request: dict, target_env: Env = Env.STAGE): """ use Env.value as key in MIGRATION_MAP for apigee organizations for src and dest organizations create initial log with request capture IP address, too, and add that add tenant prefix / username, depending orchestrate calls to migrate different artifacts, aggregate responses, add that to log as response_text :param migration_request: :param target_env: :return: """ metadata = migration_request['metadata'] request_data = migration_request['request'] apigee_mgmt_log = ApigeeMgmtLog(tenant_prefix=metadata['tenant-prefix'], destination=metadata['destination'], ip_addr=metadata['ipAddr'], username=metadata['username'], created_by=metadata['username'], user_roles=metadata['userRoles'], request_text=json.dumps(request_data), build_tags=request_data['buildTags'], build_comment=request_data['comment'] ) # once logged, remove comment and buildTags for key in REQUEST_KEYS_NO_ARTIFACTS: del migration_request['request'][key] # how to handle failed validation? response_dict = { "result": {} } try: validation_dict, artifact_info_dict = validate_payload(migration_request, target_env) if validation_dict: response_dict['validationResults'] = validation_dict response_dict['artifactInfo'] = artifact_info_dict raise ValidationException("VALIDATION FAILED! - see validationResults for details") else: # validation passed; migrate all if 'sharedflows' in request_data and request_data['sharedflows']: response_dict['sharedflows'] = migrate_shared_flows(request_data['sharedflows'], target_env=target_env), if 'proxies' in request_data and request_data['proxies']: response_dict['proxies'] = migrate_proxies(request_data['proxies'], target_env=target_env), if 'specs' in request_data and request_data['specs']: response_dict['specs'] = migrate_specs(request_data['specs'], target_env=target_env), if 'products' in request_data and request_data['products']: response_dict['products'] = migrate_products(request_data['products'], target_env=target_env) response_dict['result'] = {"SUCCESS": "Successfully migrated payload"} apigee_mgmt_log.status = 'success' status_code = 200 except ValidationException as val_err: traceback.print_tb(val_err.__traceback__) response_dict["result"] = {"ERROR": f"{val_err}"} apigee_mgmt_log.status = 'invalid' status_code = 400 except Exception as err: traceback.print_tb(err.__traceback__) response_dict["result"] = {"ERROR": f"{err}"} apigee_mgmt_log.status = 'error' status_code = 500 finally: # add aggregated response to log and persist it apigee_mgmt_log.response_text = json.dumps(response_dict) apigee_mgmt_log.save() return JsonResponse(data=response_dict, status=status_code)
0.273186
0.112893
import time import github from loguru import logger from typing import List class GithubWrapper: def __init__(self, token, throttle_secs): self.gh = github.Github(token) self.cache = {} self.throttle_secs = throttle_secs self.get_repo_cache_miss_count = 0 self.get_repo_cache_hit_count = 0 def get_repo(self, name, use_cache=True, throttled=True) -> github.Repository: if name.endswith("/"): logger.warning(f"Repo needs to be fixed by removing trailing slash in source csv: {name}") if name.endswith("*"): logger.warning(f"Repo needs to be fixed by exploding wildcard repo in source csv: {name}") if throttled: time.sleep(self.throttle_secs) key = f"repo_{name}" cached = self.cache.get(key, None) if cached is None or not use_cache: self.get_repo_cache_miss_count += 1 logger.info(f"get_repo: [{name}] (cache miss {self.get_repo_cache_miss_count})") try: self.cache[key] = self.gh.get_repo(name) except Exception as ex: logger.warning(f"Exception for get_repo with name (will re-try once): {name}") try: time.sleep(30) self.cache[key] = self.gh.get_repo(name) except Exception as ex: logger.error(f"Exception for get_repo with name: {name}") raise ex return self.cache[key] else: self.get_repo_cache_hit_count += 1 logger.info(f"get_repo: [{name}] (cache hit {self.get_repo_cache_hit_count})") return cached def get_org_repos(self, name, throttled=True) -> List[github.Repository.Repository]: logger.debug(f"get_org_repos: {name}") if throttled: time.sleep(self.throttle_secs) try: org = self.gh.get_organization(name) except Exception as ex: logger.warning(f"Exception for get_org_repos with name (will re-try once): {name}") try: time.sleep(30) org = self.gh.get_organization(name) except Exception as ex: logger.error(f"Exception for get_org_repos with name: {name}") raise ex try: repos = org.get_repos() except Exception as ex: logger.warning(f"Exception for get_repos with name (will re-try once): {name}") try: time.sleep(30) repos = org.get_repos() except Exception as ex: logger.error(f"Exception for get_repos with name: {name}") raise ex result_repos = [] for repo in repos: result_repos.append(repo) return result_repos def get_organization(self, name, throttled=True) -> github.Organization.Organization: logger.debug(f"get_organization: {name}") if throttled: time.sleep(self.throttle_secs) return self.gh.get_organization(name) def search_github(self, keywords, throttled=True): logger.debug(f"search_github: {keywords}") if throttled: time.sleep(self.throttle_secs) query = "+".join(keywords) + "+in:readme+in:description" result = self.gh.search_repositories(query, "stars", "desc") print(f"Found {result.totalCount} repo(s)") for repo in result: print(repo.clone_url)
src/library/ghw.py
import time import github from loguru import logger from typing import List class GithubWrapper: def __init__(self, token, throttle_secs): self.gh = github.Github(token) self.cache = {} self.throttle_secs = throttle_secs self.get_repo_cache_miss_count = 0 self.get_repo_cache_hit_count = 0 def get_repo(self, name, use_cache=True, throttled=True) -> github.Repository: if name.endswith("/"): logger.warning(f"Repo needs to be fixed by removing trailing slash in source csv: {name}") if name.endswith("*"): logger.warning(f"Repo needs to be fixed by exploding wildcard repo in source csv: {name}") if throttled: time.sleep(self.throttle_secs) key = f"repo_{name}" cached = self.cache.get(key, None) if cached is None or not use_cache: self.get_repo_cache_miss_count += 1 logger.info(f"get_repo: [{name}] (cache miss {self.get_repo_cache_miss_count})") try: self.cache[key] = self.gh.get_repo(name) except Exception as ex: logger.warning(f"Exception for get_repo with name (will re-try once): {name}") try: time.sleep(30) self.cache[key] = self.gh.get_repo(name) except Exception as ex: logger.error(f"Exception for get_repo with name: {name}") raise ex return self.cache[key] else: self.get_repo_cache_hit_count += 1 logger.info(f"get_repo: [{name}] (cache hit {self.get_repo_cache_hit_count})") return cached def get_org_repos(self, name, throttled=True) -> List[github.Repository.Repository]: logger.debug(f"get_org_repos: {name}") if throttled: time.sleep(self.throttle_secs) try: org = self.gh.get_organization(name) except Exception as ex: logger.warning(f"Exception for get_org_repos with name (will re-try once): {name}") try: time.sleep(30) org = self.gh.get_organization(name) except Exception as ex: logger.error(f"Exception for get_org_repos with name: {name}") raise ex try: repos = org.get_repos() except Exception as ex: logger.warning(f"Exception for get_repos with name (will re-try once): {name}") try: time.sleep(30) repos = org.get_repos() except Exception as ex: logger.error(f"Exception for get_repos with name: {name}") raise ex result_repos = [] for repo in repos: result_repos.append(repo) return result_repos def get_organization(self, name, throttled=True) -> github.Organization.Organization: logger.debug(f"get_organization: {name}") if throttled: time.sleep(self.throttle_secs) return self.gh.get_organization(name) def search_github(self, keywords, throttled=True): logger.debug(f"search_github: {keywords}") if throttled: time.sleep(self.throttle_secs) query = "+".join(keywords) + "+in:readme+in:description" result = self.gh.search_repositories(query, "stars", "desc") print(f"Found {result.totalCount} repo(s)") for repo in result: print(repo.clone_url)
0.382949
0.077588
from PyQt5 import QtWidgets from PyQt5.QtCore import QRegExp, pyqtSlot from PyQt5.QtGui import QRegExpValidator, QValidator import os import sys from lib.settings import SETTINGS, get_language_versions, get_model_languages, update_settings from lib.utils.crypt import Crypt VALID = 2 # value of state enum representing valid state after validation EMAIL_REGEX = "^([a-zA-Z0-9]+[\\._-]?[a-zA-Z0-9]+)[@](\\w+[.])+\\w{2,3}$" class InputValidator(QRegExpValidator): """ A custom validator class that will set mark the parent object as invalid if the validator fails. """ def __init__(self, *args, allow_empty=False, **kwargs): super().__init__(*args, **kwargs) self.allow_empty = allow_empty def validate(self, text: str, pos: int): state, text, pos = super(InputValidator, self).validate(text, pos) selector = { QValidator.Invalid: "invalid", QValidator.Intermediate: "intermediate", QValidator.Acceptable: "acceptable", }[state] if selector == "invalid" or (not self.allow_empty and selector == "intermediate"): self.parent().setProperty("invalid", True) else: self.parent().setProperty("invalid", False) self.parent().style().unpolish(self.parent()) self.parent().style().polish(self.parent()) return state, text, pos class SettingsView(QtWidgets.QWidget): # Dict containing the fields which are not allowed to be submitted empty empty_fields = {"name": False} def __init__(self, main_window, *args, **kwargs): super(SettingsView, self).__init__(*args, **kwargs) self.main_window = main_window scroll_area = QtWidgets.QScrollArea() scroll_area.setMaximumWidth(960) scroll_area.setWidgetResizable(True) main_layout = QtWidgets.QHBoxLayout() main_layout.addWidget(scroll_area) widget = QtWidgets.QWidget() widget.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) layout = QtWidgets.QGridLayout() layout.setVerticalSpacing(8) self.initial_state = SETTINGS # store the settings to restore it if needed self.title = QtWidgets.QLabel("Settings") self.title.setObjectName("viewTitle") self.title.setMinimumHeight(48) row = 0 layout.addWidget(self.title, row, 0, 1, 4) # Editor settings row += 1 self.editor_title = QtWidgets.QLabel("Editor") self.editor_title.setObjectName("settingsSectionTitle") layout.addWidget(self.editor_title, row, 0, 1, 4) row += 1 self.theme = QtWidgets.QComboBox() self.theme.addItem("Light Theme", "light-theme") self.theme.addItem("Dark Theme", "dark-theme") self.theme.setCurrentIndex(self.theme.findData(SETTINGS["editor"]["theme"])) layout.addWidget(QtWidgets.QLabel("Theme"), row, 0) layout.addWidget(self.theme, row, 1, 1, 3) row += 1 self.font_family = QtWidgets.QLineEdit(SETTINGS["editor"]["font-family"]) layout.addWidget(QtWidgets.QLabel("Font"), row, 0) layout.addWidget(self.font_family, row, 1, 1, 3) row += 1 self.font_size = QtWidgets.QLineEdit(SETTINGS["editor"]["font-size"]) layout.addWidget(QtWidgets.QLabel("Font size"), row, 0) self.font_size_validator = InputValidator(QRegExp("^[0-9]+$"), self.font_size) self.font_size.setValidator(self.font_size_validator) layout.addWidget(self.font_size, row, 1, 1, 3) # Meeting settings row += 1 self.meetings_title = QtWidgets.QLabel("Meetings") self.meetings_title.setObjectName("settingsSectionTitle") layout.addWidget(self.meetings_title, row, 0, 1, 4) row += 1 self.standard_duration = QtWidgets.QLineEdit(str(SETTINGS["meeting"]["standard_duration"])) self.std_dur_validator = InputValidator(QRegExp("^[0-9]+$"), self.standard_duration) self.standard_duration.setValidator(self.std_dur_validator) layout.addWidget(QtWidgets.QLabel("Standard duration (min)"), row, 0) layout.addWidget(self.standard_duration, row, 1, 1, 3) # User settings section row += 1 self.email_title = QtWidgets.QLabel("User") self.email_title.setObjectName("settingsSectionTitle") layout.addWidget(self.email_title, row, 0, 1, 4) # Name row += 1 self.name = QtWidgets.QLineEdit(str(SETTINGS["user"]["name"])) self.name.textChanged.connect(self.is_empty) layout.addWidget(QtWidgets.QLabel("Name"), row, 0) layout.addWidget(self.name, row, 1, 1, 3) # Email row += 1 self.email_address = QtWidgets.QLineEdit(str(SETTINGS["user"]["email"]["address"])) self.email_validator = InputValidator(QRegExp(EMAIL_REGEX), self.email_address) self.email_address.setValidator(self.email_validator) layout.addWidget(QtWidgets.QLabel("Email"), row, 0) layout.addWidget(self.email_address, row, 1, 1, 3) # SMTP server section row += 1 self.smtp_title = QtWidgets.QLabel("SMTP server") self.smtp_title.setObjectName("settingsSectionTitle") layout.addWidget(self.smtp_title, row, 0, 1, 4) # SMTP username (email) row += 1 conf_username = SETTINGS["user"]["email"]["username"] self.smtp_username = QtWidgets.QLineEdit(str(conf_username)) layout.addWidget(QtWidgets.QLabel("Username"), row, 0) layout.addWidget(self.smtp_username, row, 1, 1, 3) # SMTP password (email) row += 1 self.email_password = QtWidgets.QLineEdit() self.email_password.setPlaceholderText("<PASSWORD>") self.email_password.setEchoMode(QtWidgets.QLineEdit.Password) layout.addWidget(QtWidgets.QLabel("Password"), row, 0) layout.addWidget(self.email_password, row, 1, 1, 3) # SMTP host row += 1 self.smtp_host = QtWidgets.QLineEdit(str(SETTINGS["user"]["email"]["host"])) layout.addWidget(QtWidgets.QLabel("Host"), row, 0) layout.addWidget(self.smtp_host, row, 1, 1, 3) # SMTP port row += 1 self.smtp_port = QtWidgets.QLineEdit(str(SETTINGS["user"]["email"]["port"])) self.port_validator = InputValidator(QRegExp("^[0-9]+$"), self.smtp_port, allow_empty=True) self.smtp_port.setValidator(self.port_validator) layout.addWidget(QtWidgets.QLabel("Port"), row, 0) layout.addWidget(self.smtp_port, row, 1, 1, 3) # SMTP SSL row += 1 self.smtp_ssl = QtWidgets.QCheckBox() if SETTINGS["user"]["email"]["ssl"]: self.smtp_ssl.setChecked(True) layout.addWidget(QtWidgets.QLabel("SSL"), row, 0) layout.addWidget(self.smtp_ssl, row, 1, 1, 3) # Model config row += 1 self.model_title = QtWidgets.QLabel("Model") self.model_title.setObjectName("settingsSectionTitle") layout.addWidget(self.model_title, row, 0, 1, 4) # Model language selection row += 1 self.model_language = QtWidgets.QComboBox() lang_options = get_model_languages() for opt in lang_options: self.model_language.addItem(opt, opt) self.model_language.setCurrentIndex(self.model_language.findData(SETTINGS["user"]["language"])) self.model_language.currentTextChanged.connect(self.language_changed) layout.addWidget(QtWidgets.QLabel("Language"), row, 0) layout.addWidget(self.model_language, row, 1, 1, 3) # Model language versions row += 1 self.model_lang_version = QtWidgets.QComboBox() version_options = get_language_versions(SETTINGS["user"]["language"]) for opt in version_options: self.model_lang_version.addItem(opt, opt) self.model_lang_version.setCurrentIndex(self.model_lang_version.findData(SETTINGS["user"]["language_version"])) layout.addWidget(QtWidgets.QLabel("Version"), row, 0) layout.addWidget(self.model_lang_version, row, 1, 1, 3) # empty row row += 1 layout.addWidget(QtWidgets.QLabel(""), row, 0, 1, 4) # Button row # Update and restore row += 1 button_row = QtWidgets.QGridLayout() button_row.setHorizontalSpacing(10) submit_button = QtWidgets.QToolButton() submit_button.setText("Update") submit_button.clicked.connect(self.submit_on_click) restore_button = QtWidgets.QToolButton() restore_button.setText("Restore") restore_button.clicked.connect(self.restore_on_click) button_row.addWidget(submit_button, 0, 3) button_row.addWidget(restore_button, 0, 2) layout.addLayout(button_row, row, 1) # If needed make space below empty row += 1 layout.addWidget(QtWidgets.QLabel(""), row, 0) layout.setRowStretch(row, 1) layout.setColumnStretch(1, 1) self.setLayout(main_layout) widget.setLayout(layout) scroll_area.setWidget(widget) @pyqtSlot() def language_changed(self): """ Update the version options whenever the user selects another language """ version_options = get_language_versions(self.model_language.currentData()) self.model_lang_version.clear() for opt in version_options: self.model_lang_version.addItem(opt, opt) self.model_lang_version.setCurrentIndex(0) @pyqtSlot() def is_empty(self): """ Checks if the text in the widget is empty and updates the empty state """ if self.sender() == self.name: if self.name.text() == "": self.empty_fields["name"] = True self.name.setProperty("invalid", True) else: self.empty_fields["name"] = False self.name.setProperty("invalid", False) self.name.style().unpolish(self.name) self.name.style().polish(self.name) @pyqtSlot() def restore_on_click(self): """ Restores the users settings to the initial values loaded from config """ # Editor self.theme.setCurrentIndex(self.theme.findData(self.initial_state["editor"]["theme"])) self.font_family.setText(self.initial_state["editor"]["font-family"]) self.font_size.setText(self.initial_state["editor"]["font-size"]) # Meetings self.standard_duration.setText(str(self.initial_state["meeting"]["standard_duration"])) # User self.name.setText(self.initial_state["user"]["name"]) self.email_address.setText(self.initial_state["user"]["email"]["address"]) self.email_password.setText("") # SMTP self.smtp_username.setText(self.initial_state["user"]["email"]["username"]) self.smtp_host.setText(self.initial_state["user"]["email"]["host"]) self.smtp_port.setText(str(self.initial_state["user"]["email"]["port"])) self.smtp_ssl.setChecked(self.initial_state["user"]["email"]["ssl"]) # Model self.model_language.setCurrentIndex(self.model_language.findData(self.initial_state["user"]["language"])) self.model_lang_version.setCurrentIndex( self.model_lang_version.findData(self.initial_state["user"]["language_version"]) ) self.main_window.set_info_message("Restored settings.") def valid_fields(self): """ Returns a boolean indicating if all the settings are valid """ form_states = [] state, _, _ = self.std_dur_validator.validate(self.standard_duration.text(), 0) form_states.append(state) state, _, _ = self.font_size_validator.validate(self.font_size.text(), 0) form_states.append(state) state, _, _ = self.email_validator.validate(self.email_address.text(), 0) form_states.append(state) state, _, _ = self.port_validator.validate(self.smtp_port.text(), 0) form_states.append(state) # If any of the settings contain invalid input or are empty dont update # settings invalid_form_states = [state for state in form_states if state != VALID] if len(invalid_form_states) or True in self.empty_fields.values(): return False return True @pyqtSlot() def submit_on_click(self): """ Update the users config files if all the settings are valid and the required fields are not empty. """ if not self.valid_fields(): self.main_window.set_info_message("Failed to update settings. Some fields are either invalid or empty.") return crypt = Crypt() # Editor SETTINGS["editor"]["theme"] = self.theme.currentData() SETTINGS["editor"]["font-family"] = self.font_family.text() SETTINGS["editor"]["font-size"] = self.font_size.text() update_settings(os.path.abspath("config/editor"), SETTINGS["editor"]) # Meetings SETTINGS["meeting"]["standard_duration"] = int(self.standard_duration.text()) update_settings(os.path.abspath("config/meetings"), SETTINGS["meeting"]) # User SETTINGS["user"]["name"] = self.name.text() SETTINGS["user"]["email"] = { "address": self.email_address.text(), "host": self.smtp_host.text(), # Only update password if a new password was given "password": <PASSWORD>.encrypt(self.email_password.text()) if self.email_password.text() != "" else self.initial_state["user"]["email"]["password"], "port": int(self.smtp_port.text()), "ssl": self.smtp_ssl.isChecked(), "username": self.smtp_username.text(), } SETTINGS["user"]["language"] = self.model_language.currentData() SETTINGS["user"]["language_version"] = self.model_lang_version.currentData() update_settings(os.path.abspath("config/user"), SETTINGS["user"]) self.main_window.set_info_message("Updated settings.") self.email_password.setText("") # show placeholder again # NOTE(alexander): DEV mode entry point only!!! if __name__ == "__main__": from main import initialize_app appctxt, window = initialize_app() window.set_active_view(4) exit_code = appctxt.app.exec_() sys.exit(exit_code)
src/main/python/settings_view.py
from PyQt5 import QtWidgets from PyQt5.QtCore import QRegExp, pyqtSlot from PyQt5.QtGui import QRegExpValidator, QValidator import os import sys from lib.settings import SETTINGS, get_language_versions, get_model_languages, update_settings from lib.utils.crypt import Crypt VALID = 2 # value of state enum representing valid state after validation EMAIL_REGEX = "^([a-zA-Z0-9]+[\\._-]?[a-zA-Z0-9]+)[@](\\w+[.])+\\w{2,3}$" class InputValidator(QRegExpValidator): """ A custom validator class that will set mark the parent object as invalid if the validator fails. """ def __init__(self, *args, allow_empty=False, **kwargs): super().__init__(*args, **kwargs) self.allow_empty = allow_empty def validate(self, text: str, pos: int): state, text, pos = super(InputValidator, self).validate(text, pos) selector = { QValidator.Invalid: "invalid", QValidator.Intermediate: "intermediate", QValidator.Acceptable: "acceptable", }[state] if selector == "invalid" or (not self.allow_empty and selector == "intermediate"): self.parent().setProperty("invalid", True) else: self.parent().setProperty("invalid", False) self.parent().style().unpolish(self.parent()) self.parent().style().polish(self.parent()) return state, text, pos class SettingsView(QtWidgets.QWidget): # Dict containing the fields which are not allowed to be submitted empty empty_fields = {"name": False} def __init__(self, main_window, *args, **kwargs): super(SettingsView, self).__init__(*args, **kwargs) self.main_window = main_window scroll_area = QtWidgets.QScrollArea() scroll_area.setMaximumWidth(960) scroll_area.setWidgetResizable(True) main_layout = QtWidgets.QHBoxLayout() main_layout.addWidget(scroll_area) widget = QtWidgets.QWidget() widget.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) layout = QtWidgets.QGridLayout() layout.setVerticalSpacing(8) self.initial_state = SETTINGS # store the settings to restore it if needed self.title = QtWidgets.QLabel("Settings") self.title.setObjectName("viewTitle") self.title.setMinimumHeight(48) row = 0 layout.addWidget(self.title, row, 0, 1, 4) # Editor settings row += 1 self.editor_title = QtWidgets.QLabel("Editor") self.editor_title.setObjectName("settingsSectionTitle") layout.addWidget(self.editor_title, row, 0, 1, 4) row += 1 self.theme = QtWidgets.QComboBox() self.theme.addItem("Light Theme", "light-theme") self.theme.addItem("Dark Theme", "dark-theme") self.theme.setCurrentIndex(self.theme.findData(SETTINGS["editor"]["theme"])) layout.addWidget(QtWidgets.QLabel("Theme"), row, 0) layout.addWidget(self.theme, row, 1, 1, 3) row += 1 self.font_family = QtWidgets.QLineEdit(SETTINGS["editor"]["font-family"]) layout.addWidget(QtWidgets.QLabel("Font"), row, 0) layout.addWidget(self.font_family, row, 1, 1, 3) row += 1 self.font_size = QtWidgets.QLineEdit(SETTINGS["editor"]["font-size"]) layout.addWidget(QtWidgets.QLabel("Font size"), row, 0) self.font_size_validator = InputValidator(QRegExp("^[0-9]+$"), self.font_size) self.font_size.setValidator(self.font_size_validator) layout.addWidget(self.font_size, row, 1, 1, 3) # Meeting settings row += 1 self.meetings_title = QtWidgets.QLabel("Meetings") self.meetings_title.setObjectName("settingsSectionTitle") layout.addWidget(self.meetings_title, row, 0, 1, 4) row += 1 self.standard_duration = QtWidgets.QLineEdit(str(SETTINGS["meeting"]["standard_duration"])) self.std_dur_validator = InputValidator(QRegExp("^[0-9]+$"), self.standard_duration) self.standard_duration.setValidator(self.std_dur_validator) layout.addWidget(QtWidgets.QLabel("Standard duration (min)"), row, 0) layout.addWidget(self.standard_duration, row, 1, 1, 3) # User settings section row += 1 self.email_title = QtWidgets.QLabel("User") self.email_title.setObjectName("settingsSectionTitle") layout.addWidget(self.email_title, row, 0, 1, 4) # Name row += 1 self.name = QtWidgets.QLineEdit(str(SETTINGS["user"]["name"])) self.name.textChanged.connect(self.is_empty) layout.addWidget(QtWidgets.QLabel("Name"), row, 0) layout.addWidget(self.name, row, 1, 1, 3) # Email row += 1 self.email_address = QtWidgets.QLineEdit(str(SETTINGS["user"]["email"]["address"])) self.email_validator = InputValidator(QRegExp(EMAIL_REGEX), self.email_address) self.email_address.setValidator(self.email_validator) layout.addWidget(QtWidgets.QLabel("Email"), row, 0) layout.addWidget(self.email_address, row, 1, 1, 3) # SMTP server section row += 1 self.smtp_title = QtWidgets.QLabel("SMTP server") self.smtp_title.setObjectName("settingsSectionTitle") layout.addWidget(self.smtp_title, row, 0, 1, 4) # SMTP username (email) row += 1 conf_username = SETTINGS["user"]["email"]["username"] self.smtp_username = QtWidgets.QLineEdit(str(conf_username)) layout.addWidget(QtWidgets.QLabel("Username"), row, 0) layout.addWidget(self.smtp_username, row, 1, 1, 3) # SMTP password (email) row += 1 self.email_password = QtWidgets.QLineEdit() self.email_password.setPlaceholderText("<PASSWORD>") self.email_password.setEchoMode(QtWidgets.QLineEdit.Password) layout.addWidget(QtWidgets.QLabel("Password"), row, 0) layout.addWidget(self.email_password, row, 1, 1, 3) # SMTP host row += 1 self.smtp_host = QtWidgets.QLineEdit(str(SETTINGS["user"]["email"]["host"])) layout.addWidget(QtWidgets.QLabel("Host"), row, 0) layout.addWidget(self.smtp_host, row, 1, 1, 3) # SMTP port row += 1 self.smtp_port = QtWidgets.QLineEdit(str(SETTINGS["user"]["email"]["port"])) self.port_validator = InputValidator(QRegExp("^[0-9]+$"), self.smtp_port, allow_empty=True) self.smtp_port.setValidator(self.port_validator) layout.addWidget(QtWidgets.QLabel("Port"), row, 0) layout.addWidget(self.smtp_port, row, 1, 1, 3) # SMTP SSL row += 1 self.smtp_ssl = QtWidgets.QCheckBox() if SETTINGS["user"]["email"]["ssl"]: self.smtp_ssl.setChecked(True) layout.addWidget(QtWidgets.QLabel("SSL"), row, 0) layout.addWidget(self.smtp_ssl, row, 1, 1, 3) # Model config row += 1 self.model_title = QtWidgets.QLabel("Model") self.model_title.setObjectName("settingsSectionTitle") layout.addWidget(self.model_title, row, 0, 1, 4) # Model language selection row += 1 self.model_language = QtWidgets.QComboBox() lang_options = get_model_languages() for opt in lang_options: self.model_language.addItem(opt, opt) self.model_language.setCurrentIndex(self.model_language.findData(SETTINGS["user"]["language"])) self.model_language.currentTextChanged.connect(self.language_changed) layout.addWidget(QtWidgets.QLabel("Language"), row, 0) layout.addWidget(self.model_language, row, 1, 1, 3) # Model language versions row += 1 self.model_lang_version = QtWidgets.QComboBox() version_options = get_language_versions(SETTINGS["user"]["language"]) for opt in version_options: self.model_lang_version.addItem(opt, opt) self.model_lang_version.setCurrentIndex(self.model_lang_version.findData(SETTINGS["user"]["language_version"])) layout.addWidget(QtWidgets.QLabel("Version"), row, 0) layout.addWidget(self.model_lang_version, row, 1, 1, 3) # empty row row += 1 layout.addWidget(QtWidgets.QLabel(""), row, 0, 1, 4) # Button row # Update and restore row += 1 button_row = QtWidgets.QGridLayout() button_row.setHorizontalSpacing(10) submit_button = QtWidgets.QToolButton() submit_button.setText("Update") submit_button.clicked.connect(self.submit_on_click) restore_button = QtWidgets.QToolButton() restore_button.setText("Restore") restore_button.clicked.connect(self.restore_on_click) button_row.addWidget(submit_button, 0, 3) button_row.addWidget(restore_button, 0, 2) layout.addLayout(button_row, row, 1) # If needed make space below empty row += 1 layout.addWidget(QtWidgets.QLabel(""), row, 0) layout.setRowStretch(row, 1) layout.setColumnStretch(1, 1) self.setLayout(main_layout) widget.setLayout(layout) scroll_area.setWidget(widget) @pyqtSlot() def language_changed(self): """ Update the version options whenever the user selects another language """ version_options = get_language_versions(self.model_language.currentData()) self.model_lang_version.clear() for opt in version_options: self.model_lang_version.addItem(opt, opt) self.model_lang_version.setCurrentIndex(0) @pyqtSlot() def is_empty(self): """ Checks if the text in the widget is empty and updates the empty state """ if self.sender() == self.name: if self.name.text() == "": self.empty_fields["name"] = True self.name.setProperty("invalid", True) else: self.empty_fields["name"] = False self.name.setProperty("invalid", False) self.name.style().unpolish(self.name) self.name.style().polish(self.name) @pyqtSlot() def restore_on_click(self): """ Restores the users settings to the initial values loaded from config """ # Editor self.theme.setCurrentIndex(self.theme.findData(self.initial_state["editor"]["theme"])) self.font_family.setText(self.initial_state["editor"]["font-family"]) self.font_size.setText(self.initial_state["editor"]["font-size"]) # Meetings self.standard_duration.setText(str(self.initial_state["meeting"]["standard_duration"])) # User self.name.setText(self.initial_state["user"]["name"]) self.email_address.setText(self.initial_state["user"]["email"]["address"]) self.email_password.setText("") # SMTP self.smtp_username.setText(self.initial_state["user"]["email"]["username"]) self.smtp_host.setText(self.initial_state["user"]["email"]["host"]) self.smtp_port.setText(str(self.initial_state["user"]["email"]["port"])) self.smtp_ssl.setChecked(self.initial_state["user"]["email"]["ssl"]) # Model self.model_language.setCurrentIndex(self.model_language.findData(self.initial_state["user"]["language"])) self.model_lang_version.setCurrentIndex( self.model_lang_version.findData(self.initial_state["user"]["language_version"]) ) self.main_window.set_info_message("Restored settings.") def valid_fields(self): """ Returns a boolean indicating if all the settings are valid """ form_states = [] state, _, _ = self.std_dur_validator.validate(self.standard_duration.text(), 0) form_states.append(state) state, _, _ = self.font_size_validator.validate(self.font_size.text(), 0) form_states.append(state) state, _, _ = self.email_validator.validate(self.email_address.text(), 0) form_states.append(state) state, _, _ = self.port_validator.validate(self.smtp_port.text(), 0) form_states.append(state) # If any of the settings contain invalid input or are empty dont update # settings invalid_form_states = [state for state in form_states if state != VALID] if len(invalid_form_states) or True in self.empty_fields.values(): return False return True @pyqtSlot() def submit_on_click(self): """ Update the users config files if all the settings are valid and the required fields are not empty. """ if not self.valid_fields(): self.main_window.set_info_message("Failed to update settings. Some fields are either invalid or empty.") return crypt = Crypt() # Editor SETTINGS["editor"]["theme"] = self.theme.currentData() SETTINGS["editor"]["font-family"] = self.font_family.text() SETTINGS["editor"]["font-size"] = self.font_size.text() update_settings(os.path.abspath("config/editor"), SETTINGS["editor"]) # Meetings SETTINGS["meeting"]["standard_duration"] = int(self.standard_duration.text()) update_settings(os.path.abspath("config/meetings"), SETTINGS["meeting"]) # User SETTINGS["user"]["name"] = self.name.text() SETTINGS["user"]["email"] = { "address": self.email_address.text(), "host": self.smtp_host.text(), # Only update password if a new password was given "password": <PASSWORD>.encrypt(self.email_password.text()) if self.email_password.text() != "" else self.initial_state["user"]["email"]["password"], "port": int(self.smtp_port.text()), "ssl": self.smtp_ssl.isChecked(), "username": self.smtp_username.text(), } SETTINGS["user"]["language"] = self.model_language.currentData() SETTINGS["user"]["language_version"] = self.model_lang_version.currentData() update_settings(os.path.abspath("config/user"), SETTINGS["user"]) self.main_window.set_info_message("Updated settings.") self.email_password.setText("") # show placeholder again # NOTE(alexander): DEV mode entry point only!!! if __name__ == "__main__": from main import initialize_app appctxt, window = initialize_app() window.set_active_view(4) exit_code = appctxt.app.exec_() sys.exit(exit_code)
0.454714
0.147156
__author__ = '<NAME>' from typing import List, Set, Type, Iterable, Tuple from dataclasses import dataclass, field import logging from spacy.tokens.doc import Doc from spacy.tokens.span import Span from zensols.config import Dictable from . import ( ParseError, LanguageResource, TokenFeatures, FeatureToken, FeatureSentence, FeatureDocument, ) logger = logging.getLogger(__name__) @dataclass class FeatureDocumentParser(Dictable): """This class parses text in to instances of :class:`.FeatureDocument` instances. """ TOKEN_FEATURE_IDS = FeatureToken.TOKEN_FEATURE_IDS """The default value for :obj:`token_feature_ids`.""" name: str = field() """The name of the parser, which is used for errors and logging.""" langres: LanguageResource = field() """The language resource used to parse documents and create token attributes. """ token_feature_ids: Set[str] = field( default_factory=lambda: FeatureDocumentParser.TOKEN_FEATURE_IDS) """The features to keep from spaCy tokens. :see: :obj:`TOKEN_FEATURE_IDS` """ doc_class: Type[FeatureDocument] = field(default=FeatureDocument) """The type of document instances to create.""" sent_class: Type[FeatureSentence] = field(default=FeatureSentence) """The type of sentence instances to create.""" token_class: Type[FeatureToken] = field(default=FeatureToken) """The type of document instances to create.""" remove_empty_sentences: bool = field(default=False) """If ``True``, remove sentences that only have space tokens.""" def __post_init__(self): pass def _create_token(self, feature: TokenFeatures) -> FeatureToken: return self.token_class(feature, self.token_feature_ids) def _create_sent(self, spacy_sent: Span, stoks: Iterable[TokenFeatures], text: str) -> FeatureSentence: sent = tuple(map(self._create_token, stoks)) sent = self.sent_class(sent, text) return sent def _from_string(self, text: str) -> Tuple[Doc, List[FeatureSentence]]: """Parse a document from a string. """ lr: LanguageResource = self.langres doc: Doc = lr.parse(text) toks: Tuple[TokenFeatures] = tuple(lr.features(doc)) ntoks = len(toks) tix = 0 sents = [] sent: Span for sent in doc.sents: if self.remove_empty_sentences and \ (all(map(lambda t: t.is_space, sent)) or len(sent) == 0): continue e = sent[-1].i stoks = [] while tix < ntoks: tok = toks[tix] if tok.i <= e: stoks.append(tok) else: break tix += 1 sents.append(self._create_sent(sent, stoks, sent.text)) return doc, sents def parse(self, text: str, *args, **kwargs) -> FeatureDocument: """Parse text or a text as a list of sentences. :param text: either a string or a list of strings; if the former a document with one sentence will be created, otherwise a document is returned with a sentence for each string in the list """ if not isinstance(text, str): raise ParseError(f'Expecting string text but got: {text}') spacy_doc, sents = self._from_string(text) try: return self.doc_class(sents, spacy_doc, *args, **kwargs) except Exception as e: raise ParseError( f'Could not parse <{text}> for {self.doc_class} ' + f"with args {args} for parser '{self.name}'") from e def __call__(self, text: str, *args, **kwargs) -> FeatureDocument: return self.parse(text, *args, **kwargs)
src/python/zensols/nlp/docparser.py
__author__ = '<NAME>' from typing import List, Set, Type, Iterable, Tuple from dataclasses import dataclass, field import logging from spacy.tokens.doc import Doc from spacy.tokens.span import Span from zensols.config import Dictable from . import ( ParseError, LanguageResource, TokenFeatures, FeatureToken, FeatureSentence, FeatureDocument, ) logger = logging.getLogger(__name__) @dataclass class FeatureDocumentParser(Dictable): """This class parses text in to instances of :class:`.FeatureDocument` instances. """ TOKEN_FEATURE_IDS = FeatureToken.TOKEN_FEATURE_IDS """The default value for :obj:`token_feature_ids`.""" name: str = field() """The name of the parser, which is used for errors and logging.""" langres: LanguageResource = field() """The language resource used to parse documents and create token attributes. """ token_feature_ids: Set[str] = field( default_factory=lambda: FeatureDocumentParser.TOKEN_FEATURE_IDS) """The features to keep from spaCy tokens. :see: :obj:`TOKEN_FEATURE_IDS` """ doc_class: Type[FeatureDocument] = field(default=FeatureDocument) """The type of document instances to create.""" sent_class: Type[FeatureSentence] = field(default=FeatureSentence) """The type of sentence instances to create.""" token_class: Type[FeatureToken] = field(default=FeatureToken) """The type of document instances to create.""" remove_empty_sentences: bool = field(default=False) """If ``True``, remove sentences that only have space tokens.""" def __post_init__(self): pass def _create_token(self, feature: TokenFeatures) -> FeatureToken: return self.token_class(feature, self.token_feature_ids) def _create_sent(self, spacy_sent: Span, stoks: Iterable[TokenFeatures], text: str) -> FeatureSentence: sent = tuple(map(self._create_token, stoks)) sent = self.sent_class(sent, text) return sent def _from_string(self, text: str) -> Tuple[Doc, List[FeatureSentence]]: """Parse a document from a string. """ lr: LanguageResource = self.langres doc: Doc = lr.parse(text) toks: Tuple[TokenFeatures] = tuple(lr.features(doc)) ntoks = len(toks) tix = 0 sents = [] sent: Span for sent in doc.sents: if self.remove_empty_sentences and \ (all(map(lambda t: t.is_space, sent)) or len(sent) == 0): continue e = sent[-1].i stoks = [] while tix < ntoks: tok = toks[tix] if tok.i <= e: stoks.append(tok) else: break tix += 1 sents.append(self._create_sent(sent, stoks, sent.text)) return doc, sents def parse(self, text: str, *args, **kwargs) -> FeatureDocument: """Parse text or a text as a list of sentences. :param text: either a string or a list of strings; if the former a document with one sentence will be created, otherwise a document is returned with a sentence for each string in the list """ if not isinstance(text, str): raise ParseError(f'Expecting string text but got: {text}') spacy_doc, sents = self._from_string(text) try: return self.doc_class(sents, spacy_doc, *args, **kwargs) except Exception as e: raise ParseError( f'Could not parse <{text}> for {self.doc_class} ' + f"with args {args} for parser '{self.name}'") from e def __call__(self, text: str, *args, **kwargs) -> FeatureDocument: return self.parse(text, *args, **kwargs)
0.883883
0.390708
import argparse import os import tempfile import time import typing import webbrowser from difflib import SequenceMatcher from pathlib import Path from sys import platform from warnings import warn import easyocr import numpy as np from mss import mss from mutagen.wave import WAVE from PIL import Image from sclog import getLogger from screeninfo import get_monitors logger = getLogger(__name__) def open_chrome(url: str): """ Open Chrome on the current OS webbrowser opening via https://stackoverflow.com/a/24353812 os determination via https://stackoverflow.com/a/8220141 """ if platform == "linux" or platform == "linux2": chrome_path = "/usr/bin/google-chrome %s" elif platform == "darwin": chrome_path = "open -a /Applications/Google\ Chrome.app %s" elif platform == "win32": chrome_path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s" logger.debug("opening Chrome at %s to %s", chrome_path, url) return webbrowser.get(chrome_path).open(url, new=1) def transcribe( filename="recordings/v1/recording1.wav", screenshot_directory: Path = Path(), ): url = "file://" + os.path.realpath(filename) open_chrome(url) sleep_time_seconds = 2 logger.debug("waiting %i seconds for the browser to launch", sleep_time_seconds) time.sleep(sleep_time_seconds) logger.debug("preparing easyocr") reader = easyocr.Reader(["en"]) logger.debug("loading input file (%s) to get metadata", filename) audio = WAVE(filename) audio_time = int(audio.info.length) logger.debug("the file to transcribe is %i seconds long", audio_time) monitor = get_monitors()[0] width = monitor.width height = monitor.height logger.debug("the current monitor's dimensions are %i by %i", width, height) bounding_box = { "top": int(height * 3 / 4), "left": int(width / 4), "width": int(width / 2), "height": int(height * 1 / 4), } logger.debug("the bounding box for screen capture is %s", str(bounding_box)) audio_start = time.time() images = [] i = 0 logger.debug("beginning screen capture (will continue for %i seconds)", audio_time) curr_time = 0 with mss() as sct: while curr_time < audio_time: start = time.time() i += 1 img = np.asarray(sct.grab(bounding_box)) if i % 4 == 0: im = Image.fromarray(img).convert("RGB") screenshot_filename = f"screenshot{curr_time}.jpeg" screenshot_path = screenshot_directory / screenshot_filename im.save(screenshot_path) images.append(img) time.sleep(1) end = time.time() curr_time += end - start elapsed_time = time.time() - audio_start logger.debug( "Finished screen capture. Captured %i images over %i minutes %i seconds", len(images), elapsed_time / 60, elapsed_time % 60, ) logger.debug("extracting text from screenshots") res_text = [] for image in images: read_res = reader.readtext(image) read_buffer = "" for item in read_res: data, text, prob = item logger.debug("%s %s %f", data, text, prob) if prob > 0.7: read_buffer += " " + text read_buffer = read_buffer.strip() if read_buffer: res_text.append(read_buffer) logger.debug("raw text captured: %s", res_text) logger.debug("Computing Dedup") phrases = compute_deduped_phrases(res_text) logger.debug("Completed dedup phase 1 with %s", phrases) merged_phrases = compute_merged_phrases_deduped(phrases) logger.debug("Completed dedup phase 2 with %s", merged_phrases) result = ". ".join(merged_phrases) logger.info("transcription: %s", result) return result def compute_deduped_phrases(buffer): # buffer: list[str] # Merge common phrases based on last substring i = 1 phrases = [] start_token = "Live Caption" prev_matched_region = "" while i < len(buffer): string1 = buffer[i - 1].strip() string2 = buffer[i].strip() string1 = string1.replace(start_token, "") # Removes Live Caption phrase string2 = string2.replace(start_token, "") # Removes Live Caption phrase match = SequenceMatcher(None, string1, string2).find_longest_match( 0, len(string1), 0, len(string2) ) matched_region = string1[match.a : match.a + match.size].strip() if prev_matched_region and prev_matched_region in matched_region: if len(phrases) > 1 and phrases[-1] in prev_matched_region: # Case where last phrases contains a portion of last matched region # Remove the last entry to remove aliasing phrases.pop() phrases.append(prev_matched_region) prev_matched_region = matched_region i += 1 phrases.append(prev_matched_region) return phrases def merge(s1, s2): # Merges s1 with s2 based on end of s1 to start of s2 # This function is pretty slow as it's run on a buffer that's not too long # TODO Optimization start from the end and go backwards i = 0 found_match = True while not s2.startswith(s1[i:]): i += 1 if i == len(s1): found_match = False break return s1[:i] + s2, found_match def compute_merged_phrases_deduped(phrases): # phrases: list[str] # Merge phrases that have common ending such as # "We ate food" + "ate food quickly" -> "We ate food quickly" j = 1 merged_phrases = [] prev_phrase = phrases[0] while j < len(phrases): curr_phrase = phrases[j] merged_phrase, found_match = merge(prev_phrase, curr_phrase) if not found_match: # End of merge sequence. Set prev_phase to current and repeat merged_phrases.append(prev_phrase) prev_phrase = curr_phrase else: prev_phrase = merged_phrase j += 1 merged_phrases.append(prev_phrase) return merged_phrases if __name__ == "__main__": parser = argparse.ArgumentParser(description="transcribe given WAV file") parser.add_argument("filename", help="the name of the file to transcribe") parser.add_argument( "--screenshot-dir", required=False, help="directory to store screenshot files" ) args = parser.parse_args() filename = args.filename output_filename = filename + ".txt" output_path = Path(output_filename) if output_path.exists(): warn(f"output file {output_path} already exists") input_file_path = Path(filename) if input_file_path.suffix != ".wav": raise ValueError( f"transcription requires a .wav file, and {input_file_path} doesn't seem to be one" ) screenshot_dir = args.screenshot_dir if screenshot_dir is None: screenshot_dir = Path(tempfile.mkdtemp()) else: screenshot_dir = Path(args.screenshot_dir) logger.debug("will save screenshots to %s", screenshot_dir) transcription = transcribe(filename, screenshot_dir) print(transcription) with open(output_path, "w") as output: output.write(transcription)
transcribe_chrome/src/audio2text.py
import argparse import os import tempfile import time import typing import webbrowser from difflib import SequenceMatcher from pathlib import Path from sys import platform from warnings import warn import easyocr import numpy as np from mss import mss from mutagen.wave import WAVE from PIL import Image from sclog import getLogger from screeninfo import get_monitors logger = getLogger(__name__) def open_chrome(url: str): """ Open Chrome on the current OS webbrowser opening via https://stackoverflow.com/a/24353812 os determination via https://stackoverflow.com/a/8220141 """ if platform == "linux" or platform == "linux2": chrome_path = "/usr/bin/google-chrome %s" elif platform == "darwin": chrome_path = "open -a /Applications/Google\ Chrome.app %s" elif platform == "win32": chrome_path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s" logger.debug("opening Chrome at %s to %s", chrome_path, url) return webbrowser.get(chrome_path).open(url, new=1) def transcribe( filename="recordings/v1/recording1.wav", screenshot_directory: Path = Path(), ): url = "file://" + os.path.realpath(filename) open_chrome(url) sleep_time_seconds = 2 logger.debug("waiting %i seconds for the browser to launch", sleep_time_seconds) time.sleep(sleep_time_seconds) logger.debug("preparing easyocr") reader = easyocr.Reader(["en"]) logger.debug("loading input file (%s) to get metadata", filename) audio = WAVE(filename) audio_time = int(audio.info.length) logger.debug("the file to transcribe is %i seconds long", audio_time) monitor = get_monitors()[0] width = monitor.width height = monitor.height logger.debug("the current monitor's dimensions are %i by %i", width, height) bounding_box = { "top": int(height * 3 / 4), "left": int(width / 4), "width": int(width / 2), "height": int(height * 1 / 4), } logger.debug("the bounding box for screen capture is %s", str(bounding_box)) audio_start = time.time() images = [] i = 0 logger.debug("beginning screen capture (will continue for %i seconds)", audio_time) curr_time = 0 with mss() as sct: while curr_time < audio_time: start = time.time() i += 1 img = np.asarray(sct.grab(bounding_box)) if i % 4 == 0: im = Image.fromarray(img).convert("RGB") screenshot_filename = f"screenshot{curr_time}.jpeg" screenshot_path = screenshot_directory / screenshot_filename im.save(screenshot_path) images.append(img) time.sleep(1) end = time.time() curr_time += end - start elapsed_time = time.time() - audio_start logger.debug( "Finished screen capture. Captured %i images over %i minutes %i seconds", len(images), elapsed_time / 60, elapsed_time % 60, ) logger.debug("extracting text from screenshots") res_text = [] for image in images: read_res = reader.readtext(image) read_buffer = "" for item in read_res: data, text, prob = item logger.debug("%s %s %f", data, text, prob) if prob > 0.7: read_buffer += " " + text read_buffer = read_buffer.strip() if read_buffer: res_text.append(read_buffer) logger.debug("raw text captured: %s", res_text) logger.debug("Computing Dedup") phrases = compute_deduped_phrases(res_text) logger.debug("Completed dedup phase 1 with %s", phrases) merged_phrases = compute_merged_phrases_deduped(phrases) logger.debug("Completed dedup phase 2 with %s", merged_phrases) result = ". ".join(merged_phrases) logger.info("transcription: %s", result) return result def compute_deduped_phrases(buffer): # buffer: list[str] # Merge common phrases based on last substring i = 1 phrases = [] start_token = "Live Caption" prev_matched_region = "" while i < len(buffer): string1 = buffer[i - 1].strip() string2 = buffer[i].strip() string1 = string1.replace(start_token, "") # Removes Live Caption phrase string2 = string2.replace(start_token, "") # Removes Live Caption phrase match = SequenceMatcher(None, string1, string2).find_longest_match( 0, len(string1), 0, len(string2) ) matched_region = string1[match.a : match.a + match.size].strip() if prev_matched_region and prev_matched_region in matched_region: if len(phrases) > 1 and phrases[-1] in prev_matched_region: # Case where last phrases contains a portion of last matched region # Remove the last entry to remove aliasing phrases.pop() phrases.append(prev_matched_region) prev_matched_region = matched_region i += 1 phrases.append(prev_matched_region) return phrases def merge(s1, s2): # Merges s1 with s2 based on end of s1 to start of s2 # This function is pretty slow as it's run on a buffer that's not too long # TODO Optimization start from the end and go backwards i = 0 found_match = True while not s2.startswith(s1[i:]): i += 1 if i == len(s1): found_match = False break return s1[:i] + s2, found_match def compute_merged_phrases_deduped(phrases): # phrases: list[str] # Merge phrases that have common ending such as # "We ate food" + "ate food quickly" -> "We ate food quickly" j = 1 merged_phrases = [] prev_phrase = phrases[0] while j < len(phrases): curr_phrase = phrases[j] merged_phrase, found_match = merge(prev_phrase, curr_phrase) if not found_match: # End of merge sequence. Set prev_phase to current and repeat merged_phrases.append(prev_phrase) prev_phrase = curr_phrase else: prev_phrase = merged_phrase j += 1 merged_phrases.append(prev_phrase) return merged_phrases if __name__ == "__main__": parser = argparse.ArgumentParser(description="transcribe given WAV file") parser.add_argument("filename", help="the name of the file to transcribe") parser.add_argument( "--screenshot-dir", required=False, help="directory to store screenshot files" ) args = parser.parse_args() filename = args.filename output_filename = filename + ".txt" output_path = Path(output_filename) if output_path.exists(): warn(f"output file {output_path} already exists") input_file_path = Path(filename) if input_file_path.suffix != ".wav": raise ValueError( f"transcription requires a .wav file, and {input_file_path} doesn't seem to be one" ) screenshot_dir = args.screenshot_dir if screenshot_dir is None: screenshot_dir = Path(tempfile.mkdtemp()) else: screenshot_dir = Path(args.screenshot_dir) logger.debug("will save screenshots to %s", screenshot_dir) transcription = transcribe(filename, screenshot_dir) print(transcription) with open(output_path, "w") as output: output.write(transcription)
0.228759
0.148355
SNAKE_TO_CAMEL_CASE_TABLE = { "access_ip_v4": "accessIpV4", "access_ip_v6": "accessIpV6", "access_key": "accessKey", "access_level": "accessLevel", "access_rules": "accessRules", "access_to": "accessTo", "access_type": "accessType", "address_scope_id": "addressScopeId", "admin_pass": "<PASSWORD>", "admin_state_up": "adminStateUp", "all_fixed_ips": "allFixedIps", "all_metadata": "allMetadata", "all_security_group_ids": "allSecurityGroupIds", "all_tags": "allTags", "allocation_pools": "allocationPools", "allocation_pools_collection": "allocationPoolsCollection", "allow_reauth": "allowReauth", "allowed_address_pairs": "allowedAddressPairs", "allowed_cidrs": "allowedCidrs", "api_address": "apiAddress", "apiserver_port": "apiserverPort", "application_credential_id": "applicationCredentialId", "application_credential_name": "applicationCredentialName", "application_credential_secret": "applicationCredentialSecret", "associated_routers": "associatedRouters", "attach_mode": "attachMode", "auth_algorithm": "authAlgorithm", "auth_url": "authUrl", "availability_zone": "availabilityZone", "availability_zone_hints": "availabilityZoneHints", "backup_gigabytes": "backupGigabytes", "bit_length": "bitLength", "block_devices": "blockDevices", "cacert_file": "cacertFile", "client_certificate": "clientCertificate", "client_key": "clientKey", "cluster_ca_certificate": "clusterCaCertificate", "cluster_distro": "clusterDistro", "cluster_template_id": "clusterTemplateId", "coe_version": "coeVersion", "compare_type": "compareType", "config_drive": "configDrive", "configuration_id": "configurationId", "conn_limit": "connLimit", "connection_limit": "connectionLimit", "consistency_group_id": "consistencyGroupId", "container_format": "containerFormat", "container_name": "containerName", "container_read": "containerRead", "container_ref": "containerRef", "container_sync_key": "containerSyncKey", "container_sync_to": "containerSyncTo", "container_version": "containerVersion", "container_write": "containerWrite", "content_disposition": "contentDisposition", "content_encoding": "contentEncoding", "content_length": "contentLength", "content_type": "contentType", "content_types": "contentTypes", "copy_from": "copyFrom", "create_timeout": "createTimeout", "created_at": "createdAt", "creation_time": "creationTime", "creator_id": "creatorId", "default_domain": "defaultDomain", "default_pool_id": "defaultPoolId", "default_prefixlen": "defaultPrefixlen", "default_project_id": "defaultProjectId", "default_quota": "defaultQuota", "default_tls_container_ref": "defaultTlsContainerRef", "delayed_auth": "delayedAuth", "delete_after": "deleteAfter", "delete_at": "deleteAt", "delete_default_rules": "deleteDefaultRules", "destination_cidr": "destinationCidr", "destination_ip_address": "destinationIpAddress", "destination_port": "destinationPort", "detect_content_type": "detectContentType", "device_id": "deviceId", "device_owner": "deviceOwner", "disable_no_cache_header": "disableNoCacheHeader", "disable_rollback": "disableRollback", "disable_status_check": "disableStatusCheck", "discovery_url": "discoveryUrl", "disk_format": "diskFormat", "dns_assignments": "dnsAssignments", "dns_domain": "dnsDomain", "dns_ip": "dnsIp", "dns_name": "dnsName", "dns_nameserver": "dnsNameserver", "dns_nameservers": "dnsNameservers", "docker_storage_driver": "dockerStorageDriver", "docker_volume_size": "dockerVolumeSize", "domain_id": "domainId", "domain_name": "domainName", "driver_volume_type": "driverVolumeType", "dscp_mark": "dscpMark", "enable_dhcp": "enableDhcp", "enable_online_resize": "enableOnlineResize", "enable_snat": "enableSnat", "encapsulation_mode": "encapsulationMode", "encryption_algorithm": "encryptionAlgorithm", "endpoint_overrides": "endpointOverrides", "endpoint_region": "endpointRegion", "endpoint_type": "endpointType", "environment_opts": "environmentOpts", "expected_codes": "expectedCodes", "expires_at": "expiresAt", "export_locations": "exportLocations", "external_fixed_ips": "externalFixedIps", "external_gateway": "externalGateway", "external_network_id": "externalNetworkId", "external_subnet_ids": "externalSubnetIds", "external_v4_ip": "externalV4Ip", "external_v6_ip": "externalV6Ip", "extra_dhcp_options": "extraDhcpOptions", "extra_specs": "extraSpecs", "fixed_ip": "fixedIp", "fixed_ips": "fixedIps", "fixed_network": "fixedNetwork", "fixed_subnet": "fixedSubnet", "flavor_id": "flavorId", "flavor_name": "flavorName", "floating_ip": "floatingIp", "floating_ip_enabled": "floatingIpEnabled", "floating_ips": "floatingIps", "force_delete": "forceDelete", "force_destroy": "forceDestroy", "gateway_ip": "gatewayIp", "group_id": "groupId", "has_replicas": "hasReplicas", "health_monitor": "healthMonitor", "host_name": "hostName", "host_routes": "hostRoutes", "http_method": "httpMethod", "http_proxy": "httpProxy", "https_proxy": "httpsProxy", "ignore_change_password_upon_first_use": "ignoreChangePasswordUponFirstUse", "ignore_lockout_failure_attempts": "ignoreLockoutFailureAttempts", "ignore_password_expiry": "ignorePasswordExpiry", "ike_version": "ikeVersion", "ikepolicy_id": "ikepolicyId", "image_cache_path": "imageCachePath", "image_id": "imageId", "image_name": "imageName", "image_source_password": "<PASSWORD>", "image_source_url": "imageSourceUrl", "image_source_username": "imageSourceUsername", "injected_file_content_bytes": "injectedFileContentBytes", "injected_file_path_bytes": "injectedFilePathBytes", "injected_files": "injectedFiles", "insecure_registry": "insecureRegistry", "insert_headers": "insertHeaders", "instance_id": "instanceId", "ip_address": "ipAddress", "ip_version": "ipVersion", "ipsecpolicy_id": "ipsecpolicyId", "ipv6_address_mode": "ipv6AddressMode", "ipv6_ra_mode": "ipv6RaMode", "is_default": "isDefault", "is_domain": "isDomain", "is_public": "isPublic", "key_pair": "keyPair", "key_pairs": "keyPairs", "keypair_id": "keypairId", "l7_policy": "l7Policy", "l7_rule": "l7Rule", "l7policy_id": "l7policyId", "last_modified": "lastModified", "lb_method": "lbMethod", "lb_provider": "lbProvider", "listener_id": "listenerId", "loadbalancer_id": "loadbalancerId", "loadbalancer_provider": "loadbalancerProvider", "local_ep_group_id": "localEpGroupId", "local_file_path": "localFilePath", "local_id": "localId", "mac_address": "macAddress", "master_addresses": "masterAddresses", "master_count": "masterCount", "master_flavor": "masterFlavor", "master_lb_enabled": "masterLbEnabled", "max_burst_kbps": "maxBurstKbps", "max_kbps": "maxKbps", "max_prefixlen": "maxPrefixlen", "max_retries": "maxRetries", "max_retries_down": "maxRetriesDown", "member_id": "memberId", "merge_labels": "mergeLabels", "metadata_items": "metadataItems", "min_disk_gb": "minDiskGb", "min_kbps": "minKbps", "min_prefixlen": "minPrefixlen", "min_ram_mb": "minRamMb", "monitor_ids": "monitorIds", "mount_point_base": "mountPointBase", "multi_factor_auth_enabled": "multiFactorAuthEnabled", "multi_factor_auth_rules": "multiFactorAuthRules", "network_driver": "networkDriver", "network_id": "networkId", "network_mode": "networkMode", "network_type": "networkType", "neutron_net_id": "neutronNetId", "neutron_subnet_id": "neutronSubnetId", "next_hop": "nextHop", "no_fixed_ip": "noFixedIp", "no_gateway": "noGateway", "no_proxy": "noProxy", "no_routers": "noRouters", "no_security_groups": "noSecurityGroups", "node_addresses": "nodeAddresses", "node_count": "nodeCount", "notification_topics": "notificationTopics", "object_id": "objectId", "object_manifest": "objectManifest", "object_type": "objectType", "order_ref": "orderRef", "os_type": "osType", "parent_id": "parentId", "payload_content_encoding": "payloadContentEncoding", "payload_content_type": "payloadContentType", "peer_address": "peerAddress", "peer_cidrs": "peerCidrs", "peer_ep_group_id": "peerEpGroupId", "peer_id": "peerId", "per_volume_gigabytes": "perVolumeGigabytes", "phase1_negotiation_mode": "phase1NegotiationMode", "policy_id": "policyId", "pool_id": "poolId", "port_id": "portId", "port_range_max": "portRangeMax", "port_range_min": "portRangeMin", "port_security_enabled": "portSecurityEnabled", "power_state": "powerState", "prefix_length": "prefixLength", "private_key": "privateKey", "project_domain_id": "projectDomainId", "project_domain_name": "projectDomainName", "project_id": "projectId", "protocol_port": "protocolPort", "public_key": "publicKey", "qos_policy_id": "qosPolicyId", "raw_config": "rawConfig", "rbac_policy": "rbacPolicy", "redirect_pool_id": "redirectPoolId", "redirect_url": "redirectUrl", "registry_enabled": "registryEnabled", "remote_group_id": "remoteGroupId", "remote_ip_prefix": "remoteIpPrefix", "replication_type": "replicationType", "revision_number": "revisionNumber", "role_id": "roleId", "router_id": "routerId", "rx_tx_factor": "rxTxFactor", "scheduler_hints": "schedulerHints", "secret_ref": "secretRef", "secret_refs": "secretRefs", "secret_type": "secretType", "security_group": "securityGroup", "security_group_id": "securityGroupId", "security_group_ids": "securityGroupIds", "security_group_rule": "securityGroupRule", "security_group_rules": "securityGroupRules", "security_groups": "securityGroups", "security_service_ids": "securityServiceIds", "segmentation_id": "segmentationId", "server_group_members": "serverGroupMembers", "server_groups": "serverGroups", "server_type": "serverType", "service_id": "serviceId", "service_name": "serviceName", "service_type": "serviceType", "share_id": "shareId", "share_network_id": "shareNetworkId", "share_proto": "shareProto", "share_server_id": "shareServerId", "share_type": "shareType", "size_bytes": "sizeBytes", "snapshot_id": "snapshotId", "sni_container_refs": "sniContainerRefs", "source_ip_address": "sourceIpAddress", "source_port": "sourcePort", "source_replica": "sourceReplica", "source_vol_id": "sourceVolId", "stack_id": "stackId", "stack_outputs": "StackOutputs", "status_reason": "statusReason", "stop_before_destroy": "stopBeforeDestroy", "sub_ports": "subPorts", "sub_status": "subStatus", "sub_status_message": "subStatusMessage", "subnet_id": "subnetId", "subnet_ids": "subnetIds", "subnetpool_id": "subnetpoolId", "target_tenant": "targetTenant", "template_description": "templateDescription", "template_opts": "templateOpts", "tenant_id": "tenantId", "tenant_name": "tenantName", "timeout_client_data": "timeoutClientData", "timeout_member_connect": "timeoutMemberConnect", "timeout_member_data": "timeoutMemberData", "timeout_tcp_inspect": "timeoutTcpInspect", "tls_disabled": "tlsDisabled", "trans_id": "transId", "transform_protocol": "transformProtocol", "transparent_vlan": "transparentVlan", "trust_id": "trustId", "update_at": "updateAt", "updated_at": "updatedAt", "updated_time": "updatedTime", "url_path": "urlPath", "use_octavia": "useOctavia", "user_data": "userData", "user_domain_id": "userDomainId", "user_domain_name": "userDomainName", "user_id": "userId", "user_name": "userName", "value_specs": "valueSpecs", "vendor_options": "vendorOptions", "verify_checksum": "verifyChecksum", "vip_address": "vipAddress", "vip_network_id": "vipNetworkId", "vip_port_id": "vipPortId", "vip_subnet_id": "vipSubnetId", "volume_driver": "volumeDriver", "volume_id": "volumeId", "volume_type": "volumeType", "volume_type_quota": "volumeTypeQuota", "vpnservice_id": "vpnserviceId", "wait_until_associated": "waitUntilAssociated", "web_download": "webDownload", "zone_id": "zoneId", } CAMEL_TO_SNAKE_CASE_TABLE = { "accessIpV4": "access_ip_v4", "accessIpV6": "access_ip_v6", "accessKey": "access_key", "accessLevel": "access_level", "accessRules": "access_rules", "accessTo": "access_to", "accessType": "access_type", "addressScopeId": "address_scope_id", "adminPass": "<PASSWORD>", "adminStateUp": "admin_state_up", "allFixedIps": "all_fixed_ips", "allMetadata": "all_metadata", "allSecurityGroupIds": "all_security_group_ids", "allTags": "all_tags", "allocationPools": "allocation_pools", "allocationPoolsCollection": "allocation_pools_collection", "allowReauth": "allow_reauth", "allowedAddressPairs": "allowed_address_pairs", "allowedCidrs": "allowed_cidrs", "apiAddress": "api_address", "apiserverPort": "apiserver_port", "applicationCredentialId": "application_credential_id", "applicationCredentialName": "application_credential_name", "applicationCredentialSecret": "application_credential_secret", "associatedRouters": "associated_routers", "attachMode": "attach_mode", "authAlgorithm": "auth_algorithm", "authUrl": "auth_url", "availabilityZone": "availability_zone", "availabilityZoneHints": "availability_zone_hints", "backupGigabytes": "backup_gigabytes", "bitLength": "bit_length", "blockDevices": "block_devices", "cacertFile": "cacert_file", "clientCertificate": "client_certificate", "clientKey": "client_key", "clusterCaCertificate": "cluster_ca_certificate", "clusterDistro": "cluster_distro", "clusterTemplateId": "cluster_template_id", "coeVersion": "coe_version", "compareType": "compare_type", "configDrive": "config_drive", "configurationId": "configuration_id", "connLimit": "conn_limit", "connectionLimit": "connection_limit", "consistencyGroupId": "consistency_group_id", "containerFormat": "container_format", "containerName": "container_name", "containerRead": "container_read", "containerRef": "container_ref", "containerSyncKey": "container_sync_key", "containerSyncTo": "container_sync_to", "containerVersion": "container_version", "containerWrite": "container_write", "contentDisposition": "content_disposition", "contentEncoding": "content_encoding", "contentLength": "content_length", "contentType": "content_type", "contentTypes": "content_types", "copyFrom": "copy_from", "createTimeout": "create_timeout", "createdAt": "created_at", "creationTime": "creation_time", "creatorId": "creator_id", "defaultDomain": "default_domain", "defaultPoolId": "default_pool_id", "defaultPrefixlen": "default_prefixlen", "defaultProjectId": "default_project_id", "defaultQuota": "default_quota", "defaultTlsContainerRef": "default_tls_container_ref", "delayedAuth": "delayed_auth", "deleteAfter": "delete_after", "deleteAt": "delete_at", "deleteDefaultRules": "delete_default_rules", "destinationCidr": "destination_cidr", "destinationIpAddress": "destination_ip_address", "destinationPort": "destination_port", "detectContentType": "detect_content_type", "deviceId": "device_id", "deviceOwner": "device_owner", "disableNoCacheHeader": "disable_no_cache_header", "disableRollback": "disable_rollback", "disableStatusCheck": "disable_status_check", "discoveryUrl": "discovery_url", "diskFormat": "disk_format", "dnsAssignments": "dns_assignments", "dnsDomain": "dns_domain", "dnsIp": "dns_ip", "dnsName": "dns_name", "dnsNameserver": "dns_nameserver", "dnsNameservers": "dns_nameservers", "dockerStorageDriver": "docker_storage_driver", "dockerVolumeSize": "docker_volume_size", "domainId": "domain_id", "domainName": "domain_name", "driverVolumeType": "driver_volume_type", "dscpMark": "dscp_mark", "enableDhcp": "enable_dhcp", "enableOnlineResize": "enable_online_resize", "enableSnat": "enable_snat", "encapsulationMode": "encapsulation_mode", "encryptionAlgorithm": "encryption_algorithm", "endpointOverrides": "endpoint_overrides", "endpointRegion": "endpoint_region", "endpointType": "endpoint_type", "environmentOpts": "environment_opts", "expectedCodes": "expected_codes", "expiresAt": "expires_at", "exportLocations": "export_locations", "externalFixedIps": "external_fixed_ips", "externalGateway": "external_gateway", "externalNetworkId": "external_network_id", "externalSubnetIds": "external_subnet_ids", "externalV4Ip": "external_v4_ip", "externalV6Ip": "external_v6_ip", "extraDhcpOptions": "extra_dhcp_options", "extraSpecs": "extra_specs", "fixedIp": "fixed_ip", "fixedIps": "fixed_ips", "fixedNetwork": "fixed_network", "fixedSubnet": "fixed_subnet", "flavorId": "flavor_id", "flavorName": "flavor_name", "floatingIp": "floating_ip", "floatingIpEnabled": "floating_ip_enabled", "floatingIps": "floating_ips", "forceDelete": "force_delete", "forceDestroy": "force_destroy", "gatewayIp": "gateway_ip", "groupId": "group_id", "hasReplicas": "has_replicas", "healthMonitor": "health_monitor", "hostName": "host_name", "hostRoutes": "host_routes", "httpMethod": "http_method", "httpProxy": "http_proxy", "httpsProxy": "https_proxy", "ignoreChangePasswordUponFirstUse": "ignore_change_password_upon_first_use", "ignoreLockoutFailureAttempts": "ignore_lockout_failure_attempts", "ignorePasswordExpiry": "<PASSWORD>", "ikeVersion": "ike_version", "ikepolicyId": "ikepolicy_id", "imageCachePath": "image_cache_path", "imageId": "image_id", "imageName": "image_name", "imageSourcePassword": "<PASSWORD>", "imageSourceUrl": "image_source_url", "imageSourceUsername": "image_source_username", "injectedFileContentBytes": "injected_file_content_bytes", "injectedFilePathBytes": "injected_file_path_bytes", "injectedFiles": "injected_files", "insecureRegistry": "insecure_registry", "insertHeaders": "insert_headers", "instanceId": "instance_id", "ipAddress": "ip_address", "ipVersion": "ip_version", "ipsecpolicyId": "ipsecpolicy_id", "ipv6AddressMode": "ipv6_address_mode", "ipv6RaMode": "ipv6_ra_mode", "isDefault": "is_default", "isDomain": "is_domain", "isPublic": "is_public", "keyPair": "key_pair", "keyPairs": "key_pairs", "keypairId": "keypair_id", "l7Policy": "l7_policy", "l7Rule": "l7_rule", "l7policyId": "l7policy_id", "lastModified": "last_modified", "lbMethod": "lb_method", "lbProvider": "lb_provider", "listenerId": "listener_id", "loadbalancerId": "loadbalancer_id", "loadbalancerProvider": "loadbalancer_provider", "localEpGroupId": "local_ep_group_id", "localFilePath": "local_file_path", "localId": "local_id", "macAddress": "mac_address", "masterAddresses": "master_addresses", "masterCount": "master_count", "masterFlavor": "master_flavor", "masterLbEnabled": "master_lb_enabled", "maxBurstKbps": "max_burst_kbps", "maxKbps": "max_kbps", "maxPrefixlen": "max_prefixlen", "maxRetries": "max_retries", "maxRetriesDown": "max_retries_down", "memberId": "member_id", "mergeLabels": "merge_labels", "metadataItems": "metadata_items", "minDiskGb": "min_disk_gb", "minKbps": "min_kbps", "minPrefixlen": "min_prefixlen", "minRamMb": "min_ram_mb", "monitorIds": "monitor_ids", "mountPointBase": "mount_point_base", "multiFactorAuthEnabled": "multi_factor_auth_enabled", "multiFactorAuthRules": "multi_factor_auth_rules", "networkDriver": "network_driver", "networkId": "network_id", "networkMode": "network_mode", "networkType": "network_type", "neutronNetId": "neutron_net_id", "neutronSubnetId": "neutron_subnet_id", "nextHop": "next_hop", "noFixedIp": "no_fixed_ip", "noGateway": "no_gateway", "noProxy": "no_proxy", "noRouters": "no_routers", "noSecurityGroups": "no_security_groups", "nodeAddresses": "node_addresses", "nodeCount": "node_count", "notificationTopics": "notification_topics", "objectId": "object_id", "objectManifest": "object_manifest", "objectType": "object_type", "orderRef": "order_ref", "osType": "os_type", "parentId": "parent_id", "payloadContentEncoding": "payload_content_encoding", "payloadContentType": "payload_content_type", "peerAddress": "peer_address", "peerCidrs": "peer_cidrs", "peerEpGroupId": "peer_ep_group_id", "peerId": "peer_id", "perVolumeGigabytes": "per_volume_gigabytes", "phase1NegotiationMode": "phase1_negotiation_mode", "policyId": "policy_id", "poolId": "pool_id", "portId": "port_id", "portRangeMax": "port_range_max", "portRangeMin": "port_range_min", "portSecurityEnabled": "port_security_enabled", "powerState": "power_state", "prefixLength": "prefix_length", "privateKey": "private_key", "projectDomainId": "project_domain_id", "projectDomainName": "project_domain_name", "projectId": "project_id", "protocolPort": "protocol_port", "publicKey": "public_key", "qosPolicyId": "qos_policy_id", "rawConfig": "raw_config", "rbacPolicy": "rbac_policy", "redirectPoolId": "redirect_pool_id", "redirectUrl": "redirect_url", "registryEnabled": "registry_enabled", "remoteGroupId": "remote_group_id", "remoteIpPrefix": "remote_ip_prefix", "replicationType": "replication_type", "revisionNumber": "revision_number", "roleId": "role_id", "routerId": "router_id", "rxTxFactor": "rx_tx_factor", "schedulerHints": "scheduler_hints", "secretRef": "secret_ref", "secretRefs": "secret_refs", "secretType": "secret_type", "securityGroup": "security_group", "securityGroupId": "security_group_id", "securityGroupIds": "security_group_ids", "securityGroupRule": "security_group_rule", "securityGroupRules": "security_group_rules", "securityGroups": "security_groups", "securityServiceIds": "security_service_ids", "segmentationId": "segmentation_id", "serverGroupMembers": "server_group_members", "serverGroups": "server_groups", "serverType": "server_type", "serviceId": "service_id", "serviceName": "service_name", "serviceType": "service_type", "shareId": "share_id", "shareNetworkId": "share_network_id", "shareProto": "share_proto", "shareServerId": "share_server_id", "shareType": "share_type", "sizeBytes": "size_bytes", "snapshotId": "snapshot_id", "sniContainerRefs": "sni_container_refs", "sourceIpAddress": "source_ip_address", "sourcePort": "source_port", "sourceReplica": "source_replica", "sourceVolId": "source_vol_id", "stackId": "stack_id", "StackOutputs": "stack_outputs", "statusReason": "status_reason", "stopBeforeDestroy": "stop_before_destroy", "subPorts": "sub_ports", "subStatus": "sub_status", "subStatusMessage": "sub_status_message", "subnetId": "subnet_id", "subnetIds": "subnet_ids", "subnetpoolId": "subnetpool_id", "targetTenant": "target_tenant", "templateDescription": "template_description", "templateOpts": "template_opts", "tenantId": "tenant_id", "tenantName": "tenant_name", "timeoutClientData": "timeout_client_data", "timeoutMemberConnect": "timeout_member_connect", "timeoutMemberData": "timeout_member_data", "timeoutTcpInspect": "timeout_tcp_inspect", "tlsDisabled": "tls_disabled", "transId": "trans_id", "transformProtocol": "transform_protocol", "transparentVlan": "transparent_vlan", "trustId": "trust_id", "updateAt": "update_at", "updatedAt": "updated_at", "updatedTime": "updated_time", "urlPath": "url_path", "useOctavia": "use_octavia", "userData": "user_data", "userDomainId": "user_domain_id", "userDomainName": "user_domain_name", "userId": "user_id", "userName": "user_name", "valueSpecs": "value_specs", "vendorOptions": "vendor_options", "verifyChecksum": "verify_checksum", "vipAddress": "vip_address", "vipNetworkId": "vip_network_id", "vipPortId": "vip_port_id", "vipSubnetId": "vip_subnet_id", "volumeDriver": "volume_driver", "volumeId": "volume_id", "volumeType": "volume_type", "volumeTypeQuota": "volume_type_quota", "vpnserviceId": "vpnservice_id", "waitUntilAssociated": "wait_until_associated", "webDownload": "web_download", "zoneId": "zone_id", }
sdk/python/pulumi_openstack/_tables.py
SNAKE_TO_CAMEL_CASE_TABLE = { "access_ip_v4": "accessIpV4", "access_ip_v6": "accessIpV6", "access_key": "accessKey", "access_level": "accessLevel", "access_rules": "accessRules", "access_to": "accessTo", "access_type": "accessType", "address_scope_id": "addressScopeId", "admin_pass": "<PASSWORD>", "admin_state_up": "adminStateUp", "all_fixed_ips": "allFixedIps", "all_metadata": "allMetadata", "all_security_group_ids": "allSecurityGroupIds", "all_tags": "allTags", "allocation_pools": "allocationPools", "allocation_pools_collection": "allocationPoolsCollection", "allow_reauth": "allowReauth", "allowed_address_pairs": "allowedAddressPairs", "allowed_cidrs": "allowedCidrs", "api_address": "apiAddress", "apiserver_port": "apiserverPort", "application_credential_id": "applicationCredentialId", "application_credential_name": "applicationCredentialName", "application_credential_secret": "applicationCredentialSecret", "associated_routers": "associatedRouters", "attach_mode": "attachMode", "auth_algorithm": "authAlgorithm", "auth_url": "authUrl", "availability_zone": "availabilityZone", "availability_zone_hints": "availabilityZoneHints", "backup_gigabytes": "backupGigabytes", "bit_length": "bitLength", "block_devices": "blockDevices", "cacert_file": "cacertFile", "client_certificate": "clientCertificate", "client_key": "clientKey", "cluster_ca_certificate": "clusterCaCertificate", "cluster_distro": "clusterDistro", "cluster_template_id": "clusterTemplateId", "coe_version": "coeVersion", "compare_type": "compareType", "config_drive": "configDrive", "configuration_id": "configurationId", "conn_limit": "connLimit", "connection_limit": "connectionLimit", "consistency_group_id": "consistencyGroupId", "container_format": "containerFormat", "container_name": "containerName", "container_read": "containerRead", "container_ref": "containerRef", "container_sync_key": "containerSyncKey", "container_sync_to": "containerSyncTo", "container_version": "containerVersion", "container_write": "containerWrite", "content_disposition": "contentDisposition", "content_encoding": "contentEncoding", "content_length": "contentLength", "content_type": "contentType", "content_types": "contentTypes", "copy_from": "copyFrom", "create_timeout": "createTimeout", "created_at": "createdAt", "creation_time": "creationTime", "creator_id": "creatorId", "default_domain": "defaultDomain", "default_pool_id": "defaultPoolId", "default_prefixlen": "defaultPrefixlen", "default_project_id": "defaultProjectId", "default_quota": "defaultQuota", "default_tls_container_ref": "defaultTlsContainerRef", "delayed_auth": "delayedAuth", "delete_after": "deleteAfter", "delete_at": "deleteAt", "delete_default_rules": "deleteDefaultRules", "destination_cidr": "destinationCidr", "destination_ip_address": "destinationIpAddress", "destination_port": "destinationPort", "detect_content_type": "detectContentType", "device_id": "deviceId", "device_owner": "deviceOwner", "disable_no_cache_header": "disableNoCacheHeader", "disable_rollback": "disableRollback", "disable_status_check": "disableStatusCheck", "discovery_url": "discoveryUrl", "disk_format": "diskFormat", "dns_assignments": "dnsAssignments", "dns_domain": "dnsDomain", "dns_ip": "dnsIp", "dns_name": "dnsName", "dns_nameserver": "dnsNameserver", "dns_nameservers": "dnsNameservers", "docker_storage_driver": "dockerStorageDriver", "docker_volume_size": "dockerVolumeSize", "domain_id": "domainId", "domain_name": "domainName", "driver_volume_type": "driverVolumeType", "dscp_mark": "dscpMark", "enable_dhcp": "enableDhcp", "enable_online_resize": "enableOnlineResize", "enable_snat": "enableSnat", "encapsulation_mode": "encapsulationMode", "encryption_algorithm": "encryptionAlgorithm", "endpoint_overrides": "endpointOverrides", "endpoint_region": "endpointRegion", "endpoint_type": "endpointType", "environment_opts": "environmentOpts", "expected_codes": "expectedCodes", "expires_at": "expiresAt", "export_locations": "exportLocations", "external_fixed_ips": "externalFixedIps", "external_gateway": "externalGateway", "external_network_id": "externalNetworkId", "external_subnet_ids": "externalSubnetIds", "external_v4_ip": "externalV4Ip", "external_v6_ip": "externalV6Ip", "extra_dhcp_options": "extraDhcpOptions", "extra_specs": "extraSpecs", "fixed_ip": "fixedIp", "fixed_ips": "fixedIps", "fixed_network": "fixedNetwork", "fixed_subnet": "fixedSubnet", "flavor_id": "flavorId", "flavor_name": "flavorName", "floating_ip": "floatingIp", "floating_ip_enabled": "floatingIpEnabled", "floating_ips": "floatingIps", "force_delete": "forceDelete", "force_destroy": "forceDestroy", "gateway_ip": "gatewayIp", "group_id": "groupId", "has_replicas": "hasReplicas", "health_monitor": "healthMonitor", "host_name": "hostName", "host_routes": "hostRoutes", "http_method": "httpMethod", "http_proxy": "httpProxy", "https_proxy": "httpsProxy", "ignore_change_password_upon_first_use": "ignoreChangePasswordUponFirstUse", "ignore_lockout_failure_attempts": "ignoreLockoutFailureAttempts", "ignore_password_expiry": "ignorePasswordExpiry", "ike_version": "ikeVersion", "ikepolicy_id": "ikepolicyId", "image_cache_path": "imageCachePath", "image_id": "imageId", "image_name": "imageName", "image_source_password": "<PASSWORD>", "image_source_url": "imageSourceUrl", "image_source_username": "imageSourceUsername", "injected_file_content_bytes": "injectedFileContentBytes", "injected_file_path_bytes": "injectedFilePathBytes", "injected_files": "injectedFiles", "insecure_registry": "insecureRegistry", "insert_headers": "insertHeaders", "instance_id": "instanceId", "ip_address": "ipAddress", "ip_version": "ipVersion", "ipsecpolicy_id": "ipsecpolicyId", "ipv6_address_mode": "ipv6AddressMode", "ipv6_ra_mode": "ipv6RaMode", "is_default": "isDefault", "is_domain": "isDomain", "is_public": "isPublic", "key_pair": "keyPair", "key_pairs": "keyPairs", "keypair_id": "keypairId", "l7_policy": "l7Policy", "l7_rule": "l7Rule", "l7policy_id": "l7policyId", "last_modified": "lastModified", "lb_method": "lbMethod", "lb_provider": "lbProvider", "listener_id": "listenerId", "loadbalancer_id": "loadbalancerId", "loadbalancer_provider": "loadbalancerProvider", "local_ep_group_id": "localEpGroupId", "local_file_path": "localFilePath", "local_id": "localId", "mac_address": "macAddress", "master_addresses": "masterAddresses", "master_count": "masterCount", "master_flavor": "masterFlavor", "master_lb_enabled": "masterLbEnabled", "max_burst_kbps": "maxBurstKbps", "max_kbps": "maxKbps", "max_prefixlen": "maxPrefixlen", "max_retries": "maxRetries", "max_retries_down": "maxRetriesDown", "member_id": "memberId", "merge_labels": "mergeLabels", "metadata_items": "metadataItems", "min_disk_gb": "minDiskGb", "min_kbps": "minKbps", "min_prefixlen": "minPrefixlen", "min_ram_mb": "minRamMb", "monitor_ids": "monitorIds", "mount_point_base": "mountPointBase", "multi_factor_auth_enabled": "multiFactorAuthEnabled", "multi_factor_auth_rules": "multiFactorAuthRules", "network_driver": "networkDriver", "network_id": "networkId", "network_mode": "networkMode", "network_type": "networkType", "neutron_net_id": "neutronNetId", "neutron_subnet_id": "neutronSubnetId", "next_hop": "nextHop", "no_fixed_ip": "noFixedIp", "no_gateway": "noGateway", "no_proxy": "noProxy", "no_routers": "noRouters", "no_security_groups": "noSecurityGroups", "node_addresses": "nodeAddresses", "node_count": "nodeCount", "notification_topics": "notificationTopics", "object_id": "objectId", "object_manifest": "objectManifest", "object_type": "objectType", "order_ref": "orderRef", "os_type": "osType", "parent_id": "parentId", "payload_content_encoding": "payloadContentEncoding", "payload_content_type": "payloadContentType", "peer_address": "peerAddress", "peer_cidrs": "peerCidrs", "peer_ep_group_id": "peerEpGroupId", "peer_id": "peerId", "per_volume_gigabytes": "perVolumeGigabytes", "phase1_negotiation_mode": "phase1NegotiationMode", "policy_id": "policyId", "pool_id": "poolId", "port_id": "portId", "port_range_max": "portRangeMax", "port_range_min": "portRangeMin", "port_security_enabled": "portSecurityEnabled", "power_state": "powerState", "prefix_length": "prefixLength", "private_key": "privateKey", "project_domain_id": "projectDomainId", "project_domain_name": "projectDomainName", "project_id": "projectId", "protocol_port": "protocolPort", "public_key": "publicKey", "qos_policy_id": "qosPolicyId", "raw_config": "rawConfig", "rbac_policy": "rbacPolicy", "redirect_pool_id": "redirectPoolId", "redirect_url": "redirectUrl", "registry_enabled": "registryEnabled", "remote_group_id": "remoteGroupId", "remote_ip_prefix": "remoteIpPrefix", "replication_type": "replicationType", "revision_number": "revisionNumber", "role_id": "roleId", "router_id": "routerId", "rx_tx_factor": "rxTxFactor", "scheduler_hints": "schedulerHints", "secret_ref": "secretRef", "secret_refs": "secretRefs", "secret_type": "secretType", "security_group": "securityGroup", "security_group_id": "securityGroupId", "security_group_ids": "securityGroupIds", "security_group_rule": "securityGroupRule", "security_group_rules": "securityGroupRules", "security_groups": "securityGroups", "security_service_ids": "securityServiceIds", "segmentation_id": "segmentationId", "server_group_members": "serverGroupMembers", "server_groups": "serverGroups", "server_type": "serverType", "service_id": "serviceId", "service_name": "serviceName", "service_type": "serviceType", "share_id": "shareId", "share_network_id": "shareNetworkId", "share_proto": "shareProto", "share_server_id": "shareServerId", "share_type": "shareType", "size_bytes": "sizeBytes", "snapshot_id": "snapshotId", "sni_container_refs": "sniContainerRefs", "source_ip_address": "sourceIpAddress", "source_port": "sourcePort", "source_replica": "sourceReplica", "source_vol_id": "sourceVolId", "stack_id": "stackId", "stack_outputs": "StackOutputs", "status_reason": "statusReason", "stop_before_destroy": "stopBeforeDestroy", "sub_ports": "subPorts", "sub_status": "subStatus", "sub_status_message": "subStatusMessage", "subnet_id": "subnetId", "subnet_ids": "subnetIds", "subnetpool_id": "subnetpoolId", "target_tenant": "targetTenant", "template_description": "templateDescription", "template_opts": "templateOpts", "tenant_id": "tenantId", "tenant_name": "tenantName", "timeout_client_data": "timeoutClientData", "timeout_member_connect": "timeoutMemberConnect", "timeout_member_data": "timeoutMemberData", "timeout_tcp_inspect": "timeoutTcpInspect", "tls_disabled": "tlsDisabled", "trans_id": "transId", "transform_protocol": "transformProtocol", "transparent_vlan": "transparentVlan", "trust_id": "trustId", "update_at": "updateAt", "updated_at": "updatedAt", "updated_time": "updatedTime", "url_path": "urlPath", "use_octavia": "useOctavia", "user_data": "userData", "user_domain_id": "userDomainId", "user_domain_name": "userDomainName", "user_id": "userId", "user_name": "userName", "value_specs": "valueSpecs", "vendor_options": "vendorOptions", "verify_checksum": "verifyChecksum", "vip_address": "vipAddress", "vip_network_id": "vipNetworkId", "vip_port_id": "vipPortId", "vip_subnet_id": "vipSubnetId", "volume_driver": "volumeDriver", "volume_id": "volumeId", "volume_type": "volumeType", "volume_type_quota": "volumeTypeQuota", "vpnservice_id": "vpnserviceId", "wait_until_associated": "waitUntilAssociated", "web_download": "webDownload", "zone_id": "zoneId", } CAMEL_TO_SNAKE_CASE_TABLE = { "accessIpV4": "access_ip_v4", "accessIpV6": "access_ip_v6", "accessKey": "access_key", "accessLevel": "access_level", "accessRules": "access_rules", "accessTo": "access_to", "accessType": "access_type", "addressScopeId": "address_scope_id", "adminPass": "<PASSWORD>", "adminStateUp": "admin_state_up", "allFixedIps": "all_fixed_ips", "allMetadata": "all_metadata", "allSecurityGroupIds": "all_security_group_ids", "allTags": "all_tags", "allocationPools": "allocation_pools", "allocationPoolsCollection": "allocation_pools_collection", "allowReauth": "allow_reauth", "allowedAddressPairs": "allowed_address_pairs", "allowedCidrs": "allowed_cidrs", "apiAddress": "api_address", "apiserverPort": "apiserver_port", "applicationCredentialId": "application_credential_id", "applicationCredentialName": "application_credential_name", "applicationCredentialSecret": "application_credential_secret", "associatedRouters": "associated_routers", "attachMode": "attach_mode", "authAlgorithm": "auth_algorithm", "authUrl": "auth_url", "availabilityZone": "availability_zone", "availabilityZoneHints": "availability_zone_hints", "backupGigabytes": "backup_gigabytes", "bitLength": "bit_length", "blockDevices": "block_devices", "cacertFile": "cacert_file", "clientCertificate": "client_certificate", "clientKey": "client_key", "clusterCaCertificate": "cluster_ca_certificate", "clusterDistro": "cluster_distro", "clusterTemplateId": "cluster_template_id", "coeVersion": "coe_version", "compareType": "compare_type", "configDrive": "config_drive", "configurationId": "configuration_id", "connLimit": "conn_limit", "connectionLimit": "connection_limit", "consistencyGroupId": "consistency_group_id", "containerFormat": "container_format", "containerName": "container_name", "containerRead": "container_read", "containerRef": "container_ref", "containerSyncKey": "container_sync_key", "containerSyncTo": "container_sync_to", "containerVersion": "container_version", "containerWrite": "container_write", "contentDisposition": "content_disposition", "contentEncoding": "content_encoding", "contentLength": "content_length", "contentType": "content_type", "contentTypes": "content_types", "copyFrom": "copy_from", "createTimeout": "create_timeout", "createdAt": "created_at", "creationTime": "creation_time", "creatorId": "creator_id", "defaultDomain": "default_domain", "defaultPoolId": "default_pool_id", "defaultPrefixlen": "default_prefixlen", "defaultProjectId": "default_project_id", "defaultQuota": "default_quota", "defaultTlsContainerRef": "default_tls_container_ref", "delayedAuth": "delayed_auth", "deleteAfter": "delete_after", "deleteAt": "delete_at", "deleteDefaultRules": "delete_default_rules", "destinationCidr": "destination_cidr", "destinationIpAddress": "destination_ip_address", "destinationPort": "destination_port", "detectContentType": "detect_content_type", "deviceId": "device_id", "deviceOwner": "device_owner", "disableNoCacheHeader": "disable_no_cache_header", "disableRollback": "disable_rollback", "disableStatusCheck": "disable_status_check", "discoveryUrl": "discovery_url", "diskFormat": "disk_format", "dnsAssignments": "dns_assignments", "dnsDomain": "dns_domain", "dnsIp": "dns_ip", "dnsName": "dns_name", "dnsNameserver": "dns_nameserver", "dnsNameservers": "dns_nameservers", "dockerStorageDriver": "docker_storage_driver", "dockerVolumeSize": "docker_volume_size", "domainId": "domain_id", "domainName": "domain_name", "driverVolumeType": "driver_volume_type", "dscpMark": "dscp_mark", "enableDhcp": "enable_dhcp", "enableOnlineResize": "enable_online_resize", "enableSnat": "enable_snat", "encapsulationMode": "encapsulation_mode", "encryptionAlgorithm": "encryption_algorithm", "endpointOverrides": "endpoint_overrides", "endpointRegion": "endpoint_region", "endpointType": "endpoint_type", "environmentOpts": "environment_opts", "expectedCodes": "expected_codes", "expiresAt": "expires_at", "exportLocations": "export_locations", "externalFixedIps": "external_fixed_ips", "externalGateway": "external_gateway", "externalNetworkId": "external_network_id", "externalSubnetIds": "external_subnet_ids", "externalV4Ip": "external_v4_ip", "externalV6Ip": "external_v6_ip", "extraDhcpOptions": "extra_dhcp_options", "extraSpecs": "extra_specs", "fixedIp": "fixed_ip", "fixedIps": "fixed_ips", "fixedNetwork": "fixed_network", "fixedSubnet": "fixed_subnet", "flavorId": "flavor_id", "flavorName": "flavor_name", "floatingIp": "floating_ip", "floatingIpEnabled": "floating_ip_enabled", "floatingIps": "floating_ips", "forceDelete": "force_delete", "forceDestroy": "force_destroy", "gatewayIp": "gateway_ip", "groupId": "group_id", "hasReplicas": "has_replicas", "healthMonitor": "health_monitor", "hostName": "host_name", "hostRoutes": "host_routes", "httpMethod": "http_method", "httpProxy": "http_proxy", "httpsProxy": "https_proxy", "ignoreChangePasswordUponFirstUse": "ignore_change_password_upon_first_use", "ignoreLockoutFailureAttempts": "ignore_lockout_failure_attempts", "ignorePasswordExpiry": "<PASSWORD>", "ikeVersion": "ike_version", "ikepolicyId": "ikepolicy_id", "imageCachePath": "image_cache_path", "imageId": "image_id", "imageName": "image_name", "imageSourcePassword": "<PASSWORD>", "imageSourceUrl": "image_source_url", "imageSourceUsername": "image_source_username", "injectedFileContentBytes": "injected_file_content_bytes", "injectedFilePathBytes": "injected_file_path_bytes", "injectedFiles": "injected_files", "insecureRegistry": "insecure_registry", "insertHeaders": "insert_headers", "instanceId": "instance_id", "ipAddress": "ip_address", "ipVersion": "ip_version", "ipsecpolicyId": "ipsecpolicy_id", "ipv6AddressMode": "ipv6_address_mode", "ipv6RaMode": "ipv6_ra_mode", "isDefault": "is_default", "isDomain": "is_domain", "isPublic": "is_public", "keyPair": "key_pair", "keyPairs": "key_pairs", "keypairId": "keypair_id", "l7Policy": "l7_policy", "l7Rule": "l7_rule", "l7policyId": "l7policy_id", "lastModified": "last_modified", "lbMethod": "lb_method", "lbProvider": "lb_provider", "listenerId": "listener_id", "loadbalancerId": "loadbalancer_id", "loadbalancerProvider": "loadbalancer_provider", "localEpGroupId": "local_ep_group_id", "localFilePath": "local_file_path", "localId": "local_id", "macAddress": "mac_address", "masterAddresses": "master_addresses", "masterCount": "master_count", "masterFlavor": "master_flavor", "masterLbEnabled": "master_lb_enabled", "maxBurstKbps": "max_burst_kbps", "maxKbps": "max_kbps", "maxPrefixlen": "max_prefixlen", "maxRetries": "max_retries", "maxRetriesDown": "max_retries_down", "memberId": "member_id", "mergeLabels": "merge_labels", "metadataItems": "metadata_items", "minDiskGb": "min_disk_gb", "minKbps": "min_kbps", "minPrefixlen": "min_prefixlen", "minRamMb": "min_ram_mb", "monitorIds": "monitor_ids", "mountPointBase": "mount_point_base", "multiFactorAuthEnabled": "multi_factor_auth_enabled", "multiFactorAuthRules": "multi_factor_auth_rules", "networkDriver": "network_driver", "networkId": "network_id", "networkMode": "network_mode", "networkType": "network_type", "neutronNetId": "neutron_net_id", "neutronSubnetId": "neutron_subnet_id", "nextHop": "next_hop", "noFixedIp": "no_fixed_ip", "noGateway": "no_gateway", "noProxy": "no_proxy", "noRouters": "no_routers", "noSecurityGroups": "no_security_groups", "nodeAddresses": "node_addresses", "nodeCount": "node_count", "notificationTopics": "notification_topics", "objectId": "object_id", "objectManifest": "object_manifest", "objectType": "object_type", "orderRef": "order_ref", "osType": "os_type", "parentId": "parent_id", "payloadContentEncoding": "payload_content_encoding", "payloadContentType": "payload_content_type", "peerAddress": "peer_address", "peerCidrs": "peer_cidrs", "peerEpGroupId": "peer_ep_group_id", "peerId": "peer_id", "perVolumeGigabytes": "per_volume_gigabytes", "phase1NegotiationMode": "phase1_negotiation_mode", "policyId": "policy_id", "poolId": "pool_id", "portId": "port_id", "portRangeMax": "port_range_max", "portRangeMin": "port_range_min", "portSecurityEnabled": "port_security_enabled", "powerState": "power_state", "prefixLength": "prefix_length", "privateKey": "private_key", "projectDomainId": "project_domain_id", "projectDomainName": "project_domain_name", "projectId": "project_id", "protocolPort": "protocol_port", "publicKey": "public_key", "qosPolicyId": "qos_policy_id", "rawConfig": "raw_config", "rbacPolicy": "rbac_policy", "redirectPoolId": "redirect_pool_id", "redirectUrl": "redirect_url", "registryEnabled": "registry_enabled", "remoteGroupId": "remote_group_id", "remoteIpPrefix": "remote_ip_prefix", "replicationType": "replication_type", "revisionNumber": "revision_number", "roleId": "role_id", "routerId": "router_id", "rxTxFactor": "rx_tx_factor", "schedulerHints": "scheduler_hints", "secretRef": "secret_ref", "secretRefs": "secret_refs", "secretType": "secret_type", "securityGroup": "security_group", "securityGroupId": "security_group_id", "securityGroupIds": "security_group_ids", "securityGroupRule": "security_group_rule", "securityGroupRules": "security_group_rules", "securityGroups": "security_groups", "securityServiceIds": "security_service_ids", "segmentationId": "segmentation_id", "serverGroupMembers": "server_group_members", "serverGroups": "server_groups", "serverType": "server_type", "serviceId": "service_id", "serviceName": "service_name", "serviceType": "service_type", "shareId": "share_id", "shareNetworkId": "share_network_id", "shareProto": "share_proto", "shareServerId": "share_server_id", "shareType": "share_type", "sizeBytes": "size_bytes", "snapshotId": "snapshot_id", "sniContainerRefs": "sni_container_refs", "sourceIpAddress": "source_ip_address", "sourcePort": "source_port", "sourceReplica": "source_replica", "sourceVolId": "source_vol_id", "stackId": "stack_id", "StackOutputs": "stack_outputs", "statusReason": "status_reason", "stopBeforeDestroy": "stop_before_destroy", "subPorts": "sub_ports", "subStatus": "sub_status", "subStatusMessage": "sub_status_message", "subnetId": "subnet_id", "subnetIds": "subnet_ids", "subnetpoolId": "subnetpool_id", "targetTenant": "target_tenant", "templateDescription": "template_description", "templateOpts": "template_opts", "tenantId": "tenant_id", "tenantName": "tenant_name", "timeoutClientData": "timeout_client_data", "timeoutMemberConnect": "timeout_member_connect", "timeoutMemberData": "timeout_member_data", "timeoutTcpInspect": "timeout_tcp_inspect", "tlsDisabled": "tls_disabled", "transId": "trans_id", "transformProtocol": "transform_protocol", "transparentVlan": "transparent_vlan", "trustId": "trust_id", "updateAt": "update_at", "updatedAt": "updated_at", "updatedTime": "updated_time", "urlPath": "url_path", "useOctavia": "use_octavia", "userData": "user_data", "userDomainId": "user_domain_id", "userDomainName": "user_domain_name", "userId": "user_id", "userName": "user_name", "valueSpecs": "value_specs", "vendorOptions": "vendor_options", "verifyChecksum": "verify_checksum", "vipAddress": "vip_address", "vipNetworkId": "vip_network_id", "vipPortId": "vip_port_id", "vipSubnetId": "vip_subnet_id", "volumeDriver": "volume_driver", "volumeId": "volume_id", "volumeType": "volume_type", "volumeTypeQuota": "volume_type_quota", "vpnserviceId": "vpnservice_id", "waitUntilAssociated": "wait_until_associated", "webDownload": "web_download", "zoneId": "zone_id", }
0.395835
0.273077
from pyspark.ml.wrapper import JavaTransformer from pyspark.ml.util import _jvm from pyspark.ml.param import * class ScoreModel(JavaTransformer): """ Model restored from PMML. """ predictionCol = Param(Params._dummy(), "predictionCol", "prediction column name.", typeConverter=TypeConverters.toString) prependInputs = Param(Params._dummy(), "prependInputs", "whether to prepend the input cols to the output data.", typeConverter=TypeConverters.toBoolean) def __init__(self, java_model=None): """ Initialize this instance with a Java model object. """ super(ScoreModel, self).__init__(java_model) if java_model is not None: self._resetUid(java_model.uid()) def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) def getPredictionCol(self): """ Gets the value of predictionCol or its default value. """ return self.getOrDefault(self.predictionCol) def setPrependInputs(self, value): """ Sets the value of :py:attr:`prependInputs`. """ return self._set(prependInputs=value) def getPrependInputs(self): """ Gets the value of prependInputs or its default value. """ return self.getOrDefault(self.prependInputs) @classmethod def fromFile(cls, name): """ Constructs a score model from PMML file with given pathname. """ java_model = _jvm().org.pmml4s.spark.ScoreModel.fromFile(name) return cls(java_model) @classmethod def fromString(cls, s): """ Constructs a score model from PMML in a String. """ java_model = _jvm().org.pmml4s.spark.ScoreModel.fromString(s) return cls(java_model) @classmethod def fromBytes(cls, bytes_array): """ Constructs a score model from PMML in an array of bytes. """ java_model = _jvm().org.pmml4s.spark.ScoreModel.fromBytes(bytes_array) return cls(java_model)
pypmml_spark/score_model.py
from pyspark.ml.wrapper import JavaTransformer from pyspark.ml.util import _jvm from pyspark.ml.param import * class ScoreModel(JavaTransformer): """ Model restored from PMML. """ predictionCol = Param(Params._dummy(), "predictionCol", "prediction column name.", typeConverter=TypeConverters.toString) prependInputs = Param(Params._dummy(), "prependInputs", "whether to prepend the input cols to the output data.", typeConverter=TypeConverters.toBoolean) def __init__(self, java_model=None): """ Initialize this instance with a Java model object. """ super(ScoreModel, self).__init__(java_model) if java_model is not None: self._resetUid(java_model.uid()) def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) def getPredictionCol(self): """ Gets the value of predictionCol or its default value. """ return self.getOrDefault(self.predictionCol) def setPrependInputs(self, value): """ Sets the value of :py:attr:`prependInputs`. """ return self._set(prependInputs=value) def getPrependInputs(self): """ Gets the value of prependInputs or its default value. """ return self.getOrDefault(self.prependInputs) @classmethod def fromFile(cls, name): """ Constructs a score model from PMML file with given pathname. """ java_model = _jvm().org.pmml4s.spark.ScoreModel.fromFile(name) return cls(java_model) @classmethod def fromString(cls, s): """ Constructs a score model from PMML in a String. """ java_model = _jvm().org.pmml4s.spark.ScoreModel.fromString(s) return cls(java_model) @classmethod def fromBytes(cls, bytes_array): """ Constructs a score model from PMML in an array of bytes. """ java_model = _jvm().org.pmml4s.spark.ScoreModel.fromBytes(bytes_array) return cls(java_model)
0.921087
0.381594
import pprint import re # noqa: F401 import six class Model(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'allow_all_applications': 'bool', 'allowed_application_ids': 'list[str]', 'application_id': 'str', 'creation_time': 'datetime', 'description': 'str', 'documentation': 'str', 'id': 'str', 'input_types': 'list[ModelInputTypes]', 'md5sum': 'str', 'model_clazz': 'str', 'model_module': 'str', 'model_type': 'ModelTypes', 'name': 'str', 'output_format': 'object', 'short_name': 'str', 'size': 'float', 'speed': 'Speed', 'tags': 'list[str]', 'ttl': 'float' } attribute_map = { 'allow_all_applications': 'allow_all_applications', 'allowed_application_ids': 'allowed_application_ids', 'application_id': 'application_id', 'creation_time': 'creation_time', 'description': 'description', 'documentation': 'documentation', 'id': 'id', 'input_types': 'input_types', 'md5sum': 'md5sum', 'model_clazz': 'model_clazz', 'model_module': 'model_module', 'model_type': 'model_type', 'name': 'name', 'output_format': 'output_format', 'short_name': 'short_name', 'size': 'size', 'speed': 'speed', 'tags': 'tags', 'ttl': 'ttl' } def __init__(self, allow_all_applications=None, allowed_application_ids=None, application_id=None, creation_time=None, description=None, documentation=None, id=None, input_types=None, md5sum=None, model_clazz=None, model_module=None, model_type=None, name=None, output_format=None, short_name=None, size=None, speed=None, tags=None, ttl=None): # noqa: E501 """Model - a model defined in Swagger""" # noqa: E501 self._allow_all_applications = None self._allowed_application_ids = None self._application_id = None self._creation_time = None self._description = None self._documentation = None self._id = None self._input_types = None self._md5sum = None self._model_clazz = None self._model_module = None self._model_type = None self._name = None self._output_format = None self._short_name = None self._size = None self._speed = None self._tags = None self._ttl = None self.discriminator = None if allow_all_applications is not None: self.allow_all_applications = allow_all_applications if allowed_application_ids is not None: self.allowed_application_ids = allowed_application_ids if application_id is not None: self.application_id = application_id self.creation_time = creation_time if description is not None: self.description = description if documentation is not None: self.documentation = documentation self.id = id self.input_types = input_types if md5sum is not None: self.md5sum = md5sum self.model_clazz = model_clazz self.model_module = model_module self.model_type = model_type self.name = name if output_format is not None: self.output_format = output_format if short_name is not None: self.short_name = short_name self.size = size if speed is not None: self.speed = speed if tags is not None: self.tags = tags if ttl is not None: self.ttl = ttl @property def allow_all_applications(self): """Gets the allow_all_applications of this Model. # noqa: E501 :return: The allow_all_applications of this Model. # noqa: E501 :rtype: bool """ return self._allow_all_applications @allow_all_applications.setter def allow_all_applications(self, allow_all_applications): """Sets the allow_all_applications of this Model. :param allow_all_applications: The allow_all_applications of this Model. # noqa: E501 :type: bool """ self._allow_all_applications = allow_all_applications @property def allowed_application_ids(self): """Gets the allowed_application_ids of this Model. # noqa: E501 :return: The allowed_application_ids of this Model. # noqa: E501 :rtype: list[str] """ return self._allowed_application_ids @allowed_application_ids.setter def allowed_application_ids(self, allowed_application_ids): """Sets the allowed_application_ids of this Model. :param allowed_application_ids: The allowed_application_ids of this Model. # noqa: E501 :type: list[str] """ self._allowed_application_ids = allowed_application_ids @property def application_id(self): """Gets the application_id of this Model. # noqa: E501 :return: The application_id of this Model. # noqa: E501 :rtype: str """ return self._application_id @application_id.setter def application_id(self, application_id): """Sets the application_id of this Model. :param application_id: The application_id of this Model. # noqa: E501 :type: str """ self._application_id = application_id @property def creation_time(self): """Gets the creation_time of this Model. # noqa: E501 :return: The creation_time of this Model. # noqa: E501 :rtype: datetime """ return self._creation_time @creation_time.setter def creation_time(self, creation_time): """Sets the creation_time of this Model. :param creation_time: The creation_time of this Model. # noqa: E501 :type: datetime """ if creation_time is None: raise ValueError("Invalid value for `creation_time`, must not be `None`") # noqa: E501 self._creation_time = creation_time @property def description(self): """Gets the description of this Model. # noqa: E501 :return: The description of this Model. # noqa: E501 :rtype: str """ return self._description @description.setter def description(self, description): """Sets the description of this Model. :param description: The description of this Model. # noqa: E501 :type: str """ self._description = description @property def documentation(self): """Gets the documentation of this Model. # noqa: E501 :return: The documentation of this Model. # noqa: E501 :rtype: str """ return self._documentation @documentation.setter def documentation(self, documentation): """Sets the documentation of this Model. :param documentation: The documentation of this Model. # noqa: E501 :type: str """ self._documentation = documentation @property def id(self): """Gets the id of this Model. # noqa: E501 :return: The id of this Model. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this Model. :param id: The id of this Model. # noqa: E501 :type: str """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def input_types(self): """Gets the input_types of this Model. # noqa: E501 :return: The input_types of this Model. # noqa: E501 :rtype: list[ModelInputTypes] """ return self._input_types @input_types.setter def input_types(self, input_types): """Sets the input_types of this Model. :param input_types: The input_types of this Model. # noqa: E501 :type: list[ModelInputTypes] """ if input_types is None: raise ValueError("Invalid value for `input_types`, must not be `None`") # noqa: E501 self._input_types = input_types @property def md5sum(self): """Gets the md5sum of this Model. # noqa: E501 The MD5 sum of the model # noqa: E501 :return: The md5sum of this Model. # noqa: E501 :rtype: str """ return self._md5sum @md5sum.setter def md5sum(self, md5sum): """Sets the md5sum of this Model. The MD5 sum of the model # noqa: E501 :param md5sum: The md5sum of this Model. # noqa: E501 :type: str """ self._md5sum = md5sum @property def model_clazz(self): """Gets the model_clazz of this Model. # noqa: E501 The Python class name of the model # noqa: E501 :return: The model_clazz of this Model. # noqa: E501 :rtype: str """ return self._model_clazz @model_clazz.setter def model_clazz(self, model_clazz): """Sets the model_clazz of this Model. The Python class name of the model # noqa: E501 :param model_clazz: The model_clazz of this Model. # noqa: E501 :type: str """ if model_clazz is None: raise ValueError("Invalid value for `model_clazz`, must not be `None`") # noqa: E501 self._model_clazz = model_clazz @property def model_module(self): """Gets the model_module of this Model. # noqa: E501 The Python module ghosting the code for the model # noqa: E501 :return: The model_module of this Model. # noqa: E501 :rtype: str """ return self._model_module @model_module.setter def model_module(self, model_module): """Sets the model_module of this Model. The Python module ghosting the code for the model # noqa: E501 :param model_module: The model_module of this Model. # noqa: E501 :type: str """ if model_module is None: raise ValueError("Invalid value for `model_module`, must not be `None`") # noqa: E501 self._model_module = model_module @property def model_type(self): """Gets the model_type of this Model. # noqa: E501 :return: The model_type of this Model. # noqa: E501 :rtype: ModelTypes """ return self._model_type @model_type.setter def model_type(self, model_type): """Sets the model_type of this Model. :param model_type: The model_type of this Model. # noqa: E501 :type: ModelTypes """ if model_type is None: raise ValueError("Invalid value for `model_type`, must not be `None`") # noqa: E501 self._model_type = model_type @property def name(self): """Gets the name of this Model. # noqa: E501 :return: The name of this Model. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this Model. :param name: The name of this Model. # noqa: E501 :type: str """ if name is None: raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def output_format(self): """Gets the output_format of this Model. # noqa: E501 :return: The output_format of this Model. # noqa: E501 :rtype: object """ return self._output_format @output_format.setter def output_format(self, output_format): """Sets the output_format of this Model. :param output_format: The output_format of this Model. # noqa: E501 :type: object """ self._output_format = output_format @property def short_name(self): """Gets the short_name of this Model. # noqa: E501 :return: The short_name of this Model. # noqa: E501 :rtype: str """ return self._short_name @short_name.setter def short_name(self, short_name): """Sets the short_name of this Model. :param short_name: The short_name of this Model. # noqa: E501 :type: str """ self._short_name = short_name @property def size(self): """Gets the size of this Model. # noqa: E501 :return: The size of this Model. # noqa: E501 :rtype: float """ return self._size @size.setter def size(self, size): """Sets the size of this Model. :param size: The size of this Model. # noqa: E501 :type: float """ if size is None: raise ValueError("Invalid value for `size`, must not be `None`") # noqa: E501 self._size = size @property def speed(self): """Gets the speed of this Model. # noqa: E501 :return: The speed of this Model. # noqa: E501 :rtype: Speed """ return self._speed @speed.setter def speed(self, speed): """Sets the speed of this Model. :param speed: The speed of this Model. # noqa: E501 :type: Speed """ self._speed = speed @property def tags(self): """Gets the tags of this Model. # noqa: E501 :return: The tags of this Model. # noqa: E501 :rtype: list[str] """ return self._tags @tags.setter def tags(self, tags): """Sets the tags of this Model. :param tags: The tags of this Model. # noqa: E501 :type: list[str] """ self._tags = tags @property def ttl(self): """Gets the ttl of this Model. # noqa: E501 The TTL of the workers hosting this model # noqa: E501 :return: The ttl of this Model. # noqa: E501 :rtype: float """ return self._ttl @ttl.setter def ttl(self, ttl): """Sets the ttl of this Model. The TTL of the workers hosting this model # noqa: E501 :param ttl: The ttl of this Model. # noqa: E501 :type: float """ self._ttl = ttl def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Model, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Model): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
leiaapi/generated/models/model.py
import pprint import re # noqa: F401 import six class Model(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'allow_all_applications': 'bool', 'allowed_application_ids': 'list[str]', 'application_id': 'str', 'creation_time': 'datetime', 'description': 'str', 'documentation': 'str', 'id': 'str', 'input_types': 'list[ModelInputTypes]', 'md5sum': 'str', 'model_clazz': 'str', 'model_module': 'str', 'model_type': 'ModelTypes', 'name': 'str', 'output_format': 'object', 'short_name': 'str', 'size': 'float', 'speed': 'Speed', 'tags': 'list[str]', 'ttl': 'float' } attribute_map = { 'allow_all_applications': 'allow_all_applications', 'allowed_application_ids': 'allowed_application_ids', 'application_id': 'application_id', 'creation_time': 'creation_time', 'description': 'description', 'documentation': 'documentation', 'id': 'id', 'input_types': 'input_types', 'md5sum': 'md5sum', 'model_clazz': 'model_clazz', 'model_module': 'model_module', 'model_type': 'model_type', 'name': 'name', 'output_format': 'output_format', 'short_name': 'short_name', 'size': 'size', 'speed': 'speed', 'tags': 'tags', 'ttl': 'ttl' } def __init__(self, allow_all_applications=None, allowed_application_ids=None, application_id=None, creation_time=None, description=None, documentation=None, id=None, input_types=None, md5sum=None, model_clazz=None, model_module=None, model_type=None, name=None, output_format=None, short_name=None, size=None, speed=None, tags=None, ttl=None): # noqa: E501 """Model - a model defined in Swagger""" # noqa: E501 self._allow_all_applications = None self._allowed_application_ids = None self._application_id = None self._creation_time = None self._description = None self._documentation = None self._id = None self._input_types = None self._md5sum = None self._model_clazz = None self._model_module = None self._model_type = None self._name = None self._output_format = None self._short_name = None self._size = None self._speed = None self._tags = None self._ttl = None self.discriminator = None if allow_all_applications is not None: self.allow_all_applications = allow_all_applications if allowed_application_ids is not None: self.allowed_application_ids = allowed_application_ids if application_id is not None: self.application_id = application_id self.creation_time = creation_time if description is not None: self.description = description if documentation is not None: self.documentation = documentation self.id = id self.input_types = input_types if md5sum is not None: self.md5sum = md5sum self.model_clazz = model_clazz self.model_module = model_module self.model_type = model_type self.name = name if output_format is not None: self.output_format = output_format if short_name is not None: self.short_name = short_name self.size = size if speed is not None: self.speed = speed if tags is not None: self.tags = tags if ttl is not None: self.ttl = ttl @property def allow_all_applications(self): """Gets the allow_all_applications of this Model. # noqa: E501 :return: The allow_all_applications of this Model. # noqa: E501 :rtype: bool """ return self._allow_all_applications @allow_all_applications.setter def allow_all_applications(self, allow_all_applications): """Sets the allow_all_applications of this Model. :param allow_all_applications: The allow_all_applications of this Model. # noqa: E501 :type: bool """ self._allow_all_applications = allow_all_applications @property def allowed_application_ids(self): """Gets the allowed_application_ids of this Model. # noqa: E501 :return: The allowed_application_ids of this Model. # noqa: E501 :rtype: list[str] """ return self._allowed_application_ids @allowed_application_ids.setter def allowed_application_ids(self, allowed_application_ids): """Sets the allowed_application_ids of this Model. :param allowed_application_ids: The allowed_application_ids of this Model. # noqa: E501 :type: list[str] """ self._allowed_application_ids = allowed_application_ids @property def application_id(self): """Gets the application_id of this Model. # noqa: E501 :return: The application_id of this Model. # noqa: E501 :rtype: str """ return self._application_id @application_id.setter def application_id(self, application_id): """Sets the application_id of this Model. :param application_id: The application_id of this Model. # noqa: E501 :type: str """ self._application_id = application_id @property def creation_time(self): """Gets the creation_time of this Model. # noqa: E501 :return: The creation_time of this Model. # noqa: E501 :rtype: datetime """ return self._creation_time @creation_time.setter def creation_time(self, creation_time): """Sets the creation_time of this Model. :param creation_time: The creation_time of this Model. # noqa: E501 :type: datetime """ if creation_time is None: raise ValueError("Invalid value for `creation_time`, must not be `None`") # noqa: E501 self._creation_time = creation_time @property def description(self): """Gets the description of this Model. # noqa: E501 :return: The description of this Model. # noqa: E501 :rtype: str """ return self._description @description.setter def description(self, description): """Sets the description of this Model. :param description: The description of this Model. # noqa: E501 :type: str """ self._description = description @property def documentation(self): """Gets the documentation of this Model. # noqa: E501 :return: The documentation of this Model. # noqa: E501 :rtype: str """ return self._documentation @documentation.setter def documentation(self, documentation): """Sets the documentation of this Model. :param documentation: The documentation of this Model. # noqa: E501 :type: str """ self._documentation = documentation @property def id(self): """Gets the id of this Model. # noqa: E501 :return: The id of this Model. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this Model. :param id: The id of this Model. # noqa: E501 :type: str """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def input_types(self): """Gets the input_types of this Model. # noqa: E501 :return: The input_types of this Model. # noqa: E501 :rtype: list[ModelInputTypes] """ return self._input_types @input_types.setter def input_types(self, input_types): """Sets the input_types of this Model. :param input_types: The input_types of this Model. # noqa: E501 :type: list[ModelInputTypes] """ if input_types is None: raise ValueError("Invalid value for `input_types`, must not be `None`") # noqa: E501 self._input_types = input_types @property def md5sum(self): """Gets the md5sum of this Model. # noqa: E501 The MD5 sum of the model # noqa: E501 :return: The md5sum of this Model. # noqa: E501 :rtype: str """ return self._md5sum @md5sum.setter def md5sum(self, md5sum): """Sets the md5sum of this Model. The MD5 sum of the model # noqa: E501 :param md5sum: The md5sum of this Model. # noqa: E501 :type: str """ self._md5sum = md5sum @property def model_clazz(self): """Gets the model_clazz of this Model. # noqa: E501 The Python class name of the model # noqa: E501 :return: The model_clazz of this Model. # noqa: E501 :rtype: str """ return self._model_clazz @model_clazz.setter def model_clazz(self, model_clazz): """Sets the model_clazz of this Model. The Python class name of the model # noqa: E501 :param model_clazz: The model_clazz of this Model. # noqa: E501 :type: str """ if model_clazz is None: raise ValueError("Invalid value for `model_clazz`, must not be `None`") # noqa: E501 self._model_clazz = model_clazz @property def model_module(self): """Gets the model_module of this Model. # noqa: E501 The Python module ghosting the code for the model # noqa: E501 :return: The model_module of this Model. # noqa: E501 :rtype: str """ return self._model_module @model_module.setter def model_module(self, model_module): """Sets the model_module of this Model. The Python module ghosting the code for the model # noqa: E501 :param model_module: The model_module of this Model. # noqa: E501 :type: str """ if model_module is None: raise ValueError("Invalid value for `model_module`, must not be `None`") # noqa: E501 self._model_module = model_module @property def model_type(self): """Gets the model_type of this Model. # noqa: E501 :return: The model_type of this Model. # noqa: E501 :rtype: ModelTypes """ return self._model_type @model_type.setter def model_type(self, model_type): """Sets the model_type of this Model. :param model_type: The model_type of this Model. # noqa: E501 :type: ModelTypes """ if model_type is None: raise ValueError("Invalid value for `model_type`, must not be `None`") # noqa: E501 self._model_type = model_type @property def name(self): """Gets the name of this Model. # noqa: E501 :return: The name of this Model. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this Model. :param name: The name of this Model. # noqa: E501 :type: str """ if name is None: raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def output_format(self): """Gets the output_format of this Model. # noqa: E501 :return: The output_format of this Model. # noqa: E501 :rtype: object """ return self._output_format @output_format.setter def output_format(self, output_format): """Sets the output_format of this Model. :param output_format: The output_format of this Model. # noqa: E501 :type: object """ self._output_format = output_format @property def short_name(self): """Gets the short_name of this Model. # noqa: E501 :return: The short_name of this Model. # noqa: E501 :rtype: str """ return self._short_name @short_name.setter def short_name(self, short_name): """Sets the short_name of this Model. :param short_name: The short_name of this Model. # noqa: E501 :type: str """ self._short_name = short_name @property def size(self): """Gets the size of this Model. # noqa: E501 :return: The size of this Model. # noqa: E501 :rtype: float """ return self._size @size.setter def size(self, size): """Sets the size of this Model. :param size: The size of this Model. # noqa: E501 :type: float """ if size is None: raise ValueError("Invalid value for `size`, must not be `None`") # noqa: E501 self._size = size @property def speed(self): """Gets the speed of this Model. # noqa: E501 :return: The speed of this Model. # noqa: E501 :rtype: Speed """ return self._speed @speed.setter def speed(self, speed): """Sets the speed of this Model. :param speed: The speed of this Model. # noqa: E501 :type: Speed """ self._speed = speed @property def tags(self): """Gets the tags of this Model. # noqa: E501 :return: The tags of this Model. # noqa: E501 :rtype: list[str] """ return self._tags @tags.setter def tags(self, tags): """Sets the tags of this Model. :param tags: The tags of this Model. # noqa: E501 :type: list[str] """ self._tags = tags @property def ttl(self): """Gets the ttl of this Model. # noqa: E501 The TTL of the workers hosting this model # noqa: E501 :return: The ttl of this Model. # noqa: E501 :rtype: float """ return self._ttl @ttl.setter def ttl(self, ttl): """Sets the ttl of this Model. The TTL of the workers hosting this model # noqa: E501 :param ttl: The ttl of this Model. # noqa: E501 :type: float """ self._ttl = ttl def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Model, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Model): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
0.597256
0.104569
from __future__ import print_function from collections import defaultdict import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.ensemble import BaggingClassifier from sklearn.metrics import accuracy_score from .mdr import MDR from ._version import __version__ class MDREnsemble(BaseEstimator, ClassifierMixin): """Bagging ensemble of Multifactor Dimensionality Reduction (MDR) models for prediction in machine learning""" def __init__(self, n_estimators=100, tie_break=1, default_label=0, random_state=None): """Sets up the MDR ensemble Parameters ---------- n_estimators: int (default: 100) Number of MDR models to include in the ensemble tie_break: int (default: 1) Default label in case there's a tie in a set of feature pair values default_label: int (default: 0) Default label in case there's no data for a set of feature pair values random_state: int, RandomState instance or None (default: None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Returns ------- None """ self.n_estimators = n_estimators self.tie_break = tie_break self.default_label = default_label self.random_state = random_state self.feature_map = defaultdict(lambda: default_label) self.ensemble = BaggingClassifier(base_estimator=MDR(tie_break=tie_break, default_label=default_label), n_estimators=n_estimators, random_state=random_state) def fit(self, features, classes): """Constructs the MDR ensemble from the provided training data Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of class labels for prediction Returns ------- None """ self.ensemble.fit(features, classes) # Construct the feature map from the ensemble predictions unique_rows = list(set([tuple(row) for row in features])) for row in unique_rows: self.feature_map[row] = self.ensemble.predict([row])[0] def predict(self, features): """Uses the MDR ensemble to construct a new feature from the provided features Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to transform Returns ---------- array-like: {n_samples} Constructed features from the provided feature matrix """ return self.ensemble.predict(features) def fit_predict(self, features, classes): """Convenience function that fits the provided data then constructs a new feature from the provided features Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of true class labels Returns ---------- array-like: {n_samples} Constructed features from the provided feature matrix """ self.ensemble.fit(features, classes) return self.ensemble.predict(features) def score(self, features, classes, scoring_function=None, **scoring_function_kwargs): """Estimates the accuracy of the predictions from the MDR ensemble Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from classes: array-like {n_samples} List of true class labels Returns ------- accuracy_score: float The estimated accuracy based on the constructed feature """ new_feature = self.ensemble.predict(features) if scoring_function is None: return accuracy_score(classes, new_feature) else: return scoring_function(classes, new_feature, **scoring_function_kwargs)
mdr/mdr_ensemble.py
from __future__ import print_function from collections import defaultdict import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.ensemble import BaggingClassifier from sklearn.metrics import accuracy_score from .mdr import MDR from ._version import __version__ class MDREnsemble(BaseEstimator, ClassifierMixin): """Bagging ensemble of Multifactor Dimensionality Reduction (MDR) models for prediction in machine learning""" def __init__(self, n_estimators=100, tie_break=1, default_label=0, random_state=None): """Sets up the MDR ensemble Parameters ---------- n_estimators: int (default: 100) Number of MDR models to include in the ensemble tie_break: int (default: 1) Default label in case there's a tie in a set of feature pair values default_label: int (default: 0) Default label in case there's no data for a set of feature pair values random_state: int, RandomState instance or None (default: None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Returns ------- None """ self.n_estimators = n_estimators self.tie_break = tie_break self.default_label = default_label self.random_state = random_state self.feature_map = defaultdict(lambda: default_label) self.ensemble = BaggingClassifier(base_estimator=MDR(tie_break=tie_break, default_label=default_label), n_estimators=n_estimators, random_state=random_state) def fit(self, features, classes): """Constructs the MDR ensemble from the provided training data Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of class labels for prediction Returns ------- None """ self.ensemble.fit(features, classes) # Construct the feature map from the ensemble predictions unique_rows = list(set([tuple(row) for row in features])) for row in unique_rows: self.feature_map[row] = self.ensemble.predict([row])[0] def predict(self, features): """Uses the MDR ensemble to construct a new feature from the provided features Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to transform Returns ---------- array-like: {n_samples} Constructed features from the provided feature matrix """ return self.ensemble.predict(features) def fit_predict(self, features, classes): """Convenience function that fits the provided data then constructs a new feature from the provided features Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of true class labels Returns ---------- array-like: {n_samples} Constructed features from the provided feature matrix """ self.ensemble.fit(features, classes) return self.ensemble.predict(features) def score(self, features, classes, scoring_function=None, **scoring_function_kwargs): """Estimates the accuracy of the predictions from the MDR ensemble Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from classes: array-like {n_samples} List of true class labels Returns ------- accuracy_score: float The estimated accuracy based on the constructed feature """ new_feature = self.ensemble.predict(features) if scoring_function is None: return accuracy_score(classes, new_feature) else: return scoring_function(classes, new_feature, **scoring_function_kwargs)
0.924022
0.352592
import pprint import re # noqa: F401 import six from pycherwell.configuration import Configuration class AttachmentsRequest(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'attachment_id': 'str', 'attachment_types': 'list[str]', 'bus_ob_id': 'str', 'bus_ob_name': 'str', 'bus_ob_public_id': 'str', 'bus_ob_rec_id': 'str', 'include_links': 'bool', 'types': 'list[str]' } attribute_map = { 'attachment_id': 'attachmentId', 'attachment_types': 'attachmentTypes', 'bus_ob_id': 'busObId', 'bus_ob_name': 'busObName', 'bus_ob_public_id': 'busObPublicId', 'bus_ob_rec_id': 'busObRecId', 'include_links': 'includeLinks', 'types': 'types' } def __init__(self, attachment_id=None, attachment_types=None, bus_ob_id=None, bus_ob_name=None, bus_ob_public_id=None, bus_ob_rec_id=None, include_links=None, types=None, local_vars_configuration=None): # noqa: E501 """AttachmentsRequest - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._attachment_id = None self._attachment_types = None self._bus_ob_id = None self._bus_ob_name = None self._bus_ob_public_id = None self._bus_ob_rec_id = None self._include_links = None self._types = None self.discriminator = None if attachment_id is not None: self.attachment_id = attachment_id if attachment_types is not None: self.attachment_types = attachment_types if bus_ob_id is not None: self.bus_ob_id = bus_ob_id if bus_ob_name is not None: self.bus_ob_name = bus_ob_name if bus_ob_public_id is not None: self.bus_ob_public_id = bus_ob_public_id if bus_ob_rec_id is not None: self.bus_ob_rec_id = bus_ob_rec_id if include_links is not None: self.include_links = include_links if types is not None: self.types = types @property def attachment_id(self): """Gets the attachment_id of this AttachmentsRequest. # noqa: E501 :return: The attachment_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._attachment_id @attachment_id.setter def attachment_id(self, attachment_id): """Sets the attachment_id of this AttachmentsRequest. :param attachment_id: The attachment_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._attachment_id = attachment_id @property def attachment_types(self): """Gets the attachment_types of this AttachmentsRequest. # noqa: E501 :return: The attachment_types of this AttachmentsRequest. # noqa: E501 :rtype: list[str] """ return self._attachment_types @attachment_types.setter def attachment_types(self, attachment_types): """Sets the attachment_types of this AttachmentsRequest. :param attachment_types: The attachment_types of this AttachmentsRequest. # noqa: E501 :type: list[str] """ allowed_values = ["Imported", "Linked", "URL"] # noqa: E501 if (self.local_vars_configuration.client_side_validation and not set(attachment_types).issubset(set(allowed_values))): # noqa: E501 raise ValueError( "Invalid values for `attachment_types` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(attachment_types) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._attachment_types = attachment_types @property def bus_ob_id(self): """Gets the bus_ob_id of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_id @bus_ob_id.setter def bus_ob_id(self, bus_ob_id): """Sets the bus_ob_id of this AttachmentsRequest. :param bus_ob_id: The bus_ob_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_id = bus_ob_id @property def bus_ob_name(self): """Gets the bus_ob_name of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_name of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_name @bus_ob_name.setter def bus_ob_name(self, bus_ob_name): """Sets the bus_ob_name of this AttachmentsRequest. :param bus_ob_name: The bus_ob_name of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_name = bus_ob_name @property def bus_ob_public_id(self): """Gets the bus_ob_public_id of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_public_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_public_id @bus_ob_public_id.setter def bus_ob_public_id(self, bus_ob_public_id): """Sets the bus_ob_public_id of this AttachmentsRequest. :param bus_ob_public_id: The bus_ob_public_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_public_id = bus_ob_public_id @property def bus_ob_rec_id(self): """Gets the bus_ob_rec_id of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_rec_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_rec_id @bus_ob_rec_id.setter def bus_ob_rec_id(self, bus_ob_rec_id): """Sets the bus_ob_rec_id of this AttachmentsRequest. :param bus_ob_rec_id: The bus_ob_rec_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_rec_id = bus_ob_rec_id @property def include_links(self): """Gets the include_links of this AttachmentsRequest. # noqa: E501 :return: The include_links of this AttachmentsRequest. # noqa: E501 :rtype: bool """ return self._include_links @include_links.setter def include_links(self, include_links): """Sets the include_links of this AttachmentsRequest. :param include_links: The include_links of this AttachmentsRequest. # noqa: E501 :type: bool """ self._include_links = include_links @property def types(self): """Gets the types of this AttachmentsRequest. # noqa: E501 :return: The types of this AttachmentsRequest. # noqa: E501 :rtype: list[str] """ return self._types @types.setter def types(self, types): """Sets the types of this AttachmentsRequest. :param types: The types of this AttachmentsRequest. # noqa: E501 :type: list[str] """ allowed_values = ["None", "File", "FileManagerFile", "BusOb", "History", "Other"] # noqa: E501 if (self.local_vars_configuration.client_side_validation and not set(types).issubset(set(allowed_values))): # noqa: E501 raise ValueError( "Invalid values for `types` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(types) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._types = types def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AttachmentsRequest): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, AttachmentsRequest): return True return self.to_dict() != other.to_dict()
pycherwell/models/attachments_request.py
import pprint import re # noqa: F401 import six from pycherwell.configuration import Configuration class AttachmentsRequest(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'attachment_id': 'str', 'attachment_types': 'list[str]', 'bus_ob_id': 'str', 'bus_ob_name': 'str', 'bus_ob_public_id': 'str', 'bus_ob_rec_id': 'str', 'include_links': 'bool', 'types': 'list[str]' } attribute_map = { 'attachment_id': 'attachmentId', 'attachment_types': 'attachmentTypes', 'bus_ob_id': 'busObId', 'bus_ob_name': 'busObName', 'bus_ob_public_id': 'busObPublicId', 'bus_ob_rec_id': 'busObRecId', 'include_links': 'includeLinks', 'types': 'types' } def __init__(self, attachment_id=None, attachment_types=None, bus_ob_id=None, bus_ob_name=None, bus_ob_public_id=None, bus_ob_rec_id=None, include_links=None, types=None, local_vars_configuration=None): # noqa: E501 """AttachmentsRequest - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._attachment_id = None self._attachment_types = None self._bus_ob_id = None self._bus_ob_name = None self._bus_ob_public_id = None self._bus_ob_rec_id = None self._include_links = None self._types = None self.discriminator = None if attachment_id is not None: self.attachment_id = attachment_id if attachment_types is not None: self.attachment_types = attachment_types if bus_ob_id is not None: self.bus_ob_id = bus_ob_id if bus_ob_name is not None: self.bus_ob_name = bus_ob_name if bus_ob_public_id is not None: self.bus_ob_public_id = bus_ob_public_id if bus_ob_rec_id is not None: self.bus_ob_rec_id = bus_ob_rec_id if include_links is not None: self.include_links = include_links if types is not None: self.types = types @property def attachment_id(self): """Gets the attachment_id of this AttachmentsRequest. # noqa: E501 :return: The attachment_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._attachment_id @attachment_id.setter def attachment_id(self, attachment_id): """Sets the attachment_id of this AttachmentsRequest. :param attachment_id: The attachment_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._attachment_id = attachment_id @property def attachment_types(self): """Gets the attachment_types of this AttachmentsRequest. # noqa: E501 :return: The attachment_types of this AttachmentsRequest. # noqa: E501 :rtype: list[str] """ return self._attachment_types @attachment_types.setter def attachment_types(self, attachment_types): """Sets the attachment_types of this AttachmentsRequest. :param attachment_types: The attachment_types of this AttachmentsRequest. # noqa: E501 :type: list[str] """ allowed_values = ["Imported", "Linked", "URL"] # noqa: E501 if (self.local_vars_configuration.client_side_validation and not set(attachment_types).issubset(set(allowed_values))): # noqa: E501 raise ValueError( "Invalid values for `attachment_types` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(attachment_types) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._attachment_types = attachment_types @property def bus_ob_id(self): """Gets the bus_ob_id of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_id @bus_ob_id.setter def bus_ob_id(self, bus_ob_id): """Sets the bus_ob_id of this AttachmentsRequest. :param bus_ob_id: The bus_ob_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_id = bus_ob_id @property def bus_ob_name(self): """Gets the bus_ob_name of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_name of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_name @bus_ob_name.setter def bus_ob_name(self, bus_ob_name): """Sets the bus_ob_name of this AttachmentsRequest. :param bus_ob_name: The bus_ob_name of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_name = bus_ob_name @property def bus_ob_public_id(self): """Gets the bus_ob_public_id of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_public_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_public_id @bus_ob_public_id.setter def bus_ob_public_id(self, bus_ob_public_id): """Sets the bus_ob_public_id of this AttachmentsRequest. :param bus_ob_public_id: The bus_ob_public_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_public_id = bus_ob_public_id @property def bus_ob_rec_id(self): """Gets the bus_ob_rec_id of this AttachmentsRequest. # noqa: E501 :return: The bus_ob_rec_id of this AttachmentsRequest. # noqa: E501 :rtype: str """ return self._bus_ob_rec_id @bus_ob_rec_id.setter def bus_ob_rec_id(self, bus_ob_rec_id): """Sets the bus_ob_rec_id of this AttachmentsRequest. :param bus_ob_rec_id: The bus_ob_rec_id of this AttachmentsRequest. # noqa: E501 :type: str """ self._bus_ob_rec_id = bus_ob_rec_id @property def include_links(self): """Gets the include_links of this AttachmentsRequest. # noqa: E501 :return: The include_links of this AttachmentsRequest. # noqa: E501 :rtype: bool """ return self._include_links @include_links.setter def include_links(self, include_links): """Sets the include_links of this AttachmentsRequest. :param include_links: The include_links of this AttachmentsRequest. # noqa: E501 :type: bool """ self._include_links = include_links @property def types(self): """Gets the types of this AttachmentsRequest. # noqa: E501 :return: The types of this AttachmentsRequest. # noqa: E501 :rtype: list[str] """ return self._types @types.setter def types(self, types): """Sets the types of this AttachmentsRequest. :param types: The types of this AttachmentsRequest. # noqa: E501 :type: list[str] """ allowed_values = ["None", "File", "FileManagerFile", "BusOb", "History", "Other"] # noqa: E501 if (self.local_vars_configuration.client_side_validation and not set(types).issubset(set(allowed_values))): # noqa: E501 raise ValueError( "Invalid values for `types` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(types) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._types = types def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AttachmentsRequest): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, AttachmentsRequest): return True return self.to_dict() != other.to_dict()
0.616359
0.067362
import pandas as pd import numpy as np from logging_utils import log_exception, log_info, log_warn def loadFile(filename): """ ** Function loadFile** loads the content of a file into a python dataframe Allowed file formats are TXT (.txt), CSV (.csv), and Excel (.xls or xlsx) **parameters**: >*filename: name of file to load **return >dataframe **exception** >write error to log file and quit application """ try: if filename.endswith('.csv') or filename.endswith('.txt'): with open(filename, 'r') as f: header = f.readline() if '\t' in header: data = pd.read_csv(filename, sep='\t', dtype='str', na_values='NA') else: data = pd.read_csv(filename, na_values='NA') del header f.close() elif filename.endswith('.xlsx') or filename.endswith('.xls'): data = pd.read_excel(filename, sheet_name=0, na_values='NA') return data.replace(np.nan, '', regex=True) except Exception as e: log_exception('Error opening file %s' %filename) log_exception(e) return 2 def saveFile(data, filename, index=False, header=True): """ **Function saveFile** saves a dataframe to file with specified filename. The file format used is based on the extension of the specified filename. >CSV - comma separated values (.csv) >TXT - tab delimited values (.txt) >XLSX - MS Excel format (.xlsx or xls) """ try: # if filename.endswith('.csv'): # data.to_csv(filename, index=None, sep=',', na_rep='', mode='w', line_terminator='\n') # elif filename.endswith('.txt'): # data.to_csv(filename, index=None, sep='\t', na_rep='', mode='w', line_terminator='\n') # elif filename.endswith('.xlsx') or filename.endswith('.xls'): # data.to_excel(filename, index=None, sep='\t', na_rep='', mode='w', line_terminator='\n') # else: # data.to_csv(filename, index=None, sep='\t', na_rep='', mode='w', line_terminator='\n') if filename.endswith('.csv'): data.to_csv(filename, index=index, header=header, sep=',', na_rep='', mode='w', line_terminator='\n') elif filename.endswith('.txt') : data.to_csv(filename, index=index, header=header, sep='\t', na_rep='', mode='w', line_terminator='\n') elif filename.endswith('.xlsx') or filename.endswith('.xls') : data.to_excel(filename, index=index, header=header, sep='\t', na_rep='', mode='w', line_terminator='\n') else: data.to_csv(filename, index=index, header=header, sep='\t', na_rep='NA', mode='w', line_terminator='\n') except Exception as e: log_exception('Error saving file %s' %filename) log_exception(e)
Utils.py
import pandas as pd import numpy as np from logging_utils import log_exception, log_info, log_warn def loadFile(filename): """ ** Function loadFile** loads the content of a file into a python dataframe Allowed file formats are TXT (.txt), CSV (.csv), and Excel (.xls or xlsx) **parameters**: >*filename: name of file to load **return >dataframe **exception** >write error to log file and quit application """ try: if filename.endswith('.csv') or filename.endswith('.txt'): with open(filename, 'r') as f: header = f.readline() if '\t' in header: data = pd.read_csv(filename, sep='\t', dtype='str', na_values='NA') else: data = pd.read_csv(filename, na_values='NA') del header f.close() elif filename.endswith('.xlsx') or filename.endswith('.xls'): data = pd.read_excel(filename, sheet_name=0, na_values='NA') return data.replace(np.nan, '', regex=True) except Exception as e: log_exception('Error opening file %s' %filename) log_exception(e) return 2 def saveFile(data, filename, index=False, header=True): """ **Function saveFile** saves a dataframe to file with specified filename. The file format used is based on the extension of the specified filename. >CSV - comma separated values (.csv) >TXT - tab delimited values (.txt) >XLSX - MS Excel format (.xlsx or xls) """ try: # if filename.endswith('.csv'): # data.to_csv(filename, index=None, sep=',', na_rep='', mode='w', line_terminator='\n') # elif filename.endswith('.txt'): # data.to_csv(filename, index=None, sep='\t', na_rep='', mode='w', line_terminator='\n') # elif filename.endswith('.xlsx') or filename.endswith('.xls'): # data.to_excel(filename, index=None, sep='\t', na_rep='', mode='w', line_terminator='\n') # else: # data.to_csv(filename, index=None, sep='\t', na_rep='', mode='w', line_terminator='\n') if filename.endswith('.csv'): data.to_csv(filename, index=index, header=header, sep=',', na_rep='', mode='w', line_terminator='\n') elif filename.endswith('.txt') : data.to_csv(filename, index=index, header=header, sep='\t', na_rep='', mode='w', line_terminator='\n') elif filename.endswith('.xlsx') or filename.endswith('.xls') : data.to_excel(filename, index=index, header=header, sep='\t', na_rep='', mode='w', line_terminator='\n') else: data.to_csv(filename, index=index, header=header, sep='\t', na_rep='NA', mode='w', line_terminator='\n') except Exception as e: log_exception('Error saving file %s' %filename) log_exception(e)
0.245175
0.245661
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = [ 'NetworkAssignIpv4Args', 'NetworkAssignIpv6Args', 'NetworkAssignmentPoolArgs', 'NetworkRouteArgs', 'GetNetworkAssignIpv4Args', 'GetNetworkAssignIpv6Args', 'GetNetworkAssignmentPoolArgs', 'GetNetworkRouteArgs', ] @pulumi.input_type class NetworkAssignIpv4Args: def __init__(__self__, *, zerotier: Optional[pulumi.Input[bool]] = None): if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def zerotier(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "zerotier", value) @pulumi.input_type class NetworkAssignIpv6Args: def __init__(__self__, *, rfc4193: Optional[pulumi.Input[bool]] = None, sixplane: Optional[pulumi.Input[bool]] = None, zerotier: Optional[pulumi.Input[bool]] = None): if rfc4193 is not None: pulumi.set(__self__, "rfc4193", rfc4193) if sixplane is not None: pulumi.set(__self__, "sixplane", sixplane) if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def rfc4193(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "rfc4193") @rfc4193.setter def rfc4193(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "rfc4193", value) @property @pulumi.getter def sixplane(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "sixplane") @sixplane.setter def sixplane(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "sixplane", value) @property @pulumi.getter def zerotier(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "zerotier", value) @pulumi.input_type class NetworkAssignmentPoolArgs: def __init__(__self__, *, end: Optional[pulumi.Input[str]] = None, start: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] end: The last address in the assignment rule. This must be the highest number in the pool. end must also be accompanied by start. :param pulumi.Input[str] start: The first address in the assignment rule. This must be the lowest number in the pool. `start` must also be accompanied by `end`. """ if end is not None: pulumi.set(__self__, "end", end) if start is not None: pulumi.set(__self__, "start", start) @property @pulumi.getter def end(self) -> Optional[pulumi.Input[str]]: """ The last address in the assignment rule. This must be the highest number in the pool. end must also be accompanied by start. """ return pulumi.get(self, "end") @end.setter def end(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "end", value) @property @pulumi.getter def start(self) -> Optional[pulumi.Input[str]]: """ The first address in the assignment rule. This must be the lowest number in the pool. `start` must also be accompanied by `end`. """ return pulumi.get(self, "start") @start.setter def start(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "start", value) @pulumi.input_type class NetworkRouteArgs: def __init__(__self__, *, target: pulumi.Input[str], via: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] target: Network to route for :param pulumi.Input[str] via: Gateway address """ pulumi.set(__self__, "target", target) if via is not None: pulumi.set(__self__, "via", via) @property @pulumi.getter def target(self) -> pulumi.Input[str]: """ Network to route for """ return pulumi.get(self, "target") @target.setter def target(self, value: pulumi.Input[str]): pulumi.set(self, "target", value) @property @pulumi.getter def via(self) -> Optional[pulumi.Input[str]]: """ Gateway address """ return pulumi.get(self, "via") @via.setter def via(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "via", value) @pulumi.input_type class GetNetworkAssignIpv4Args: def __init__(__self__, *, zerotier: Optional[bool] = None): if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def zerotier(self) -> Optional[bool]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[bool]): pulumi.set(self, "zerotier", value) @pulumi.input_type class GetNetworkAssignIpv6Args: def __init__(__self__, *, rfc4193: Optional[bool] = None, sixplane: Optional[bool] = None, zerotier: Optional[bool] = None): if rfc4193 is not None: pulumi.set(__self__, "rfc4193", rfc4193) if sixplane is not None: pulumi.set(__self__, "sixplane", sixplane) if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def rfc4193(self) -> Optional[bool]: return pulumi.get(self, "rfc4193") @rfc4193.setter def rfc4193(self, value: Optional[bool]): pulumi.set(self, "rfc4193", value) @property @pulumi.getter def sixplane(self) -> Optional[bool]: return pulumi.get(self, "sixplane") @sixplane.setter def sixplane(self, value: Optional[bool]): pulumi.set(self, "sixplane", value) @property @pulumi.getter def zerotier(self) -> Optional[bool]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[bool]): pulumi.set(self, "zerotier", value) @pulumi.input_type class GetNetworkAssignmentPoolArgs: def __init__(__self__, *, end: Optional[str] = None, start: Optional[str] = None): if end is not None: pulumi.set(__self__, "end", end) if start is not None: pulumi.set(__self__, "start", start) @property @pulumi.getter def end(self) -> Optional[str]: return pulumi.get(self, "end") @end.setter def end(self, value: Optional[str]): pulumi.set(self, "end", value) @property @pulumi.getter def start(self) -> Optional[str]: return pulumi.get(self, "start") @start.setter def start(self, value: Optional[str]): pulumi.set(self, "start", value) @pulumi.input_type class GetNetworkRouteArgs: def __init__(__self__, *, target: str, via: Optional[str] = None): pulumi.set(__self__, "target", target) if via is not None: pulumi.set(__self__, "via", via) @property @pulumi.getter def target(self) -> str: return pulumi.get(self, "target") @target.setter def target(self, value: str): pulumi.set(self, "target", value) @property @pulumi.getter def via(self) -> Optional[str]: return pulumi.get(self, "via") @via.setter def via(self, value: Optional[str]): pulumi.set(self, "via", value)
sdk/python/pulumi_zerotier/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = [ 'NetworkAssignIpv4Args', 'NetworkAssignIpv6Args', 'NetworkAssignmentPoolArgs', 'NetworkRouteArgs', 'GetNetworkAssignIpv4Args', 'GetNetworkAssignIpv6Args', 'GetNetworkAssignmentPoolArgs', 'GetNetworkRouteArgs', ] @pulumi.input_type class NetworkAssignIpv4Args: def __init__(__self__, *, zerotier: Optional[pulumi.Input[bool]] = None): if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def zerotier(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "zerotier", value) @pulumi.input_type class NetworkAssignIpv6Args: def __init__(__self__, *, rfc4193: Optional[pulumi.Input[bool]] = None, sixplane: Optional[pulumi.Input[bool]] = None, zerotier: Optional[pulumi.Input[bool]] = None): if rfc4193 is not None: pulumi.set(__self__, "rfc4193", rfc4193) if sixplane is not None: pulumi.set(__self__, "sixplane", sixplane) if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def rfc4193(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "rfc4193") @rfc4193.setter def rfc4193(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "rfc4193", value) @property @pulumi.getter def sixplane(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "sixplane") @sixplane.setter def sixplane(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "sixplane", value) @property @pulumi.getter def zerotier(self) -> Optional[pulumi.Input[bool]]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "zerotier", value) @pulumi.input_type class NetworkAssignmentPoolArgs: def __init__(__self__, *, end: Optional[pulumi.Input[str]] = None, start: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] end: The last address in the assignment rule. This must be the highest number in the pool. end must also be accompanied by start. :param pulumi.Input[str] start: The first address in the assignment rule. This must be the lowest number in the pool. `start` must also be accompanied by `end`. """ if end is not None: pulumi.set(__self__, "end", end) if start is not None: pulumi.set(__self__, "start", start) @property @pulumi.getter def end(self) -> Optional[pulumi.Input[str]]: """ The last address in the assignment rule. This must be the highest number in the pool. end must also be accompanied by start. """ return pulumi.get(self, "end") @end.setter def end(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "end", value) @property @pulumi.getter def start(self) -> Optional[pulumi.Input[str]]: """ The first address in the assignment rule. This must be the lowest number in the pool. `start` must also be accompanied by `end`. """ return pulumi.get(self, "start") @start.setter def start(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "start", value) @pulumi.input_type class NetworkRouteArgs: def __init__(__self__, *, target: pulumi.Input[str], via: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] target: Network to route for :param pulumi.Input[str] via: Gateway address """ pulumi.set(__self__, "target", target) if via is not None: pulumi.set(__self__, "via", via) @property @pulumi.getter def target(self) -> pulumi.Input[str]: """ Network to route for """ return pulumi.get(self, "target") @target.setter def target(self, value: pulumi.Input[str]): pulumi.set(self, "target", value) @property @pulumi.getter def via(self) -> Optional[pulumi.Input[str]]: """ Gateway address """ return pulumi.get(self, "via") @via.setter def via(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "via", value) @pulumi.input_type class GetNetworkAssignIpv4Args: def __init__(__self__, *, zerotier: Optional[bool] = None): if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def zerotier(self) -> Optional[bool]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[bool]): pulumi.set(self, "zerotier", value) @pulumi.input_type class GetNetworkAssignIpv6Args: def __init__(__self__, *, rfc4193: Optional[bool] = None, sixplane: Optional[bool] = None, zerotier: Optional[bool] = None): if rfc4193 is not None: pulumi.set(__self__, "rfc4193", rfc4193) if sixplane is not None: pulumi.set(__self__, "sixplane", sixplane) if zerotier is not None: pulumi.set(__self__, "zerotier", zerotier) @property @pulumi.getter def rfc4193(self) -> Optional[bool]: return pulumi.get(self, "rfc4193") @rfc4193.setter def rfc4193(self, value: Optional[bool]): pulumi.set(self, "rfc4193", value) @property @pulumi.getter def sixplane(self) -> Optional[bool]: return pulumi.get(self, "sixplane") @sixplane.setter def sixplane(self, value: Optional[bool]): pulumi.set(self, "sixplane", value) @property @pulumi.getter def zerotier(self) -> Optional[bool]: return pulumi.get(self, "zerotier") @zerotier.setter def zerotier(self, value: Optional[bool]): pulumi.set(self, "zerotier", value) @pulumi.input_type class GetNetworkAssignmentPoolArgs: def __init__(__self__, *, end: Optional[str] = None, start: Optional[str] = None): if end is not None: pulumi.set(__self__, "end", end) if start is not None: pulumi.set(__self__, "start", start) @property @pulumi.getter def end(self) -> Optional[str]: return pulumi.get(self, "end") @end.setter def end(self, value: Optional[str]): pulumi.set(self, "end", value) @property @pulumi.getter def start(self) -> Optional[str]: return pulumi.get(self, "start") @start.setter def start(self, value: Optional[str]): pulumi.set(self, "start", value) @pulumi.input_type class GetNetworkRouteArgs: def __init__(__self__, *, target: str, via: Optional[str] = None): pulumi.set(__self__, "target", target) if via is not None: pulumi.set(__self__, "via", via) @property @pulumi.getter def target(self) -> str: return pulumi.get(self, "target") @target.setter def target(self, value: str): pulumi.set(self, "target", value) @property @pulumi.getter def via(self) -> Optional[str]: return pulumi.get(self, "via") @via.setter def via(self, value: Optional[str]): pulumi.set(self, "via", value)
0.858659
0.102754
import os os.chdir(r'working directory') import matplotlib.image as img import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox import numpy as np # ============================================================================= # ============================================================================= # Initial Inputs and values # Spine positions to be removed sp='right','left','top','bottom' # x-axis grid indices xgrid=np.repeat([0,1,2,3],4) # y-axis grid indices ygrid=np.array([3,2,1,0]) for i in range(1,3): ygrid=np.concatenate([ygrid,ygrid]) # Figure numbers fignum= ['a1','a2','a3','a4', 'b1', 'b2', 'b3','b4', 'c1','c2','c3','c4','d1','d2','d3','d4'] # Figure descriptions descriptions= ['Different model calibration options vs. model efficiency', 'Gantt Chart for measurement durations of different data types', 'Average historical monthly hydroclimatic observations (10+ years)', 'Catchment Budyko plot using different PET estimations', 'Model efficiency for 1 Million Monte carlo simulations', 'Estimated phase and water level change in a SAR interferograms', 'Cross-sectional Elevation profile of Groundwater layers', 'Groundwater particle travel time from a pollution zone to a lake', 'Observed vs. predicted runoff from a rainfall-runoff model', 'Wetland extent change based on water management options', 'Regulation compliance of hypothetical water management options', 'Estimated revenue based on different water management options', 'Modeled results for minimized cost based on pollutant reduction', 'Estimated remediation measure efficiency vs. minimized costs', 'The sensitivity of different modeled parameters (3d surface)', 'Probability of pollutant remediation vs stochastic assumptions'] # defining text annotation function def annotate(h,y,t,s): return x.text(h, y, t, fontsize=s, color='steelblue') # ============================================================================= # ============================================================================= # Plotting # plotting main grid and background fig, axs = plt.subplots(4,4, figsize=(25,20), facecolor='aliceblue') # loading the portfolio for i in range(1,17): x=axs[ygrid[i-1],xgrid[i-1]] x.imshow(img.imread(str(i)+'.jpg')); x.set_xticks([]); x.set_yticks([]) x.set_anchor('C') # Drawing the main frame frame = plt.Rectangle((0.09, 0.09), 0.85, 0.85, fill=False, color="steelblue", lw=5, zorder=1000, transform=fig.transFigure, figure=fig) fig.patches.extend([frame]) # Drawing x-grid using smaller arrows for i in [580,1200,1850]: x=axs[0,0] x.arrow(-230,i,3400,0,clip_on=False, lw=2,head_width=0, head_length=0, ls=(0,(5,10)),fc='lightskyblue',ec='lightskyblue') # Drawing y-grid using smaller arrows for i in [680,1480,2320]: x=axs[0,0] x.arrow(i,-160,0,2650,clip_on=False, lw=2,head_width=0, head_length=0, ls=(0,(5,10)),fc='lightskyblue',ec='lightskyblue') # Adding title annotate(800, -300, 'My Portfolio', 100) # create figure padding for i,j in [3500,-400], [-600,-450], [800,4500]: annotate(i,j,' ', 80) # drawing figure numbers on the main grid # x-axis for i,k in [200,'a'], [1100,'b'], [1850,'c'],[2700,'d']: annotate(i,2800,k, 80) # y-axis for j,k in [2250,'1'], [1550,'2'], [900,'3'],[200,'4']: annotate(-500,j,k, 80) # Drawing the description box frame = plt.Rectangle((0.12, -0.45), 0.8, 0.28, fill=False, color="steelblue", lw=3, ls='--',zorder=1000, transform=fig.transFigure, figure=fig) fig.patches.extend([frame]) # Adding description box title annotate(950, 3250, 'Description', 60) # adding figure descriptions pos=np.arange(3500,4350,100);pos for i in range(0,8): annotate(0, pos[i], fignum[i]+') '+descriptions[i], 18) for i in range(0,8): annotate(0+1600, pos[i], fignum[i+8]+') '+descriptions[i+8], 18) # Saving the Portfolio plt.savefig('Visualization_Progress_fin.jpg', dpi=300, bbox_inches='tight') # =============================================================================
Mini_DViz_Portfolio.py
import os os.chdir(r'working directory') import matplotlib.image as img import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox import numpy as np # ============================================================================= # ============================================================================= # Initial Inputs and values # Spine positions to be removed sp='right','left','top','bottom' # x-axis grid indices xgrid=np.repeat([0,1,2,3],4) # y-axis grid indices ygrid=np.array([3,2,1,0]) for i in range(1,3): ygrid=np.concatenate([ygrid,ygrid]) # Figure numbers fignum= ['a1','a2','a3','a4', 'b1', 'b2', 'b3','b4', 'c1','c2','c3','c4','d1','d2','d3','d4'] # Figure descriptions descriptions= ['Different model calibration options vs. model efficiency', 'Gantt Chart for measurement durations of different data types', 'Average historical monthly hydroclimatic observations (10+ years)', 'Catchment Budyko plot using different PET estimations', 'Model efficiency for 1 Million Monte carlo simulations', 'Estimated phase and water level change in a SAR interferograms', 'Cross-sectional Elevation profile of Groundwater layers', 'Groundwater particle travel time from a pollution zone to a lake', 'Observed vs. predicted runoff from a rainfall-runoff model', 'Wetland extent change based on water management options', 'Regulation compliance of hypothetical water management options', 'Estimated revenue based on different water management options', 'Modeled results for minimized cost based on pollutant reduction', 'Estimated remediation measure efficiency vs. minimized costs', 'The sensitivity of different modeled parameters (3d surface)', 'Probability of pollutant remediation vs stochastic assumptions'] # defining text annotation function def annotate(h,y,t,s): return x.text(h, y, t, fontsize=s, color='steelblue') # ============================================================================= # ============================================================================= # Plotting # plotting main grid and background fig, axs = plt.subplots(4,4, figsize=(25,20), facecolor='aliceblue') # loading the portfolio for i in range(1,17): x=axs[ygrid[i-1],xgrid[i-1]] x.imshow(img.imread(str(i)+'.jpg')); x.set_xticks([]); x.set_yticks([]) x.set_anchor('C') # Drawing the main frame frame = plt.Rectangle((0.09, 0.09), 0.85, 0.85, fill=False, color="steelblue", lw=5, zorder=1000, transform=fig.transFigure, figure=fig) fig.patches.extend([frame]) # Drawing x-grid using smaller arrows for i in [580,1200,1850]: x=axs[0,0] x.arrow(-230,i,3400,0,clip_on=False, lw=2,head_width=0, head_length=0, ls=(0,(5,10)),fc='lightskyblue',ec='lightskyblue') # Drawing y-grid using smaller arrows for i in [680,1480,2320]: x=axs[0,0] x.arrow(i,-160,0,2650,clip_on=False, lw=2,head_width=0, head_length=0, ls=(0,(5,10)),fc='lightskyblue',ec='lightskyblue') # Adding title annotate(800, -300, 'My Portfolio', 100) # create figure padding for i,j in [3500,-400], [-600,-450], [800,4500]: annotate(i,j,' ', 80) # drawing figure numbers on the main grid # x-axis for i,k in [200,'a'], [1100,'b'], [1850,'c'],[2700,'d']: annotate(i,2800,k, 80) # y-axis for j,k in [2250,'1'], [1550,'2'], [900,'3'],[200,'4']: annotate(-500,j,k, 80) # Drawing the description box frame = plt.Rectangle((0.12, -0.45), 0.8, 0.28, fill=False, color="steelblue", lw=3, ls='--',zorder=1000, transform=fig.transFigure, figure=fig) fig.patches.extend([frame]) # Adding description box title annotate(950, 3250, 'Description', 60) # adding figure descriptions pos=np.arange(3500,4350,100);pos for i in range(0,8): annotate(0, pos[i], fignum[i]+') '+descriptions[i], 18) for i in range(0,8): annotate(0+1600, pos[i], fignum[i+8]+') '+descriptions[i+8], 18) # Saving the Portfolio plt.savefig('Visualization_Progress_fin.jpg', dpi=300, bbox_inches='tight') # =============================================================================
0.592549
0.427576
import time import datetime import botlib from javascript import require, On, Once, AsyncTask, once, off pathfinder = require('mineflayer-pathfinder') class ChatBot: stopActivity = True activity_start = 0 activity_name = "None" activity_major = False activity_last_duration = 0 def __init__(self): print('chat ', end='') # Command : [function, name, major activity flag, min_arguments] self.commandList = { "analyze": [self.analyzeBuild, "Analyze building", False, 0], "build": [self.doBuild, "Build a blueprint", True, 1], "chop": [self.chopWood, "Chop wood", True, 0], "deposit": [self.depositToChest, "Deposit all in chest", False, 0], "eat": [self.eatFood, "Eat Something", False, 0], "farm": [self.doFarming, "Farming", True , 0], "hello": [self.sayHello, "Say Hello", False, 0], "inventory": [self.printInventory, "List Inventory", False, 0], "mine": [self.doMining, "Mine for resources", True, 1], "sleep": [self.sleepInBed, "Sleep in a bed", False, 0], "stop": [self.stopThis, "Stop all activities", False, 0], "status": [self.sayStatus, "Report status", False, 0], "wake": [self.wakeUp, "Stop sleeping", False, 0], "yeet": [self.exitGame, "Exit the game", False, 0], } def chat(self,txt): self.bot.chat(txt) self.pdebug(f' chat: {txt}',0) def sayStatus(self): self.pdebug(f' level : {self.bot.experience.level}',0) self.pdebug(f' health: {int(100*self.bot.health/20)}%',0) self.pdebug(f' food : {int(100*self.bot.food/20)}%',0) def sayHello(self): self.chat('hello to you too!') def startActivity(self, name): t_str = botlib.myTime() self.pdebug(60*'-',1) self.pdebug(f'{name:47} {t_str}',1) self.pdebug(60*'-',1) self.activity_start = time.time() self.activity_name = name self.stopActivity = False self.activity_major = True self.dangerType = None self.speedMode = False def endActivity(self): if self.activity_major: t_str = botlib.myTime() d_str = str(datetime.timedelta(seconds=int(time.time()-self.activity_start))) self.pdebug(f'Activity {self.activity_name} ended at {t_str} (duration: {d_str})',1) self.bot.clearControlStates('sneak', False) self.eatFood() self.activity_last_duration = d_str self.bot.stopActivity = True self.activity_major = False def safeSleep(self,t): for i in range(0,t): time.sleep(1) if self.stopActivity: return False return True def stopThis(self): self.stopActivity = True def sleepInBed(self): bed = self.findClosestBlock("White Bed",xz_radius=3,y_radius=1) if not bed: self.chat('cant find a White Bed nearby (I only use those)') else: self.bot.sleep(bed) self.chat('good night!') def wakeUp(self): self.bot.wake() self.chat('i woke up!') def exitGame(self): # exit the game off(self.bot, 'chat', onChat) def handleChat(self,sender, message, this, *rest): # check if order is incorrect to fix a bug we are seeing between Guido and Daniel if type(sender) != type(""): # reorder t = sender sender = message message = this this = t message = message.strip() # Is this for me, or for someone else? if message.startswith(self.callsign): print(f'{sender} messaged me "{message}"') message = message[len(self.callsign):] elif sender != self.bossPlayer(): return self.handleCommand(message,sender) def handleCommand(self, message, sender): # Handle standard commands message = message.lower() cmd = message.split()[0] args = message.split()[1:] if cmd in self.commandList: c = self.commandList[cmd] call_function = c[0] if c[2]: # Major activity if self.activity_major: self.pdebug(f'*** error: major activity in progress, stop it first {self.activity_name}.') return self.startActivity(c[1]) @AsyncTask(start=True) def asyncActivity(task): if c[3] > 0: call_function(args) else: call_function() else: if c[3] > 0: call_function(args) else: call_function() return # Legacy commands, need to clean up # come - try to get to the player if 'come' in message or 'go' in message: if message == 'come': player = self.bot.players[sender] elif 'go to' in message: player = self.bot.players[message[6:]] else: self.chat("No Clear Target") target = player.entity if not target: self.chat("I don't see you!") return pos = target.position @AsyncTask(start=True) def doCome(task): self.walkTo(pos.x, pos.y, pos.z) if 'follow' in message: if message == 'follow': player = self.bot.players[sender] elif len(message) > 6: player = self.bot.players[message[7:]] else: self.chat("No Clear Target") target = player.entity if not target: self.chat("I don't see you!") return @AsyncTask(start=True) def follow(task): while self.stopActivity != True: self.bot.pathfinder.setGoal(pathfinder.goals.GoalFollow(player.entity, 1)) time.sleep(2) if message.startswith('moveto'): args = message[6:].split() if len(args) != 1: self.chat('Need name of location to move to.') return @AsyncTask(start=True) def doMoveTo(task): gotoLocation(self.bot,args[0]) if message.startswith('transfer to'): args = message[11:].split() if len(args) != 1: self.chat('Need name of target chest.') return @AsyncTask(start=True) def doTransfer(task): transferToChest(self.bot,args[0]) if message.startswith('mineshaft'): args = [int(s) for s in message[9:].split() if s.isdigit()] if len(args) != 2: self.chat('Minebox needs three arguments: radius and max depth.') return if args[0] < 1: self.chat(f'Box radius must be at least 1, is {args[0]}') return if args[1] < 1: self.chat(f'Max depth must be at least 1, is {args[1]}') return @AsyncTask(start=True) def doShaftMine(task): shaftMine(self.bot,args[0],args[1])
chat.py
import time import datetime import botlib from javascript import require, On, Once, AsyncTask, once, off pathfinder = require('mineflayer-pathfinder') class ChatBot: stopActivity = True activity_start = 0 activity_name = "None" activity_major = False activity_last_duration = 0 def __init__(self): print('chat ', end='') # Command : [function, name, major activity flag, min_arguments] self.commandList = { "analyze": [self.analyzeBuild, "Analyze building", False, 0], "build": [self.doBuild, "Build a blueprint", True, 1], "chop": [self.chopWood, "Chop wood", True, 0], "deposit": [self.depositToChest, "Deposit all in chest", False, 0], "eat": [self.eatFood, "Eat Something", False, 0], "farm": [self.doFarming, "Farming", True , 0], "hello": [self.sayHello, "Say Hello", False, 0], "inventory": [self.printInventory, "List Inventory", False, 0], "mine": [self.doMining, "Mine for resources", True, 1], "sleep": [self.sleepInBed, "Sleep in a bed", False, 0], "stop": [self.stopThis, "Stop all activities", False, 0], "status": [self.sayStatus, "Report status", False, 0], "wake": [self.wakeUp, "Stop sleeping", False, 0], "yeet": [self.exitGame, "Exit the game", False, 0], } def chat(self,txt): self.bot.chat(txt) self.pdebug(f' chat: {txt}',0) def sayStatus(self): self.pdebug(f' level : {self.bot.experience.level}',0) self.pdebug(f' health: {int(100*self.bot.health/20)}%',0) self.pdebug(f' food : {int(100*self.bot.food/20)}%',0) def sayHello(self): self.chat('hello to you too!') def startActivity(self, name): t_str = botlib.myTime() self.pdebug(60*'-',1) self.pdebug(f'{name:47} {t_str}',1) self.pdebug(60*'-',1) self.activity_start = time.time() self.activity_name = name self.stopActivity = False self.activity_major = True self.dangerType = None self.speedMode = False def endActivity(self): if self.activity_major: t_str = botlib.myTime() d_str = str(datetime.timedelta(seconds=int(time.time()-self.activity_start))) self.pdebug(f'Activity {self.activity_name} ended at {t_str} (duration: {d_str})',1) self.bot.clearControlStates('sneak', False) self.eatFood() self.activity_last_duration = d_str self.bot.stopActivity = True self.activity_major = False def safeSleep(self,t): for i in range(0,t): time.sleep(1) if self.stopActivity: return False return True def stopThis(self): self.stopActivity = True def sleepInBed(self): bed = self.findClosestBlock("White Bed",xz_radius=3,y_radius=1) if not bed: self.chat('cant find a White Bed nearby (I only use those)') else: self.bot.sleep(bed) self.chat('good night!') def wakeUp(self): self.bot.wake() self.chat('i woke up!') def exitGame(self): # exit the game off(self.bot, 'chat', onChat) def handleChat(self,sender, message, this, *rest): # check if order is incorrect to fix a bug we are seeing between Guido and Daniel if type(sender) != type(""): # reorder t = sender sender = message message = this this = t message = message.strip() # Is this for me, or for someone else? if message.startswith(self.callsign): print(f'{sender} messaged me "{message}"') message = message[len(self.callsign):] elif sender != self.bossPlayer(): return self.handleCommand(message,sender) def handleCommand(self, message, sender): # Handle standard commands message = message.lower() cmd = message.split()[0] args = message.split()[1:] if cmd in self.commandList: c = self.commandList[cmd] call_function = c[0] if c[2]: # Major activity if self.activity_major: self.pdebug(f'*** error: major activity in progress, stop it first {self.activity_name}.') return self.startActivity(c[1]) @AsyncTask(start=True) def asyncActivity(task): if c[3] > 0: call_function(args) else: call_function() else: if c[3] > 0: call_function(args) else: call_function() return # Legacy commands, need to clean up # come - try to get to the player if 'come' in message or 'go' in message: if message == 'come': player = self.bot.players[sender] elif 'go to' in message: player = self.bot.players[message[6:]] else: self.chat("No Clear Target") target = player.entity if not target: self.chat("I don't see you!") return pos = target.position @AsyncTask(start=True) def doCome(task): self.walkTo(pos.x, pos.y, pos.z) if 'follow' in message: if message == 'follow': player = self.bot.players[sender] elif len(message) > 6: player = self.bot.players[message[7:]] else: self.chat("No Clear Target") target = player.entity if not target: self.chat("I don't see you!") return @AsyncTask(start=True) def follow(task): while self.stopActivity != True: self.bot.pathfinder.setGoal(pathfinder.goals.GoalFollow(player.entity, 1)) time.sleep(2) if message.startswith('moveto'): args = message[6:].split() if len(args) != 1: self.chat('Need name of location to move to.') return @AsyncTask(start=True) def doMoveTo(task): gotoLocation(self.bot,args[0]) if message.startswith('transfer to'): args = message[11:].split() if len(args) != 1: self.chat('Need name of target chest.') return @AsyncTask(start=True) def doTransfer(task): transferToChest(self.bot,args[0]) if message.startswith('mineshaft'): args = [int(s) for s in message[9:].split() if s.isdigit()] if len(args) != 2: self.chat('Minebox needs three arguments: radius and max depth.') return if args[0] < 1: self.chat(f'Box radius must be at least 1, is {args[0]}') return if args[1] < 1: self.chat(f'Max depth must be at least 1, is {args[1]}') return @AsyncTask(start=True) def doShaftMine(task): shaftMine(self.bot,args[0],args[1])
0.311113
0.167968
import os.path from os import path import sys from pprint import pprint from direct.showbase.ShowBase import ShowBase from direct.task import Task from direct.actor.Actor import Actor from direct.interval.IntervalGlobal import Sequence from panda3d.core import Point3 from direct.gui.OnscreenText import OnscreenText from panda3d.core import loadPrcFileData loadPrcFileData("", "win-size 800 450") def defaultTask(task): global lastplay gframe = task.frame ftext = "GFrame: " + str(task.frame) + "\n" for anim in tstat: if gframe > anim['start'] and gframe < anim['end']: if 'fname' in anim and anim['act']['inuse'] == 1: if anim['act']['current'] == 0: anim['object'].reparentTo(render) ftext = ftext + "Animation: " + anim['fname'] + "\n" anim['object'].pose('anim', anim['act']['start']+anim['act']['current']) lastplay = gframe anim['act']['current'] = anim['act']['current'] + anim['act']['delta'] ftext = ftext + "LFrame: " + str(anim['act']['current']) + "/" + str(anim['act']['end']) textObject.text = ftext if anim['act']['current'] > anim['act']['end']: print ("Warning: current frame > end frame") anim['act']['current'] = anim['act']['end'] if gframe > anim['end']: if anim['finally'] == 'destroy': anim['object'].cleanup () if gframe - lastplay > 20: sys.exit() return Task.cont tstat = [] gframe = 0 lastplay = 0 sid = int(input ("Enter Subject ID (INTEGER): ")) print ("Enter Range of action files to preview (ex. 20, 28). Leave blank for 1, 1000") nrange = str(input ("Enter Range: ")) if nrange == '': nrange = '1,200' nidf, nidl = int(nrange.split(',')[0].strip()), int(nrange.split(',')[1].strip()) actdir = str(input ("Enter action directory (default is 'actions'): ")) if actdir == '': actdir = 'actions' for nid in range (nidf, nidl): fname = "basemodels/"+actdir+"/A20GFLC-A20g%02d_%02d" %(sid, nid) print ("fname", fname) if not path.isfile(fname+".egg"): continue print ("Working for file: ", fname+".egg") actor = Actor('basemodels/bam files/humanbase.bam', {'anim': fname}) ac = actor.getAnimControl('anim') animlen = ac.getNumFrames() animdat = {'object': actor, 'modegg': 'A05GFEA', 'fname': fname, 'start': gframe, 'end': gframe+animlen, 'finally': 'destroy', 'pos': {'inuse': 0, 'start': [], 'end': [], 'current': [], 'delta': [], 'frames': 0}, 'hpr': {'inuse': 0, 'start': [], 'end': [], 'current': [], 'delta': [], 'frames': 0}, 'act': {'inuse': 1, 'start': 0, 'end': animlen, 'current': 0, 'delta': 1, 'frames': animlen} } gframe = gframe + animlen tstat.append (animdat) ShowBase() scene = loader.loadModel("openmodels/BeachTerrain") scene.reparentTo(render) base.disableMouse() camera.setPos(0, -60, 12) camera.setHpr(0, 0, 0) textObject = OnscreenText(text=" ", pos=(-1.2, 0.9), scale=0.07, align=0) taskMgr.add(defaultTask, "defaultTask") base.run()
p3danimall.py
import os.path from os import path import sys from pprint import pprint from direct.showbase.ShowBase import ShowBase from direct.task import Task from direct.actor.Actor import Actor from direct.interval.IntervalGlobal import Sequence from panda3d.core import Point3 from direct.gui.OnscreenText import OnscreenText from panda3d.core import loadPrcFileData loadPrcFileData("", "win-size 800 450") def defaultTask(task): global lastplay gframe = task.frame ftext = "GFrame: " + str(task.frame) + "\n" for anim in tstat: if gframe > anim['start'] and gframe < anim['end']: if 'fname' in anim and anim['act']['inuse'] == 1: if anim['act']['current'] == 0: anim['object'].reparentTo(render) ftext = ftext + "Animation: " + anim['fname'] + "\n" anim['object'].pose('anim', anim['act']['start']+anim['act']['current']) lastplay = gframe anim['act']['current'] = anim['act']['current'] + anim['act']['delta'] ftext = ftext + "LFrame: " + str(anim['act']['current']) + "/" + str(anim['act']['end']) textObject.text = ftext if anim['act']['current'] > anim['act']['end']: print ("Warning: current frame > end frame") anim['act']['current'] = anim['act']['end'] if gframe > anim['end']: if anim['finally'] == 'destroy': anim['object'].cleanup () if gframe - lastplay > 20: sys.exit() return Task.cont tstat = [] gframe = 0 lastplay = 0 sid = int(input ("Enter Subject ID (INTEGER): ")) print ("Enter Range of action files to preview (ex. 20, 28). Leave blank for 1, 1000") nrange = str(input ("Enter Range: ")) if nrange == '': nrange = '1,200' nidf, nidl = int(nrange.split(',')[0].strip()), int(nrange.split(',')[1].strip()) actdir = str(input ("Enter action directory (default is 'actions'): ")) if actdir == '': actdir = 'actions' for nid in range (nidf, nidl): fname = "basemodels/"+actdir+"/A20GFLC-A20g%02d_%02d" %(sid, nid) print ("fname", fname) if not path.isfile(fname+".egg"): continue print ("Working for file: ", fname+".egg") actor = Actor('basemodels/bam files/humanbase.bam', {'anim': fname}) ac = actor.getAnimControl('anim') animlen = ac.getNumFrames() animdat = {'object': actor, 'modegg': 'A05GFEA', 'fname': fname, 'start': gframe, 'end': gframe+animlen, 'finally': 'destroy', 'pos': {'inuse': 0, 'start': [], 'end': [], 'current': [], 'delta': [], 'frames': 0}, 'hpr': {'inuse': 0, 'start': [], 'end': [], 'current': [], 'delta': [], 'frames': 0}, 'act': {'inuse': 1, 'start': 0, 'end': animlen, 'current': 0, 'delta': 1, 'frames': animlen} } gframe = gframe + animlen tstat.append (animdat) ShowBase() scene = loader.loadModel("openmodels/BeachTerrain") scene.reparentTo(render) base.disableMouse() camera.setPos(0, -60, 12) camera.setHpr(0, 0, 0) textObject = OnscreenText(text=" ", pos=(-1.2, 0.9), scale=0.07, align=0) taskMgr.add(defaultTask, "defaultTask") base.run()
0.083148
0.056288
from math import sqrt #КРУГ #События class Circle: def __init__(self, par): self.par = par self.risCircle() def risCircle(self): self.par.kill() self.par.standart_unbind() self.par.old_func = 'self.risCircle()' self.par.c.bind('<Button-1>', self.circle) self.par.dialog.config(text = 'Circle - center point:') self.par.info.config(text = 'Enter - stop') def circle(self, event): self.par.command.focus_set() self.par.set_coord() self.par.ex = self.par.priv_coord[0] self.par.ey = self.par.priv_coord[1] self.par.c.bind_class(self.par.c,"<1>", self.circle2) self.par.dialog.config(text = 'Circle - radius:') self.par.circle_clone = True def circle2(self, event=None): self.par.command.focus_set() self.par.ex2 = self.par.priv_coord[0] self.par.ey2 = self.par.priv_coord[1] self.par.ex,self.par.ey = self.par.coordinator(self.par.ex,self.par.ey) self.par.ex2,self.par.ey2 = self.par.commer(self.par.ex,self.par.ey,self.par.ex2,self.par.ey2) if event: c_circle(self.par, self.par.ex,self.par.ey,self.par.ex2,self.par.ey2) self.par.history_undo.append(('c_', self.par.Ncircle)) #self.par.com = None self.par.changeFlag = True self.par.circle_clone = False self.par.enumerator_p() self.par.risCircle() else: self.par.set_coord() c_circle(self.par, self.par.ex,self.par.ey,self.par.ex2,self.par.ey2, temp = 'Yes') #Отрисовка def c_circle(par, x0, y0, xr = None, yr = None, width = None, sloy = None, fill = None, R = None, ID = None, temp = None): if sloy == None: fill = par.color width = par.width sloy = par.sloy width = int(width) if not temp: if not ID: par.Ncircled+=1 ID = par.Ncircle = 'c' + str(par.Ncircled) id_dict = {} if R == None: R = sqrt((xr-x0)*(xr-x0) + (yr-y0)*(yr-y0)) x1=x0-R x2=x0+R y1=y0-R y2=y0+R s = R/20.0 R = par.n_coordinator(R) id = par.c.create_oval(x1,y1,x2,y2,outline=fill, full=None,width=width,tags = ('obj', ID)) id_dict[id] = ('cir', 'priv') #print par.c.itemcget(id, 'full') id = par.c.create_line(x0-s,y0-s,x0+s,y0+s,fill=fill,tags = ('obj', ID, 'cir_centr')) id_dict[id] = ('line', 'priv', 'cir_centr') id = par.c.create_line(x0+s,y0-s,x0-s,y0+s,fill=fill,tags = ('obj', ID, 'cir_centr')) id_dict[id] = ('line', 'priv', 'cir_centr') par.ALLOBJECT[ID] = {'object':'circle', 'fill':fill, 'width':width, 'sloy':sloy, 'R':R, 'id':id_dict} else: if R == None: R = sqrt((xr-x0)*(xr-x0) + (yr-y0)*(yr-y0)) x1=x0-R x2=x0+R y1=y0-R y2=y0+R s = R/20.0 R = par.n_coordinator(R) par.c.create_oval(x1,y1,x2,y2,outline=fill, full=None,width=width,tags = ('obj', 'temp')) par.c.create_line(x0-s,y0-s,x0+s,y0+s,fill=fill,tags = ('obj', 'temp')) par.c.create_line(x0+s,y0-s,x0-s,y0+s,fill=fill,tags = ('obj', 'temp'))
src/circle.py
from math import sqrt #КРУГ #События class Circle: def __init__(self, par): self.par = par self.risCircle() def risCircle(self): self.par.kill() self.par.standart_unbind() self.par.old_func = 'self.risCircle()' self.par.c.bind('<Button-1>', self.circle) self.par.dialog.config(text = 'Circle - center point:') self.par.info.config(text = 'Enter - stop') def circle(self, event): self.par.command.focus_set() self.par.set_coord() self.par.ex = self.par.priv_coord[0] self.par.ey = self.par.priv_coord[1] self.par.c.bind_class(self.par.c,"<1>", self.circle2) self.par.dialog.config(text = 'Circle - radius:') self.par.circle_clone = True def circle2(self, event=None): self.par.command.focus_set() self.par.ex2 = self.par.priv_coord[0] self.par.ey2 = self.par.priv_coord[1] self.par.ex,self.par.ey = self.par.coordinator(self.par.ex,self.par.ey) self.par.ex2,self.par.ey2 = self.par.commer(self.par.ex,self.par.ey,self.par.ex2,self.par.ey2) if event: c_circle(self.par, self.par.ex,self.par.ey,self.par.ex2,self.par.ey2) self.par.history_undo.append(('c_', self.par.Ncircle)) #self.par.com = None self.par.changeFlag = True self.par.circle_clone = False self.par.enumerator_p() self.par.risCircle() else: self.par.set_coord() c_circle(self.par, self.par.ex,self.par.ey,self.par.ex2,self.par.ey2, temp = 'Yes') #Отрисовка def c_circle(par, x0, y0, xr = None, yr = None, width = None, sloy = None, fill = None, R = None, ID = None, temp = None): if sloy == None: fill = par.color width = par.width sloy = par.sloy width = int(width) if not temp: if not ID: par.Ncircled+=1 ID = par.Ncircle = 'c' + str(par.Ncircled) id_dict = {} if R == None: R = sqrt((xr-x0)*(xr-x0) + (yr-y0)*(yr-y0)) x1=x0-R x2=x0+R y1=y0-R y2=y0+R s = R/20.0 R = par.n_coordinator(R) id = par.c.create_oval(x1,y1,x2,y2,outline=fill, full=None,width=width,tags = ('obj', ID)) id_dict[id] = ('cir', 'priv') #print par.c.itemcget(id, 'full') id = par.c.create_line(x0-s,y0-s,x0+s,y0+s,fill=fill,tags = ('obj', ID, 'cir_centr')) id_dict[id] = ('line', 'priv', 'cir_centr') id = par.c.create_line(x0+s,y0-s,x0-s,y0+s,fill=fill,tags = ('obj', ID, 'cir_centr')) id_dict[id] = ('line', 'priv', 'cir_centr') par.ALLOBJECT[ID] = {'object':'circle', 'fill':fill, 'width':width, 'sloy':sloy, 'R':R, 'id':id_dict} else: if R == None: R = sqrt((xr-x0)*(xr-x0) + (yr-y0)*(yr-y0)) x1=x0-R x2=x0+R y1=y0-R y2=y0+R s = R/20.0 R = par.n_coordinator(R) par.c.create_oval(x1,y1,x2,y2,outline=fill, full=None,width=width,tags = ('obj', 'temp')) par.c.create_line(x0-s,y0-s,x0+s,y0+s,fill=fill,tags = ('obj', 'temp')) par.c.create_line(x0+s,y0-s,x0-s,y0+s,fill=fill,tags = ('obj', 'temp'))
0.165728
0.126974
import xmlrpc.client import ssl import socket # Required for network/socket connections import os # Required for Forking/child processes import time # Required for sleep call import threading # Required for communication sub-threads import pymysql import server_monitor as myServer import certs.gencert as gencert import config import logging from logging.config import fileConfig # Load logging config fileConfig('setup/logging.conf') log = logging.getLogger(__name__) # Global Variables -- Don't change. [No need to change.] CERTFILE = "certs/domains/local.cert" # Placeholder; updated when executed KEYFILE = "certs/domains/local.key" # Default; updated when executed hostIP = "localhost" # Default; updated when executed admin_selected = False # Return ip address of local host where server is running def getMyIP(): log.info('Getting Host ip address.') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 53)) ipAdd = s.getsockname()[0] s.close() log.debug('Socket closed: ipAdd=%s' % ipAdd) return ipAdd # Return host name/fqdn of based on give ip address def findHostName(ipAddress): log.info('Finding Host Name based on ip address') try: log.debug('Trying now...') name, alias, addresslist = socket.gethostbyaddr(ipAddress) log.debug('Returning name: %s' % name) return name except socket.herror: log.exception("Hostname/FQDN not found: Hostname/FQDN Required. " "Correct by adding record in DNS server or within local" "hosts file (/etc/hosts) and then restart controller.") return "None" # Create SSL certs for current ip address if not already present def verifyCerts(): global CERTFILE global KEYFILE # Determine file path based on current ip address CERTFILE = ''.join([config.certPath, config.rootDomain, ".cert"]) KEYFILE = ''.join([config.certPath, config.rootDomain, ".key"]) log.debug("CERTFILE: %s" % (CERTFILE)) log.debug("KEYFILE: %s" % (KEYFILE)) # If cert or key file not present, create new certs if not os.path.isfile(CERTFILE) or not os.path.isfile(KEYFILE): gencert.gencert(config.rootDomain) log.info("Certfile(s) NOT present; new certs created.") print("Certfile(s) NOT present; new certs created.") else: log.info("Certfiles Verified Present") print("Certfiles Verified Present.") # Start a thread child to run server connection as a daemon def startServer(): log.info("Starting Server...") # Now, start thread log.debug("Starting new thread...") t = threading.Thread(name="Monitor_ServerDaemon", target=myServer.runServer, args=(hostIP, config.mntrServerPort, CERTFILE, KEYFILE ) ) t.daemon = True t.start() log.debug("Thread started; end of startServer fn.") # Check and Display the status of all child processes def checkStatus(): log.debug("Checking Status of Threads...") totalThreads = threading.active_count() subThreads = totalThreads - 1 print("\nSub-Thread(s): %d" % (subThreads)) main_thread = threading.currentThread() k = 1 for t in threading.enumerate(): if t is main_thread: continue print("Thread #%d:" % (k)) print("Name: %s" % (t.name)) print("Ident: %d" % (t.ident)) ans = "unknown" if t.is_alive(): ans = "YES" else: ans = "NO" print("Alive? %s\n" % (ans)) k = k+1 log.debug("End of checkStatus fn.") # Display Status of all Hosts currently connected def displayStatus(): log.debug("Displaying agents now") print("Displaying agents currently connected...") # Connect to database to query agents log.debug("Connecting to database") db = pymysql.connect(host=config.mysqlHost, port=config.mysqlPort, user=config.mntrMysqlUser, passwd=<PASSWORD>, db=config.mysqlDB) cursor = db.cursor() # Query to retrieve id/time of registration sql = "SELECT distinct agent FROM status;" agents = [] # Get agents try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists results = cursor.fetchall() for row in results: thisAgent = row[0] agents.append(thisAgent) log.debug("Agent Received as: %s" % (thisAgent)) except: log.exception("ERROR in db query>> %s" % sql) print("FOUND %d agent(s) monitored.\n" % len(agents)) # Query to retrieve each agents's data for k in range(len(agents)): sql = "SELECT agent, status, timestamp, alias, id FROM "\ "status where agent = '%s' ORDER BY id "\ "DESC LIMIT 1" % (agents[k]) # Get host info try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists results = cursor.fetchall() print("Agent #%d" % (k + 1)) for row in results: thisAgent = row[0] thisStatus = row[1] thisTime = row[2] thisAlias = row[3] thisID = row[4] print("Agent: %s" % thisAgent) print("Alias: %s" % thisAlias) print("Status: %s" % thisStatus) print("Time Connected: %s" % thisTime) print("ID Number: %s\n" % thisID) log.debug("Host %d Displayed" % (k + 1)) except: log.exception("ERROR in db query>> %s" % sql) # Disconnect from database db.close() # Simple test function to ensure communication is working def mathTest(): log.debug("Start of Math Test Function...") myContext = ssl.create_default_context() myContext.load_verify_locations(config.CACERTFILE) myurl = ''.join(['https://', config.agntHostName, ':', str(config.agntServerPort)]) with xmlrpc.client.ServerProxy(myurl, context=myContext) as proxy: try: print("5 + 9 is %d" % (proxy.add(5, 9))) print("21 x 3 is: %d" % (proxy.multiply(21, 3))) except ConnectionRefusedError: log.warning("Connection to Agent FAILED") print("Connection to Agent Server FAILED:\n", "Is Agent listening? Confirm connection", "settings and try again.") print("Settings used: '%s'" % myurl) except: log.warning("Connection to Agent FAILED") print("Connection Failed. Suspected incorrect URL.") print("Settings used: '%s'" % myurl) # Quit gracefully after terminting all child processes def myQuit(): log.info("Monitor Exiting. Goodbye.") print("Monitor Exiting. Goodbye.\n") raise SystemExit # Stop Controller Server def stopServer(): log.debug("Stopping Monitor Server.") # TODO Determine if it is possible to stop a daemon thread # without stopping the whole program; for now, this just # ends the entire program print("Monitor Server Stopping.") myQuit() def invalid(choice): log.debug("Invalid choice: %s" % choice) print("INVALID CHOICE!") def adminMenu(): log.debug("Displaying admin menu") print("\nAdmin Menu:") print("a) Connection Test with Agent (simple math test)") print("b) SSL Verification (verify certificates") print("c) STOP Monitor Server (program will exit)") print("d) START* Monitor Server (*only if not running already)") print("9) BACK (return to 'Menu')") return input("Make a Choice\n>>> ") def adminSelection(): global admin_selected adminChoice = adminMenu() if adminChoice == "a": mathTest() elif adminChoice == "b": verifyCerts() elif adminChoice == "c": stopServer() elif adminChoice == "d": startServer() elif adminChoice == "9": log.debug("Admin is De-selected") print("Back to Main Menu...") admin_selected = False elif adminChoice == "r": # Refresh Menu (do nothing) log.info("Refreshing Menu") elif adminChoice in ["q", ":q"]: myQuit() else: invalid(adminChoice) def menu(): log.debug("Displaying menu") print("\n\nMENU[Monitor]:") print("1) Check MONITOR server status") print("2) Display Current Status") print("9) ADMIN MENU") print("q) QUIT") return input("Make a Choice\n>>> ") def myMenu(): global admin_selected choice = 0 if admin_selected: choice = "9" else: choice = menu() if choice == "1": checkStatus() elif choice == "2": displayStatus() elif choice == "9": admin_selected = True log.debug("Admin is Selected") adminSelection() elif choice in ["q", ":q"]: myQuit() elif choice == "r": # Refresh Menu (do nothing) log.info("Refreshing Menu") else: invalid(choice) # Start of Main if __name__ == '__main__': log.info("Starting Monitor Main.") hostIP = getMyIP() verifyHostName = findHostName(hostIP) pid = os.getpid() print("Host IP: %s" % (hostIP)) print("Hostname: %s" % (verifyHostName)) log.debug("PID: %d" % (pid)) if verifyHostName == "None": log.debug("Hostname not found: Returned 'None'") elif verifyHostName in [config.ctlrHostName, config.mntrHostName]: log.debug("HostName verified.") log.debug("Verifying certificates.") # Verify certificates present prior to displaying menu verifyCerts() # Starting Server startServer() time.sleep(2) # Display Menu [repeatedly] for user while True: myMenu() time.sleep(1) else: log.error("Hostname incorrect. " "Hostname Found: %s; Hostname " "Required: %s." % (verifyHostName, config.mntrHostName))
monitor.py
import xmlrpc.client import ssl import socket # Required for network/socket connections import os # Required for Forking/child processes import time # Required for sleep call import threading # Required for communication sub-threads import pymysql import server_monitor as myServer import certs.gencert as gencert import config import logging from logging.config import fileConfig # Load logging config fileConfig('setup/logging.conf') log = logging.getLogger(__name__) # Global Variables -- Don't change. [No need to change.] CERTFILE = "certs/domains/local.cert" # Placeholder; updated when executed KEYFILE = "certs/domains/local.key" # Default; updated when executed hostIP = "localhost" # Default; updated when executed admin_selected = False # Return ip address of local host where server is running def getMyIP(): log.info('Getting Host ip address.') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 53)) ipAdd = s.getsockname()[0] s.close() log.debug('Socket closed: ipAdd=%s' % ipAdd) return ipAdd # Return host name/fqdn of based on give ip address def findHostName(ipAddress): log.info('Finding Host Name based on ip address') try: log.debug('Trying now...') name, alias, addresslist = socket.gethostbyaddr(ipAddress) log.debug('Returning name: %s' % name) return name except socket.herror: log.exception("Hostname/FQDN not found: Hostname/FQDN Required. " "Correct by adding record in DNS server or within local" "hosts file (/etc/hosts) and then restart controller.") return "None" # Create SSL certs for current ip address if not already present def verifyCerts(): global CERTFILE global KEYFILE # Determine file path based on current ip address CERTFILE = ''.join([config.certPath, config.rootDomain, ".cert"]) KEYFILE = ''.join([config.certPath, config.rootDomain, ".key"]) log.debug("CERTFILE: %s" % (CERTFILE)) log.debug("KEYFILE: %s" % (KEYFILE)) # If cert or key file not present, create new certs if not os.path.isfile(CERTFILE) or not os.path.isfile(KEYFILE): gencert.gencert(config.rootDomain) log.info("Certfile(s) NOT present; new certs created.") print("Certfile(s) NOT present; new certs created.") else: log.info("Certfiles Verified Present") print("Certfiles Verified Present.") # Start a thread child to run server connection as a daemon def startServer(): log.info("Starting Server...") # Now, start thread log.debug("Starting new thread...") t = threading.Thread(name="Monitor_ServerDaemon", target=myServer.runServer, args=(hostIP, config.mntrServerPort, CERTFILE, KEYFILE ) ) t.daemon = True t.start() log.debug("Thread started; end of startServer fn.") # Check and Display the status of all child processes def checkStatus(): log.debug("Checking Status of Threads...") totalThreads = threading.active_count() subThreads = totalThreads - 1 print("\nSub-Thread(s): %d" % (subThreads)) main_thread = threading.currentThread() k = 1 for t in threading.enumerate(): if t is main_thread: continue print("Thread #%d:" % (k)) print("Name: %s" % (t.name)) print("Ident: %d" % (t.ident)) ans = "unknown" if t.is_alive(): ans = "YES" else: ans = "NO" print("Alive? %s\n" % (ans)) k = k+1 log.debug("End of checkStatus fn.") # Display Status of all Hosts currently connected def displayStatus(): log.debug("Displaying agents now") print("Displaying agents currently connected...") # Connect to database to query agents log.debug("Connecting to database") db = pymysql.connect(host=config.mysqlHost, port=config.mysqlPort, user=config.mntrMysqlUser, passwd=<PASSWORD>, db=config.mysqlDB) cursor = db.cursor() # Query to retrieve id/time of registration sql = "SELECT distinct agent FROM status;" agents = [] # Get agents try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists results = cursor.fetchall() for row in results: thisAgent = row[0] agents.append(thisAgent) log.debug("Agent Received as: %s" % (thisAgent)) except: log.exception("ERROR in db query>> %s" % sql) print("FOUND %d agent(s) monitored.\n" % len(agents)) # Query to retrieve each agents's data for k in range(len(agents)): sql = "SELECT agent, status, timestamp, alias, id FROM "\ "status where agent = '%s' ORDER BY id "\ "DESC LIMIT 1" % (agents[k]) # Get host info try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists results = cursor.fetchall() print("Agent #%d" % (k + 1)) for row in results: thisAgent = row[0] thisStatus = row[1] thisTime = row[2] thisAlias = row[3] thisID = row[4] print("Agent: %s" % thisAgent) print("Alias: %s" % thisAlias) print("Status: %s" % thisStatus) print("Time Connected: %s" % thisTime) print("ID Number: %s\n" % thisID) log.debug("Host %d Displayed" % (k + 1)) except: log.exception("ERROR in db query>> %s" % sql) # Disconnect from database db.close() # Simple test function to ensure communication is working def mathTest(): log.debug("Start of Math Test Function...") myContext = ssl.create_default_context() myContext.load_verify_locations(config.CACERTFILE) myurl = ''.join(['https://', config.agntHostName, ':', str(config.agntServerPort)]) with xmlrpc.client.ServerProxy(myurl, context=myContext) as proxy: try: print("5 + 9 is %d" % (proxy.add(5, 9))) print("21 x 3 is: %d" % (proxy.multiply(21, 3))) except ConnectionRefusedError: log.warning("Connection to Agent FAILED") print("Connection to Agent Server FAILED:\n", "Is Agent listening? Confirm connection", "settings and try again.") print("Settings used: '%s'" % myurl) except: log.warning("Connection to Agent FAILED") print("Connection Failed. Suspected incorrect URL.") print("Settings used: '%s'" % myurl) # Quit gracefully after terminting all child processes def myQuit(): log.info("Monitor Exiting. Goodbye.") print("Monitor Exiting. Goodbye.\n") raise SystemExit # Stop Controller Server def stopServer(): log.debug("Stopping Monitor Server.") # TODO Determine if it is possible to stop a daemon thread # without stopping the whole program; for now, this just # ends the entire program print("Monitor Server Stopping.") myQuit() def invalid(choice): log.debug("Invalid choice: %s" % choice) print("INVALID CHOICE!") def adminMenu(): log.debug("Displaying admin menu") print("\nAdmin Menu:") print("a) Connection Test with Agent (simple math test)") print("b) SSL Verification (verify certificates") print("c) STOP Monitor Server (program will exit)") print("d) START* Monitor Server (*only if not running already)") print("9) BACK (return to 'Menu')") return input("Make a Choice\n>>> ") def adminSelection(): global admin_selected adminChoice = adminMenu() if adminChoice == "a": mathTest() elif adminChoice == "b": verifyCerts() elif adminChoice == "c": stopServer() elif adminChoice == "d": startServer() elif adminChoice == "9": log.debug("Admin is De-selected") print("Back to Main Menu...") admin_selected = False elif adminChoice == "r": # Refresh Menu (do nothing) log.info("Refreshing Menu") elif adminChoice in ["q", ":q"]: myQuit() else: invalid(adminChoice) def menu(): log.debug("Displaying menu") print("\n\nMENU[Monitor]:") print("1) Check MONITOR server status") print("2) Display Current Status") print("9) ADMIN MENU") print("q) QUIT") return input("Make a Choice\n>>> ") def myMenu(): global admin_selected choice = 0 if admin_selected: choice = "9" else: choice = menu() if choice == "1": checkStatus() elif choice == "2": displayStatus() elif choice == "9": admin_selected = True log.debug("Admin is Selected") adminSelection() elif choice in ["q", ":q"]: myQuit() elif choice == "r": # Refresh Menu (do nothing) log.info("Refreshing Menu") else: invalid(choice) # Start of Main if __name__ == '__main__': log.info("Starting Monitor Main.") hostIP = getMyIP() verifyHostName = findHostName(hostIP) pid = os.getpid() print("Host IP: %s" % (hostIP)) print("Hostname: %s" % (verifyHostName)) log.debug("PID: %d" % (pid)) if verifyHostName == "None": log.debug("Hostname not found: Returned 'None'") elif verifyHostName in [config.ctlrHostName, config.mntrHostName]: log.debug("HostName verified.") log.debug("Verifying certificates.") # Verify certificates present prior to displaying menu verifyCerts() # Starting Server startServer() time.sleep(2) # Display Menu [repeatedly] for user while True: myMenu() time.sleep(1) else: log.error("Hostname incorrect. " "Hostname Found: %s; Hostname " "Required: %s." % (verifyHostName, config.mntrHostName))
0.426799
0.066995
from __future__ import unicode_literals from __future__ import print_function import logging import numpy as np from . import SampleBasedDecay logger = logging.getLogger('decay.sigmoid') class SigmoidDecay(SampleBasedDecay): """ Class that decays the value following the sigmoid curve. Sigmoid is: k Y = --------------------- + 1 a + bx 1 + e This curve used a=5, b=-10, k=-1 This intersects the Y axis at +1 and the X axis at -1 and +1. We're interested only in the positive x. """ def __init__(self, *args, **kwargs): """ Constructor. """ super(SigmoidDecay, self).__init__( decay_name='.decay.sigmoid.', *args, **kwargs) def __str__(self): """ Represent this object as a human-readable string. """ return 'SigmoidDecay()' def __repr__(self): """ Represent this object as a python constructor. """ return 'SigmoidDecay()' decay_x = np.array([ 0.0, 0.05263157894736842, 0.10526315789473684, 0.15789473684210525, 0.21052631578947367, 0.2631578947368421, 0.3157894736842105, 0.3684210526315789, 0.42105263157894735, 0.47368421052631576, 0.5263157894736842, 0.5789473684210527, 0.631578947368421, 0.6842105263157894, 0.7368421052631579, 0.7894736842105263, 0.8421052631578947, 0.894736842105263, 0.9473684210526315, 1.0, ]) decay_y = np.array([ 1.0, 0.9887233930500594, 0.981060202331128, 0.9683560429143016, 0.9475856461385416, 0.9143873364615575, 0.8631975029868619, 0.7884803317042178, 0.6877183092063931, 0.5654124132133331, 0.4345875867866671, 0.3122816907936069, 0.21151966829578206, 0.13680249701313818, 0.08561266353844266, 0.05241435386145843, 0.03164395708569834, 0.018939797668871994, 0.011276606949940704, 0.0, ])
decay/decays/sample/sigmoid.py
from __future__ import unicode_literals from __future__ import print_function import logging import numpy as np from . import SampleBasedDecay logger = logging.getLogger('decay.sigmoid') class SigmoidDecay(SampleBasedDecay): """ Class that decays the value following the sigmoid curve. Sigmoid is: k Y = --------------------- + 1 a + bx 1 + e This curve used a=5, b=-10, k=-1 This intersects the Y axis at +1 and the X axis at -1 and +1. We're interested only in the positive x. """ def __init__(self, *args, **kwargs): """ Constructor. """ super(SigmoidDecay, self).__init__( decay_name='.decay.sigmoid.', *args, **kwargs) def __str__(self): """ Represent this object as a human-readable string. """ return 'SigmoidDecay()' def __repr__(self): """ Represent this object as a python constructor. """ return 'SigmoidDecay()' decay_x = np.array([ 0.0, 0.05263157894736842, 0.10526315789473684, 0.15789473684210525, 0.21052631578947367, 0.2631578947368421, 0.3157894736842105, 0.3684210526315789, 0.42105263157894735, 0.47368421052631576, 0.5263157894736842, 0.5789473684210527, 0.631578947368421, 0.6842105263157894, 0.7368421052631579, 0.7894736842105263, 0.8421052631578947, 0.894736842105263, 0.9473684210526315, 1.0, ]) decay_y = np.array([ 1.0, 0.9887233930500594, 0.981060202331128, 0.9683560429143016, 0.9475856461385416, 0.9143873364615575, 0.8631975029868619, 0.7884803317042178, 0.6877183092063931, 0.5654124132133331, 0.4345875867866671, 0.3122816907936069, 0.21151966829578206, 0.13680249701313818, 0.08561266353844266, 0.05241435386145843, 0.03164395708569834, 0.018939797668871994, 0.011276606949940704, 0.0, ])
0.815233
0.229125
import os from pylearn2ext.chbmit import CHBMIT from pylearn2ext.epilepsiae import EpilepsiaeTest def compute_n_samples_chbmit(): patients = [1, 3, 5, 8, 10, 20] model_path = '../models' data_path = '/Users/akara/Workspace/data/chbmit' with open(os.path.join(model_path, 'sdae_chbmit_train_test_samples'), 'wb') as f: f.write('patient_id,leave_file_idx,total_samples,train_samples,test_samples\n') for patient_id in patients: files = { 1: range(7), 3: range(7), 5: range(5), 8: range(5), 10: range(7), 20: range(6), } for f_idx in files[patient_id]: leave_one_out_file = f_idx dataset = CHBMIT(patient_id=patient_id, which_set='train', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, transform='single_channel', leave_one_out_file=leave_one_out_file, window_size=256, batch_size=20) n_train_samples = dataset.X.shape[0] dataset = CHBMIT(patient_id=patient_id, which_set='test', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, transform='single_channel', leave_one_out_file=leave_one_out_file, window_size=256, batch_size=20) n_test_samples = dataset.X.shape[0] n_total_samples = n_train_samples + n_test_samples f.write('{0},{1},{2},{3},{4}\n'.format(patient_id, leave_one_out_file, n_total_samples, n_train_samples, n_test_samples)) def compute_n_samples_epilepsiae(): patients = [1] model_path = '../models' data_path = '/Users/akara/Workspace/data/epilepsiae' with open(os.path.join(model_path, 'sdae_epilepsiae_train_test_samples'), 'wb') as f: f.write('patient_id,leave_seizure_idx,total_samples,train_samples,test_samples\n') for patient_id in patients: seizures = { 1: range(6) } for s_idx in seizures[patient_id]: leave_one_out_seizure = s_idx dataset = EpilepsiaeTest(patient_id=patient_id, which_set='train', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, leave_one_out_seizure=leave_one_out_seizure, sample_size_second=1, batch_size=20) n_train_samples = dataset.X.shape[0] dataset = EpilepsiaeTest(patient_id=patient_id, which_set='test', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, leave_one_out_seizure=leave_one_out_seizure, sample_size_second=1, batch_size=20) n_test_samples = dataset.X.shape[0] n_total_samples = n_train_samples + n_test_samples f.write('{0},{1},{2},{3},{4}\n'.format(patient_id, leave_one_out_seizure, n_total_samples, n_train_samples, n_test_samples)) if __name__ == '__main__': # compute_n_samples_chbmit() compute_n_samples_epilepsiae()
seizure detection code/Stacked Autoencoders for Seizure Detection/tests/compute_num_samples.py
import os from pylearn2ext.chbmit import CHBMIT from pylearn2ext.epilepsiae import EpilepsiaeTest def compute_n_samples_chbmit(): patients = [1, 3, 5, 8, 10, 20] model_path = '../models' data_path = '/Users/akara/Workspace/data/chbmit' with open(os.path.join(model_path, 'sdae_chbmit_train_test_samples'), 'wb') as f: f.write('patient_id,leave_file_idx,total_samples,train_samples,test_samples\n') for patient_id in patients: files = { 1: range(7), 3: range(7), 5: range(5), 8: range(5), 10: range(7), 20: range(6), } for f_idx in files[patient_id]: leave_one_out_file = f_idx dataset = CHBMIT(patient_id=patient_id, which_set='train', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, transform='single_channel', leave_one_out_file=leave_one_out_file, window_size=256, batch_size=20) n_train_samples = dataset.X.shape[0] dataset = CHBMIT(patient_id=patient_id, which_set='test', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, transform='single_channel', leave_one_out_file=leave_one_out_file, window_size=256, batch_size=20) n_test_samples = dataset.X.shape[0] n_total_samples = n_train_samples + n_test_samples f.write('{0},{1},{2},{3},{4}\n'.format(patient_id, leave_one_out_file, n_total_samples, n_train_samples, n_test_samples)) def compute_n_samples_epilepsiae(): patients = [1] model_path = '../models' data_path = '/Users/akara/Workspace/data/epilepsiae' with open(os.path.join(model_path, 'sdae_epilepsiae_train_test_samples'), 'wb') as f: f.write('patient_id,leave_seizure_idx,total_samples,train_samples,test_samples\n') for patient_id in patients: seizures = { 1: range(6) } for s_idx in seizures[patient_id]: leave_one_out_seizure = s_idx dataset = EpilepsiaeTest(patient_id=patient_id, which_set='train', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, leave_one_out_seizure=leave_one_out_seizure, sample_size_second=1, batch_size=20) n_train_samples = dataset.X.shape[0] dataset = EpilepsiaeTest(patient_id=patient_id, which_set='test', preprocessor_path=os.path.join(model_path, 'sdae_scaler.pkl'), data_dir=data_path, leave_one_out_seizure=leave_one_out_seizure, sample_size_second=1, batch_size=20) n_test_samples = dataset.X.shape[0] n_total_samples = n_train_samples + n_test_samples f.write('{0},{1},{2},{3},{4}\n'.format(patient_id, leave_one_out_seizure, n_total_samples, n_train_samples, n_test_samples)) if __name__ == '__main__': # compute_n_samples_chbmit() compute_n_samples_epilepsiae()
0.250363
0.194884
import contextlib import os import shlex import sys import subprocess import tempfile from pathlib import Path # Branhes to backport to, in order from master, without master FBRANCHES = ['f34', 'f33', 'f32', 'f31'] # Colors BLUE = '\033[94m' GREEN = '\033[92m' END = '\033[0m' # Component swaps COMPONENTS = { 'python3.9': { 'f32': 'python39', 'f31': 'python39', }, 'python3.8': { 'f32': 'python3', 'f31': 'python38', }, 'python3.7': { 'f32': 'python37', 'f31': 'python3', }, 'python3.6': { 'f32': 'python36', 'f31': 'python36', }, 'python3.5': { 'f32': 'python35', 'f31': 'python35', }, } def debug(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def run(cmd): debug(f'{BLUE}$ {cmd}{END}') cmd = shlex.split(cmd) out = subprocess.check_output(cmd, text=True).rstrip() if out: debug(out) return out @contextlib.contextmanager def in_tmp(): original_location = os. getcwd() try: with tempfile.TemporaryDirectory() as d: os.chdir(d) yield finally: os.chdir(original_location) def parse_args(): # TODO?: Add more sophisticated argument parsing # TODO: Get this info from (a link to) Pagure PR if len(sys.argv) < 3: print(f'Usage: {sys.argv[0]} COMPONENT BRANCH [ORIGINAL_USERNAME [MY_USERNAME]]') sys.exit(1) component = sys.argv[1] branch = sys.argv[2] try: original_username = sys.argv[3] except IndexError: original_username = run('whoami') try: my_username = sys.argv[4] except IndexError: my_username = run('whoami') return component, branch, original_username, my_username def source_filenames(sources_path): for line in Path(sources_path).read_text().splitlines(): yield line.partition('(')[-1].partition(')')[0] def git_stuff(component, branch, original_username, my_username): origin = f'ssh://pkgs.fedoraproject.org/rpms/{component}.git' new = f'ssh://pkgs.fedoraproject.org/forks/{original_username}/rpms/{component}.git' backport = f'ssh://pkgs.fedoraproject.org/forks/{my_username}/rpms/{component}.git' run(f'git clone {origin} {component}') os.chdir(component) run(f'git remote add new {new} --fetch') run(f'git remote add backport {backport}') run(f'git remote -v') run(f'git switch --track new/{branch}') branch_ = branch for fbranch in FBRANCHES: try: new_component = COMPONENTS[component][fbranch] except KeyError: remote = 'origin' component_ = component else: origin_ = f'ssh://pkgs.fedoraproject.org/rpms/{new_component}.git' run(f'git remote add origin-{fbranch} {origin_} --fetch') backport_ = f'ssh://pkgs.fedoraproject.org/forks/{my_username}/rpms/{new_component}.git' run(f'git remote add backport-{fbranch} {backport_}') run(f'git remote -v') remote = f'origin-{fbranch}' component_ = new_component try: run(f'git merge-base --is-ancestor {remote}/{fbranch} {branch_}') except subprocess.CalledProcessError: patches = run(f'git format-patch origin/main').splitlines() if component != component_: run(f'fedpkg --name {component} sources') sources = ' '.join(source_filenames('sources')) run(f'fedpkg --name {component_} new-sources {sources}') run(f'git switch --track {remote}/{fbranch}') backport_branch = f'{fbranch}-auto-{original_username}-{branch}' run(f'git switch -c {backport_branch}') for patch in patches: try: run(f'ferrypick {patch} {component_}') except subprocess.CalledProcessError: print('Sorry, this branch needs manual backport :(') sys.exit(1) run(f'git push --force -u backport-{fbranch} {backport_branch}') run(f'git switch {branch}') branch_ = backport_branch link = (f'https://src.fedoraproject.org/fork/{my_username}/' f'rpms/{component_}/diff/{fbranch}..{branch_}') else: link = (f'https://src.fedoraproject.org/fork/{original_username}/' f'rpms/{component_}/diff/{fbranch}..{branch_}') print(f'{GREEN}{link}{END}') def main(): with in_tmp(): git_stuff(*parse_args()) if __name__ == '__main__': main()
branchsync.py
import contextlib import os import shlex import sys import subprocess import tempfile from pathlib import Path # Branhes to backport to, in order from master, without master FBRANCHES = ['f34', 'f33', 'f32', 'f31'] # Colors BLUE = '\033[94m' GREEN = '\033[92m' END = '\033[0m' # Component swaps COMPONENTS = { 'python3.9': { 'f32': 'python39', 'f31': 'python39', }, 'python3.8': { 'f32': 'python3', 'f31': 'python38', }, 'python3.7': { 'f32': 'python37', 'f31': 'python3', }, 'python3.6': { 'f32': 'python36', 'f31': 'python36', }, 'python3.5': { 'f32': 'python35', 'f31': 'python35', }, } def debug(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def run(cmd): debug(f'{BLUE}$ {cmd}{END}') cmd = shlex.split(cmd) out = subprocess.check_output(cmd, text=True).rstrip() if out: debug(out) return out @contextlib.contextmanager def in_tmp(): original_location = os. getcwd() try: with tempfile.TemporaryDirectory() as d: os.chdir(d) yield finally: os.chdir(original_location) def parse_args(): # TODO?: Add more sophisticated argument parsing # TODO: Get this info from (a link to) Pagure PR if len(sys.argv) < 3: print(f'Usage: {sys.argv[0]} COMPONENT BRANCH [ORIGINAL_USERNAME [MY_USERNAME]]') sys.exit(1) component = sys.argv[1] branch = sys.argv[2] try: original_username = sys.argv[3] except IndexError: original_username = run('whoami') try: my_username = sys.argv[4] except IndexError: my_username = run('whoami') return component, branch, original_username, my_username def source_filenames(sources_path): for line in Path(sources_path).read_text().splitlines(): yield line.partition('(')[-1].partition(')')[0] def git_stuff(component, branch, original_username, my_username): origin = f'ssh://pkgs.fedoraproject.org/rpms/{component}.git' new = f'ssh://pkgs.fedoraproject.org/forks/{original_username}/rpms/{component}.git' backport = f'ssh://pkgs.fedoraproject.org/forks/{my_username}/rpms/{component}.git' run(f'git clone {origin} {component}') os.chdir(component) run(f'git remote add new {new} --fetch') run(f'git remote add backport {backport}') run(f'git remote -v') run(f'git switch --track new/{branch}') branch_ = branch for fbranch in FBRANCHES: try: new_component = COMPONENTS[component][fbranch] except KeyError: remote = 'origin' component_ = component else: origin_ = f'ssh://pkgs.fedoraproject.org/rpms/{new_component}.git' run(f'git remote add origin-{fbranch} {origin_} --fetch') backport_ = f'ssh://pkgs.fedoraproject.org/forks/{my_username}/rpms/{new_component}.git' run(f'git remote add backport-{fbranch} {backport_}') run(f'git remote -v') remote = f'origin-{fbranch}' component_ = new_component try: run(f'git merge-base --is-ancestor {remote}/{fbranch} {branch_}') except subprocess.CalledProcessError: patches = run(f'git format-patch origin/main').splitlines() if component != component_: run(f'fedpkg --name {component} sources') sources = ' '.join(source_filenames('sources')) run(f'fedpkg --name {component_} new-sources {sources}') run(f'git switch --track {remote}/{fbranch}') backport_branch = f'{fbranch}-auto-{original_username}-{branch}' run(f'git switch -c {backport_branch}') for patch in patches: try: run(f'ferrypick {patch} {component_}') except subprocess.CalledProcessError: print('Sorry, this branch needs manual backport :(') sys.exit(1) run(f'git push --force -u backport-{fbranch} {backport_branch}') run(f'git switch {branch}') branch_ = backport_branch link = (f'https://src.fedoraproject.org/fork/{my_username}/' f'rpms/{component_}/diff/{fbranch}..{branch_}') else: link = (f'https://src.fedoraproject.org/fork/{original_username}/' f'rpms/{component_}/diff/{fbranch}..{branch_}') print(f'{GREEN}{link}{END}') def main(): with in_tmp(): git_stuff(*parse_args()) if __name__ == '__main__': main()
0.173778
0.096791
import json import logging import boto3 from data_access.data_config import LOG_LEVEL from botocore.exceptions import ClientError from decimal import Decimal logger = logging.getLogger('DDB_Utils') logger.setLevel(LOG_LEVEL) dynamodb = boto3.resource('dynamodb') def convert_num_to_dec(num): """ Convert a number to decimal. This is required when writing floating point numbers to DDB. :param num: a float :return: representation of the number in Decimal """ return Decimal(str(num)) class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) def put_item_ddb(table_name, item, ddb_client=None): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('putting in ddb using ddb client override') else: table = dynamodb.Table(table_name) try: table.put_item(Item=item) logger.info(f'success putting item to {table_name} DDB table.') except ClientError as e: logger.error(f'Error putting item to ddb: {table_name}', exc_info=True) raise e def update_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('updating ddb using ddb client override') else: table = dynamodb.Table(table_name) try: table.update_item(**kwargs) logger.info(f'Success updating item to {table_name} DDB table.') except ClientError as e: logger.error(f'Error updating item to ddb: {table_name}', exc_info=True) raise e def query_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('querying ddb using ddb client override') else: table = dynamodb.Table(table_name) try: response = table.query(**kwargs) for i, item in enumerate(response["Items"]): logger.debug(f'item {i}: {json.dumps(item, cls=DecimalEncoder)}') result = response['Items'] while 'LastEvaluatedKey' in response: response = table.query(ExclusiveStartKey=response['LastEvaluatedKey'], **kwargs) logger.info(f'DDBQuery: Found {len(response["Items"])} items in next page.') result.extend(response['Items']) return result except ClientError as e: logger.error(f'Error querying {table_name} DDB table', exc_info=True) raise e def scan_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('querying ddb using ddb client override') else: table = dynamodb.Table(table_name) try: response = table.scan(**kwargs) for i, item in enumerate(response["Items"]): logger.debug(f'item {i}: {json.dumps(item, cls=DecimalEncoder)}') result = response['Items'] while 'LastEvaluatedKey' in response: response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'], **kwargs) logger.info(f'DDBQuery: Found {len(response["Items"])} items in next page.') result.extend(response['Items']) return result except ClientError as e: logger.error(f'Error scanning {table_name} DDB table', exc_info=True) raise e def get_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('getting ddb data using ddb client override') else: table = dynamodb.Table(table_name) try: valid_args = ['Key', 'AttributesToGet', 'ProjectionExpression'] response = table.get_item(**{k: v for k, v in kwargs.items() if k in valid_args}) except ClientError as e: logger.error('Error querying %s DDB table', table_name, exc_info=True) raise e else: if 'Item' not in response: return None item = response['Item'] logger.info('Success querying %s DDB table. Found item', table_name) logger.debug('item %s', json.dumps(item, cls=DecimalEncoder)) return item class DDBUpdateBuilder(object): def __init__(self, key, table_name, ddb_client=None): self.key = key self.table_name = table_name self.ddb_client = ddb_client self.update_expressions = [] self.expression_attr_names = {} self.expression_attr_vals = {} def update_attr(self, attr_name, attr_value, convert=lambda x: x): self.update_expressions.append(f'#{attr_name} = :{attr_name}') self.expression_attr_names[f'#{attr_name}'] = attr_name self.expression_attr_vals[f':{attr_name}'] = convert(attr_value) def update_params(self): return { 'Key': self.key, 'UpdateExpression': 'set ' + ','.join(self.update_expressions), 'ExpressionAttributeNames': self.expression_attr_names, 'ExpressionAttributeValues': self.expression_attr_vals } def commit(self): if self.update_expressions: ddb_update_item = self.update_params() update_item_ddb(self.table_name, self.ddb_client, **ddb_update_item) else: logger.info('DDBUpdateBuilder: nothing to update. will do nothing.') def __enter__(self): return self def __exit__(self, *exc): logger.info(f'Committing params to dynamodb [{self.table_name}: {self.key}]') self.commit()
lambda/src/data_access/ddb_util.py
import json import logging import boto3 from data_access.data_config import LOG_LEVEL from botocore.exceptions import ClientError from decimal import Decimal logger = logging.getLogger('DDB_Utils') logger.setLevel(LOG_LEVEL) dynamodb = boto3.resource('dynamodb') def convert_num_to_dec(num): """ Convert a number to decimal. This is required when writing floating point numbers to DDB. :param num: a float :return: representation of the number in Decimal """ return Decimal(str(num)) class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) def put_item_ddb(table_name, item, ddb_client=None): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('putting in ddb using ddb client override') else: table = dynamodb.Table(table_name) try: table.put_item(Item=item) logger.info(f'success putting item to {table_name} DDB table.') except ClientError as e: logger.error(f'Error putting item to ddb: {table_name}', exc_info=True) raise e def update_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('updating ddb using ddb client override') else: table = dynamodb.Table(table_name) try: table.update_item(**kwargs) logger.info(f'Success updating item to {table_name} DDB table.') except ClientError as e: logger.error(f'Error updating item to ddb: {table_name}', exc_info=True) raise e def query_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('querying ddb using ddb client override') else: table = dynamodb.Table(table_name) try: response = table.query(**kwargs) for i, item in enumerate(response["Items"]): logger.debug(f'item {i}: {json.dumps(item, cls=DecimalEncoder)}') result = response['Items'] while 'LastEvaluatedKey' in response: response = table.query(ExclusiveStartKey=response['LastEvaluatedKey'], **kwargs) logger.info(f'DDBQuery: Found {len(response["Items"])} items in next page.') result.extend(response['Items']) return result except ClientError as e: logger.error(f'Error querying {table_name} DDB table', exc_info=True) raise e def scan_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('querying ddb using ddb client override') else: table = dynamodb.Table(table_name) try: response = table.scan(**kwargs) for i, item in enumerate(response["Items"]): logger.debug(f'item {i}: {json.dumps(item, cls=DecimalEncoder)}') result = response['Items'] while 'LastEvaluatedKey' in response: response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'], **kwargs) logger.info(f'DDBQuery: Found {len(response["Items"])} items in next page.') result.extend(response['Items']) return result except ClientError as e: logger.error(f'Error scanning {table_name} DDB table', exc_info=True) raise e def get_item_ddb(table_name, ddb_client=None, **kwargs): if ddb_client is not None: table = ddb_client.Table(table_name) logger.info('getting ddb data using ddb client override') else: table = dynamodb.Table(table_name) try: valid_args = ['Key', 'AttributesToGet', 'ProjectionExpression'] response = table.get_item(**{k: v for k, v in kwargs.items() if k in valid_args}) except ClientError as e: logger.error('Error querying %s DDB table', table_name, exc_info=True) raise e else: if 'Item' not in response: return None item = response['Item'] logger.info('Success querying %s DDB table. Found item', table_name) logger.debug('item %s', json.dumps(item, cls=DecimalEncoder)) return item class DDBUpdateBuilder(object): def __init__(self, key, table_name, ddb_client=None): self.key = key self.table_name = table_name self.ddb_client = ddb_client self.update_expressions = [] self.expression_attr_names = {} self.expression_attr_vals = {} def update_attr(self, attr_name, attr_value, convert=lambda x: x): self.update_expressions.append(f'#{attr_name} = :{attr_name}') self.expression_attr_names[f'#{attr_name}'] = attr_name self.expression_attr_vals[f':{attr_name}'] = convert(attr_value) def update_params(self): return { 'Key': self.key, 'UpdateExpression': 'set ' + ','.join(self.update_expressions), 'ExpressionAttributeNames': self.expression_attr_names, 'ExpressionAttributeValues': self.expression_attr_vals } def commit(self): if self.update_expressions: ddb_update_item = self.update_params() update_item_ddb(self.table_name, self.ddb_client, **ddb_update_item) else: logger.info('DDBUpdateBuilder: nothing to update. will do nothing.') def __enter__(self): return self def __exit__(self, *exc): logger.info(f'Committing params to dynamodb [{self.table_name}: {self.key}]') self.commit()
0.480479
0.109873
from typing import List, Dict, Union import numpy as np from overrides import final from ikpy.chain import Chain from ikpy.link import OriginLink, URDFLink, Link from tdw.tdw_utils import TDWUtils from tdw.quaternion_utils import QuaternionUtils from tdw.add_ons.robot import Robot from tdw.librarian import RobotLibrarian, RobotRecord class RobotArm(Robot): """ A robot with a single arm. This class includes an inverse kinematic (IK) solver that allows the robot to reach for a target position. """ def __init__(self, name: str, robot_id: int = 0, position: Dict[str, float] = None, rotation: Dict[str, float] = None, source: Union[RobotLibrarian, RobotRecord] = None): """ :param name: The name of the robot. :param robot_id: The ID of the robot. :param position: The position of the robot. If None, defaults to `{"x": 0, "y": 0, "z": 0}`. :param rotation: The rotation of the robot in Euler angles (degrees). If None, defaults to `{"x": 0, "y": 0, "z": 0}`. :param source: The source file of the robot. If None: The source will be the URL of the robot record in TDW's built-in [`RobotLibrarian`](../librarian/robot_librarian.md). If `RobotRecord`: the source is the URL in the record. If `RobotLibrarian`: The source is the record in the provided `RobotLibrarian` that matches `name`. """ super().__init__(name=name, robot_id=robot_id, position=position, rotation=rotation, source=source) assert self._record is not None, "Record is None." assert len(self._record.ik) > 0, "Record doesn't have IK data." # A list of joint names in the order that they appear in the IK chain. self._joint_order: List[str] = list() # Convert the record data into joint links. links: List[Link] = [OriginLink()] for link in self._record.ik[0]: self._joint_order.append(link["name"]) links.append(URDFLink(name=link["name"], translation_vector=np.array(link["translation_vector"]), orientation=np.array(link["orientation"]), rotation=None if link["rotation"] is None else np.array(link["rotation"]), bounds=link["bounds"])) # Set robot arm IK chain. self._chain: Chain = Chain(name=name, links=links) def reach_for(self, target: Union[Dict[str, float], np.array]) -> None: """ Start to reach for a target position. :param target: The target position. Can be a dictionary or a numpy array. """ angles = self._get_ik_angles(target=target) # Convert the IK solution to degrees. Remove the origin link. angles = [float(np.rad2deg(angle)) for angle in angles[1:]] # Convert the angles to a dictionary of joint targets. targets = dict() for joint_name, angle in zip(self._joint_order, angles): targets[self.static.joint_ids_by_name[joint_name]] = angle self.set_joint_targets(targets=targets) def set_joint_targets(self, targets: Dict[int, Union[float, Dict[str, float]]]) -> None: """ Set target angles or positions for a dictionary of joints. :param targets: A dictionary of joint targets. Key = The ID of the joint. Value = the targets. For spherical joints, this must be a Vector3 dictionary, for example `{"x": 40, "y": 0, "z": 0}` (angles in degrees). For revolute joints, this must be a float (an angle in degrees). For prismatic joints, this must be a float (a distance in meters). """ super().set_joint_targets(targets=targets) def add_joint_forces(self, forces: Dict[int, Union[float, Dict[str, float]]]) -> None: """ Add torques and forces to a dictionary of joints. :param forces: A dictionary of joint forces. Key = The ID of the joint. Value = the targets. For spherical joints, this must be a Vector3 dictionary, for example `{"x": 40, "y": 0, "z": 0}` (torques in Newtons). For revolute joints, this must be a float (a torque in Newtons). For prismatic joints, this must be a float (a force in Newtons). """ super().add_joint_forces(forces=forces) def stop_joints(self, joint_ids: List[int] = None) -> None: """ Stop the joints at their current angles or positions. :param joint_ids: A list of joint IDs. If None, stop all joints. """ super().stop_joints(joint_ids=joint_ids) @final def _get_ik_angles(self, target: Union[Dict[str, float], np.array]) -> List[float]: """ :param target: The target position to reach for. :return: A list of angles of an IK solution in radians. """ # Get the current angles of the joints. initial_angles = [0] for joint_name in self._joint_order: initial_angles.append(self.dynamic.joints[self.static.joint_ids_by_name[joint_name]].angles[0]) initial_angles = np.radians(initial_angles) if isinstance(target, dict): target = TDWUtils.vector3_to_array(target) # Convert the worldspace position to a relative position. relative_target = self._absolute_to_relative(target=target) # Get the IK solution. return self._chain.inverse_kinematics(target_position=relative_target, initial_position=initial_angles) @final def _absolute_to_relative(self, target: np.array) -> np.array: """ :param target: The target position. :return: The target position in relative coordinates. """ return QuaternionUtils.world_to_local_vector(position=target, origin=self.dynamic.transform.position, rotation=self.dynamic.transform.rotation)
Python/tdw/add_ons/robot_arm.py
from typing import List, Dict, Union import numpy as np from overrides import final from ikpy.chain import Chain from ikpy.link import OriginLink, URDFLink, Link from tdw.tdw_utils import TDWUtils from tdw.quaternion_utils import QuaternionUtils from tdw.add_ons.robot import Robot from tdw.librarian import RobotLibrarian, RobotRecord class RobotArm(Robot): """ A robot with a single arm. This class includes an inverse kinematic (IK) solver that allows the robot to reach for a target position. """ def __init__(self, name: str, robot_id: int = 0, position: Dict[str, float] = None, rotation: Dict[str, float] = None, source: Union[RobotLibrarian, RobotRecord] = None): """ :param name: The name of the robot. :param robot_id: The ID of the robot. :param position: The position of the robot. If None, defaults to `{"x": 0, "y": 0, "z": 0}`. :param rotation: The rotation of the robot in Euler angles (degrees). If None, defaults to `{"x": 0, "y": 0, "z": 0}`. :param source: The source file of the robot. If None: The source will be the URL of the robot record in TDW's built-in [`RobotLibrarian`](../librarian/robot_librarian.md). If `RobotRecord`: the source is the URL in the record. If `RobotLibrarian`: The source is the record in the provided `RobotLibrarian` that matches `name`. """ super().__init__(name=name, robot_id=robot_id, position=position, rotation=rotation, source=source) assert self._record is not None, "Record is None." assert len(self._record.ik) > 0, "Record doesn't have IK data." # A list of joint names in the order that they appear in the IK chain. self._joint_order: List[str] = list() # Convert the record data into joint links. links: List[Link] = [OriginLink()] for link in self._record.ik[0]: self._joint_order.append(link["name"]) links.append(URDFLink(name=link["name"], translation_vector=np.array(link["translation_vector"]), orientation=np.array(link["orientation"]), rotation=None if link["rotation"] is None else np.array(link["rotation"]), bounds=link["bounds"])) # Set robot arm IK chain. self._chain: Chain = Chain(name=name, links=links) def reach_for(self, target: Union[Dict[str, float], np.array]) -> None: """ Start to reach for a target position. :param target: The target position. Can be a dictionary or a numpy array. """ angles = self._get_ik_angles(target=target) # Convert the IK solution to degrees. Remove the origin link. angles = [float(np.rad2deg(angle)) for angle in angles[1:]] # Convert the angles to a dictionary of joint targets. targets = dict() for joint_name, angle in zip(self._joint_order, angles): targets[self.static.joint_ids_by_name[joint_name]] = angle self.set_joint_targets(targets=targets) def set_joint_targets(self, targets: Dict[int, Union[float, Dict[str, float]]]) -> None: """ Set target angles or positions for a dictionary of joints. :param targets: A dictionary of joint targets. Key = The ID of the joint. Value = the targets. For spherical joints, this must be a Vector3 dictionary, for example `{"x": 40, "y": 0, "z": 0}` (angles in degrees). For revolute joints, this must be a float (an angle in degrees). For prismatic joints, this must be a float (a distance in meters). """ super().set_joint_targets(targets=targets) def add_joint_forces(self, forces: Dict[int, Union[float, Dict[str, float]]]) -> None: """ Add torques and forces to a dictionary of joints. :param forces: A dictionary of joint forces. Key = The ID of the joint. Value = the targets. For spherical joints, this must be a Vector3 dictionary, for example `{"x": 40, "y": 0, "z": 0}` (torques in Newtons). For revolute joints, this must be a float (a torque in Newtons). For prismatic joints, this must be a float (a force in Newtons). """ super().add_joint_forces(forces=forces) def stop_joints(self, joint_ids: List[int] = None) -> None: """ Stop the joints at their current angles or positions. :param joint_ids: A list of joint IDs. If None, stop all joints. """ super().stop_joints(joint_ids=joint_ids) @final def _get_ik_angles(self, target: Union[Dict[str, float], np.array]) -> List[float]: """ :param target: The target position to reach for. :return: A list of angles of an IK solution in radians. """ # Get the current angles of the joints. initial_angles = [0] for joint_name in self._joint_order: initial_angles.append(self.dynamic.joints[self.static.joint_ids_by_name[joint_name]].angles[0]) initial_angles = np.radians(initial_angles) if isinstance(target, dict): target = TDWUtils.vector3_to_array(target) # Convert the worldspace position to a relative position. relative_target = self._absolute_to_relative(target=target) # Get the IK solution. return self._chain.inverse_kinematics(target_position=relative_target, initial_position=initial_angles) @final def _absolute_to_relative(self, target: np.array) -> np.array: """ :param target: The target position. :return: The target position in relative coordinates. """ return QuaternionUtils.world_to_local_vector(position=target, origin=self.dynamic.transform.position, rotation=self.dynamic.transform.rotation)
0.971497
0.660323
from freetype import * def arrow( x,y, dx, dy, **kwargs): kwargs['shape'] = 'full' kwargs['head_width'] = 30 kwargs['head_length'] = 40 kwargs['length_includes_head'] =True kwargs['facecolor'] = 'k' kwargs['edgecolor'] ='k' kwargs['linewidth'] =.5 plt.arrow(x,y,dx,dy,**kwargs) def double_arrow(x, y, dx, dy, **kwargs): cx,cy = x+dx/2., y+dy/2. dx /= 2.0 dy /= 2.0 arrow(cx,cy,+dx,+dy,**kwargs) arrow(cx,cy,-dx,-dy,**kwargs) def line(x, y, dx, dy, **kwargs): kwargs['color'] = 'k' kwargs['linewidth'] =.5 plt.plot([x,x+dx],[y,y+dy],**kwargs) def point(x, y, r, **kwargs): kwargs['color'] = 'k' plt.scatter([x],[y],r,**kwargs) def text( x,y,text, **kwargs): kwargs['fontsize'] = 18 plt.text(x, y, text, **kwargs) if __name__ == '__main__': import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches face = Face('./Vera.ttf') face.set_char_size( 32*64 ) face.load_char('g') slot = face.glyph bitmap = slot.bitmap width = slot.bitmap.width rows = slot.bitmap.rows pitch = slot.bitmap.pitch outline= slot.outline start, end = 0, 0 VERTS, CODES = [], [] # Iterate over each contour for i in range(len(outline.contours)): end = outline.contours[i] points = outline.points[start:end+1] points.append(points[0]) tags = outline.tags[start:end+1] tags.append(tags[0]) segments = [ [points[0],], ] for j in range(1, len(points) ): segments[-1].append(points[j]) if tags[j] & (1 << 0) and j < (len(points)-1): segments.append( [points[j],] ) verts = [points[0], ] codes = [Path.MOVETO,] for segment in segments: if len(segment) == 2: verts.extend(segment[1:]) codes.extend([Path.LINETO]) elif len(segment) == 3: verts.extend(segment[1:]) codes.extend([Path.CURVE3, Path.CURVE3]) else: verts.append(segment[1]) codes.append(Path.CURVE3) for i in range(1,len(segment)-2): A,B = segment[i], segment[i+1] C = ((A[0]+B[0])/2.0, (A[1]+B[1])/2.0) verts.extend([ C, B ]) codes.extend([ Path.CURVE3, Path.CURVE3]) verts.append(segment[-1]) codes.append(Path.CURVE3) VERTS.extend(verts) CODES.extend(codes) start = end+1 VERTS = np.array(VERTS) x,y = VERTS[:,0], VERTS[:,1] VERTS[:,0], VERTS[:,1] = x, y path = Path(VERTS, CODES) xmin, xmax = x.min(), x.max() ymin, ymax = y.min(), y.max() width,height = xmax-xmin, ymax-ymin dw, dh = 0.2*width, 0.1*height bearing = xmin - slot.metrics.horiBearingX, ymin - slot.metrics.horiBearingY advance = slot.advance origin = bearing figure = plt.figure(figsize=(16,10), frameon=False, facecolor="white") axes = plt.subplot(121, frameon=False, aspect=1) glyph = patches.PathPatch(path, fill = True, facecolor='k', lw=0) plt.xlim(xmin - .25*width, xmax + .75*width) plt.ylim(ymin - .5*height, xmax + .75*height) plt.xticks([]), plt.yticks([]) axes.add_patch(glyph) # Y axis arrow(origin[0], ymin-dh, 0, height+3*dh) # X axis arrow(origin[0]-dw, 0, width+3*dw, 0) # origin point(0,0,50) text( -20, -20, "$origin$", va='top', ha='right') # Bounding box bbox = patches.Rectangle( (xmin,ymin), width, height, fill = False, lw=.5) axes.add_patch(bbox) # Width line(xmin, ymax, 0, 3*dh, linestyle="dotted") text( xmin, ymax+3.25*dh, "$x_{min}$", va='bottom', ha='center') line(xmax, ymax, 0, 3*dh, linestyle="dotted") text( xmax, ymax+3.25*dh, "$x_{max}$", va='bottom', ha='center') double_arrow(xmin, ymax+2.5*dh, width, 0) text(xmin+width/2., ymax+1.75*dh, "$width$", va='bottom', ha='center') # Height line(xmax, ymin, 3*dw, 0, linestyle="dotted") text(xmax+3.25*dw, ymin, "$y_{min}$", va='baseline', ha='left') line(xmax, ymax, 3*dw, 0, linestyle="dotted") text(xmax+3.25*dw, ymax, "$y_{max}$", va='baseline', ha='left') double_arrow(xmax+2.5*dw, ymin, 0, height) text(xmax+2.75*dw, ymin+height/2., "$height$", va='center', ha='left') # Advance point(advance.x,0,50) line(advance.x, 0, 0, ymin-dh, linestyle="dotted") arrow(0, ymin-.5*dh, advance.x, 0) text(advance.x/2., ymin-1.25*dh, "$advance$", va='bottom', ha='center') # Bearing Y arrow(xmax+.25*dw, 0, 0, ymax) text(xmax+.5*dw, ymax/2, "$Y_{bearing}$", va='center', ha='left') # Bearing X arrow(0, ymax/2., xmin, 0) text(-10, ymax/2, "$X_{bearing}$", va='baseline', ha='right') # ------------------------------------------------------------------------- axes = plt.subplot(122, frameon=False, aspect=1) glyph = patches.PathPatch(path, fill = True, facecolor='k', lw=0) axes.add_patch(glyph) plt.xlim(xmin - .25*width, xmax + .75*width) plt.ylim(ymin - .5*height, xmax + .75*height) plt.xticks([]), plt.yticks([]) advance = slot.metrics.vertAdvance x_bearing = slot.metrics.vertBearingX y_bearing = slot.metrics.vertBearingY # Y axis arrow(xmin-x_bearing, ymax+y_bearing+2*dh, 0, -advance-3*dh) # X axis arrow(xmin-2*dw, ymax+y_bearing, width+4*dw, 0) # origin point( xmin-x_bearing, ymax+y_bearing, 50) text( xmin-x_bearing-30, ymax+y_bearing+10, "$origin$", va='bottom', ha='right') # Bounding box bbox = patches.Rectangle( (xmin,ymin), width, height, fill = False, lw=.5) axes.add_patch(bbox) # # Advance point(xmin-x_bearing, ymax+y_bearing-advance, 50) line(xmin-x_bearing, ymax+y_bearing-advance, xmax-dw, 0, linestyle="dotted") arrow(xmax+dw, ymax+y_bearing, 0, -advance) text(xmax+1.25*dw, ymax+y_bearing-advance/2., "$advance$", va='baseline', ha='left') # Width line(xmin, ymin, 0, -4*dh, linestyle="dotted") text( xmin, ymin-4.25*dh, "$x_{min}$", va='top', ha='center') line(xmax, ymin, 0, -4*dh, linestyle="dotted") text( xmax, ymin-4.25*dh, "$x_{max}$", va='top', ha='center') double_arrow(xmin, ymin-3.5*dh, width, 0) text(xmin+width/2., ymin-3.75*dh, "$width$", va='top', ha='center') # Height line(xmin, ymin, -3*dw, 0, linestyle="dotted") text(xmin-1.5*dw, ymin, "$y_{min}$", va='baseline', ha='right') line(xmin, ymax, -3*dw, 0, linestyle="dotted") text(xmin-1.5*dw, ymax, "$y_{max}$", va='baseline', ha='right') double_arrow(xmin-.5*dw, ymin, 0, height) text(xmin-.75*dw, ymin+height/2., "$height$", va='center', ha='right') #point(xmin-x_bearing, ymax+y_bearing, 50) # Bearing Y arrow(xmax-.5*dw, ymax+y_bearing, 0, -y_bearing) text(xmax-.5*dw, ymax+y_bearing+.25*dh, "$Y_{bearing}$", va='bottom', ha='center') # # Bearing X line(xmin, ymax, 0, 3*dh, linestyle="dotted") arrow(xmin-x_bearing, ymax+y_bearing+dh, x_bearing, 0) text(xmin-.25*dw, ymax+y_bearing+dh, "$X_{bearing}$", va='baseline', ha='right') plt.savefig('glyph-metrics.pdf') plt.show()
examples/glyph-metrics.py
from freetype import * def arrow( x,y, dx, dy, **kwargs): kwargs['shape'] = 'full' kwargs['head_width'] = 30 kwargs['head_length'] = 40 kwargs['length_includes_head'] =True kwargs['facecolor'] = 'k' kwargs['edgecolor'] ='k' kwargs['linewidth'] =.5 plt.arrow(x,y,dx,dy,**kwargs) def double_arrow(x, y, dx, dy, **kwargs): cx,cy = x+dx/2., y+dy/2. dx /= 2.0 dy /= 2.0 arrow(cx,cy,+dx,+dy,**kwargs) arrow(cx,cy,-dx,-dy,**kwargs) def line(x, y, dx, dy, **kwargs): kwargs['color'] = 'k' kwargs['linewidth'] =.5 plt.plot([x,x+dx],[y,y+dy],**kwargs) def point(x, y, r, **kwargs): kwargs['color'] = 'k' plt.scatter([x],[y],r,**kwargs) def text( x,y,text, **kwargs): kwargs['fontsize'] = 18 plt.text(x, y, text, **kwargs) if __name__ == '__main__': import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches face = Face('./Vera.ttf') face.set_char_size( 32*64 ) face.load_char('g') slot = face.glyph bitmap = slot.bitmap width = slot.bitmap.width rows = slot.bitmap.rows pitch = slot.bitmap.pitch outline= slot.outline start, end = 0, 0 VERTS, CODES = [], [] # Iterate over each contour for i in range(len(outline.contours)): end = outline.contours[i] points = outline.points[start:end+1] points.append(points[0]) tags = outline.tags[start:end+1] tags.append(tags[0]) segments = [ [points[0],], ] for j in range(1, len(points) ): segments[-1].append(points[j]) if tags[j] & (1 << 0) and j < (len(points)-1): segments.append( [points[j],] ) verts = [points[0], ] codes = [Path.MOVETO,] for segment in segments: if len(segment) == 2: verts.extend(segment[1:]) codes.extend([Path.LINETO]) elif len(segment) == 3: verts.extend(segment[1:]) codes.extend([Path.CURVE3, Path.CURVE3]) else: verts.append(segment[1]) codes.append(Path.CURVE3) for i in range(1,len(segment)-2): A,B = segment[i], segment[i+1] C = ((A[0]+B[0])/2.0, (A[1]+B[1])/2.0) verts.extend([ C, B ]) codes.extend([ Path.CURVE3, Path.CURVE3]) verts.append(segment[-1]) codes.append(Path.CURVE3) VERTS.extend(verts) CODES.extend(codes) start = end+1 VERTS = np.array(VERTS) x,y = VERTS[:,0], VERTS[:,1] VERTS[:,0], VERTS[:,1] = x, y path = Path(VERTS, CODES) xmin, xmax = x.min(), x.max() ymin, ymax = y.min(), y.max() width,height = xmax-xmin, ymax-ymin dw, dh = 0.2*width, 0.1*height bearing = xmin - slot.metrics.horiBearingX, ymin - slot.metrics.horiBearingY advance = slot.advance origin = bearing figure = plt.figure(figsize=(16,10), frameon=False, facecolor="white") axes = plt.subplot(121, frameon=False, aspect=1) glyph = patches.PathPatch(path, fill = True, facecolor='k', lw=0) plt.xlim(xmin - .25*width, xmax + .75*width) plt.ylim(ymin - .5*height, xmax + .75*height) plt.xticks([]), plt.yticks([]) axes.add_patch(glyph) # Y axis arrow(origin[0], ymin-dh, 0, height+3*dh) # X axis arrow(origin[0]-dw, 0, width+3*dw, 0) # origin point(0,0,50) text( -20, -20, "$origin$", va='top', ha='right') # Bounding box bbox = patches.Rectangle( (xmin,ymin), width, height, fill = False, lw=.5) axes.add_patch(bbox) # Width line(xmin, ymax, 0, 3*dh, linestyle="dotted") text( xmin, ymax+3.25*dh, "$x_{min}$", va='bottom', ha='center') line(xmax, ymax, 0, 3*dh, linestyle="dotted") text( xmax, ymax+3.25*dh, "$x_{max}$", va='bottom', ha='center') double_arrow(xmin, ymax+2.5*dh, width, 0) text(xmin+width/2., ymax+1.75*dh, "$width$", va='bottom', ha='center') # Height line(xmax, ymin, 3*dw, 0, linestyle="dotted") text(xmax+3.25*dw, ymin, "$y_{min}$", va='baseline', ha='left') line(xmax, ymax, 3*dw, 0, linestyle="dotted") text(xmax+3.25*dw, ymax, "$y_{max}$", va='baseline', ha='left') double_arrow(xmax+2.5*dw, ymin, 0, height) text(xmax+2.75*dw, ymin+height/2., "$height$", va='center', ha='left') # Advance point(advance.x,0,50) line(advance.x, 0, 0, ymin-dh, linestyle="dotted") arrow(0, ymin-.5*dh, advance.x, 0) text(advance.x/2., ymin-1.25*dh, "$advance$", va='bottom', ha='center') # Bearing Y arrow(xmax+.25*dw, 0, 0, ymax) text(xmax+.5*dw, ymax/2, "$Y_{bearing}$", va='center', ha='left') # Bearing X arrow(0, ymax/2., xmin, 0) text(-10, ymax/2, "$X_{bearing}$", va='baseline', ha='right') # ------------------------------------------------------------------------- axes = plt.subplot(122, frameon=False, aspect=1) glyph = patches.PathPatch(path, fill = True, facecolor='k', lw=0) axes.add_patch(glyph) plt.xlim(xmin - .25*width, xmax + .75*width) plt.ylim(ymin - .5*height, xmax + .75*height) plt.xticks([]), plt.yticks([]) advance = slot.metrics.vertAdvance x_bearing = slot.metrics.vertBearingX y_bearing = slot.metrics.vertBearingY # Y axis arrow(xmin-x_bearing, ymax+y_bearing+2*dh, 0, -advance-3*dh) # X axis arrow(xmin-2*dw, ymax+y_bearing, width+4*dw, 0) # origin point( xmin-x_bearing, ymax+y_bearing, 50) text( xmin-x_bearing-30, ymax+y_bearing+10, "$origin$", va='bottom', ha='right') # Bounding box bbox = patches.Rectangle( (xmin,ymin), width, height, fill = False, lw=.5) axes.add_patch(bbox) # # Advance point(xmin-x_bearing, ymax+y_bearing-advance, 50) line(xmin-x_bearing, ymax+y_bearing-advance, xmax-dw, 0, linestyle="dotted") arrow(xmax+dw, ymax+y_bearing, 0, -advance) text(xmax+1.25*dw, ymax+y_bearing-advance/2., "$advance$", va='baseline', ha='left') # Width line(xmin, ymin, 0, -4*dh, linestyle="dotted") text( xmin, ymin-4.25*dh, "$x_{min}$", va='top', ha='center') line(xmax, ymin, 0, -4*dh, linestyle="dotted") text( xmax, ymin-4.25*dh, "$x_{max}$", va='top', ha='center') double_arrow(xmin, ymin-3.5*dh, width, 0) text(xmin+width/2., ymin-3.75*dh, "$width$", va='top', ha='center') # Height line(xmin, ymin, -3*dw, 0, linestyle="dotted") text(xmin-1.5*dw, ymin, "$y_{min}$", va='baseline', ha='right') line(xmin, ymax, -3*dw, 0, linestyle="dotted") text(xmin-1.5*dw, ymax, "$y_{max}$", va='baseline', ha='right') double_arrow(xmin-.5*dw, ymin, 0, height) text(xmin-.75*dw, ymin+height/2., "$height$", va='center', ha='right') #point(xmin-x_bearing, ymax+y_bearing, 50) # Bearing Y arrow(xmax-.5*dw, ymax+y_bearing, 0, -y_bearing) text(xmax-.5*dw, ymax+y_bearing+.25*dh, "$Y_{bearing}$", va='bottom', ha='center') # # Bearing X line(xmin, ymax, 0, 3*dh, linestyle="dotted") arrow(xmin-x_bearing, ymax+y_bearing+dh, x_bearing, 0) text(xmin-.25*dw, ymax+y_bearing+dh, "$X_{bearing}$", va='baseline', ha='right') plt.savefig('glyph-metrics.pdf') plt.show()
0.403214
0.294526
from html.parser import HTMLParser import json class TableMiningParser(HTMLParser): def __init__(self): super().__init__() self.n_tbody = 0 self.content_list = [] self.content_row = [] self.in_header_row = False self.in_tr = False self.in_td = False self.analyze_finished = False self.in_link_in_td = False def handle_starttag(self, tag, attrs): if self.analyze_finished: return if tag == "tbody": self.n_tbody += 1 if self.n_tbody == 1: if tag == "tr": self.in_tr = True elif self.in_tr: if tag == "th": self.in_header_row = True elif tag == "td": self.in_td = True elif self.in_td and tag == "a": self.in_link_in_td = True def handle_endtag(self, tag): if self.analyze_finished: return if tag == "tbody": self.n_tbody -= 1 if self.n_tbody == 0: self.analyze_finished = True if self.n_tbody == 1: if self.in_tr: if self.in_td: if tag == "td": self.in_td = False elif self.in_link_in_td and tag == "a": self.in_link_in_td = False elif tag == "tr": self.in_tr = False if not self.in_header_row: self.content_list.append(self.content_row) self.content_row = [] self.in_header_row = False def handle_data(self, data): if self.n_tbody == 1 and self.in_tr and self.in_td: cleaned_data = data.strip().strip("\u200E\u200F") if self.in_link_in_td or cleaned_data != "": self.content_row.append(cleaned_data) def convert_row(row): ( locale_id_str, locale_name, locale_english_full_name, language_english_name, locale_local_name, acp_str, oemcp_str, country_abbrev, language_abbrev, ) = row locale_id = int(locale_id_str, 16) acp = int(acp_str) oemcp = int(oemcp_str) return { "locale": locale_name, "locale_id": locale_id, "language": language_english_name, "locale_name_english": locale_english_full_name, "locale_name_local": locale_local_name, "acp": acp, "oemcp": oemcp, "country_abbrev": country_abbrev, "language_abbrev": language_abbrev, } parser = TableMiningParser() with open("nls_info.html", encoding="UTF-8") as f: parser.feed(f.read()) content_list = [convert_row(r) for r in parser.content_list] with open("nls_info.json", "w", encoding="UTF-8") as f: json.dump(content_list, f)
assets/extract_to_json.py
from html.parser import HTMLParser import json class TableMiningParser(HTMLParser): def __init__(self): super().__init__() self.n_tbody = 0 self.content_list = [] self.content_row = [] self.in_header_row = False self.in_tr = False self.in_td = False self.analyze_finished = False self.in_link_in_td = False def handle_starttag(self, tag, attrs): if self.analyze_finished: return if tag == "tbody": self.n_tbody += 1 if self.n_tbody == 1: if tag == "tr": self.in_tr = True elif self.in_tr: if tag == "th": self.in_header_row = True elif tag == "td": self.in_td = True elif self.in_td and tag == "a": self.in_link_in_td = True def handle_endtag(self, tag): if self.analyze_finished: return if tag == "tbody": self.n_tbody -= 1 if self.n_tbody == 0: self.analyze_finished = True if self.n_tbody == 1: if self.in_tr: if self.in_td: if tag == "td": self.in_td = False elif self.in_link_in_td and tag == "a": self.in_link_in_td = False elif tag == "tr": self.in_tr = False if not self.in_header_row: self.content_list.append(self.content_row) self.content_row = [] self.in_header_row = False def handle_data(self, data): if self.n_tbody == 1 and self.in_tr and self.in_td: cleaned_data = data.strip().strip("\u200E\u200F") if self.in_link_in_td or cleaned_data != "": self.content_row.append(cleaned_data) def convert_row(row): ( locale_id_str, locale_name, locale_english_full_name, language_english_name, locale_local_name, acp_str, oemcp_str, country_abbrev, language_abbrev, ) = row locale_id = int(locale_id_str, 16) acp = int(acp_str) oemcp = int(oemcp_str) return { "locale": locale_name, "locale_id": locale_id, "language": language_english_name, "locale_name_english": locale_english_full_name, "locale_name_local": locale_local_name, "acp": acp, "oemcp": oemcp, "country_abbrev": country_abbrev, "language_abbrev": language_abbrev, } parser = TableMiningParser() with open("nls_info.html", encoding="UTF-8") as f: parser.feed(f.read()) content_list = [convert_row(r) for r in parser.content_list] with open("nls_info.json", "w", encoding="UTF-8") as f: json.dump(content_list, f)
0.45302
0.160135
import sys, os, os.path import subprocess import ctypes def name2lib(name): """Convert a name 'foo' into the OS dependent library name:: libfoo.so libfoo.dylib foo.dll """ _prefix = "" if os.name == 'nt' else 'lib' _dll = "dll" if os.name == '.nt' else '.so' if sys.platform == 'darwin': _dll = '.dylib' return _prefix + name + _dll def lib2name(lib): """Convert an OS dependent library name to the base name:: libfoo.so.0.1 => foo foo.dll => foo """ if lib.startswith('lib'): lib = lib[4:] return lib.split('.',1)[0] def expand(path): """Return the abspath for a given path """ return os.path.abspath(os.path.expanduser(path)) def find_library(libname, paths=[]): """Search the system (and optional paths) for a fully qualified library name. Uses system configurations, PATH, LD_LIBRARY_PATH and DY_LDLIBRARY_PATH:: find_library('foo') => /usr/lib/libfoo.so.0.1 Search order: * 'paths' tuple argument in order * env LD_LIBRARY_PATH in order * env DYLD_LIBRARY_PATH in order * env PATH in order * system paths as determined by ctypes .. NOTE:: On OSX, the system python will often not work due to env restrictions. Using virtualenv or similar will work around this restriction even if based on the system python. """ paths = [expand(p) for p in paths] name = lib2name(libname) env = os.environ.copy() LD=env.get('LD_LIBRARY_PATH', "") DY=env.get('DYLD_LIBRARY_PATH', "") PA=env.get('PATH', "") search_in = paths[:] if LD: search_in.append(LD) if DY: search_in.append(DY) if PA: search_in.append(PA) full_search_path = os.pathsep.join(search_in) search_env = 'LD_LIBRARY_PATH' cmd_prefix = '' if os.name == 'nt': search_env = 'PATH' elif sys.platform == 'darwin': search_env = 'DYLD_LIBRARY_PATH' cmd_prefix = 'export %s="%s"; ' % (search_env, full_search_path) env[search_env]=full_search_path ## OSX really confuses things. Only way to make it work. ## even plumbum fails. command = '%s"%s" -c "import ctypes.util; print(ctypes.util.find_library(\'%s\'))"' % ( cmd_prefix, sys.executable, name) sp = subprocess.Popen(command, shell=True, env=env, stdout=subprocess.PIPE) found = sp.communicate()[0].strip() if found == 'None': return None return found
src/clients/python/trtis_cidmgr/util.py
import sys, os, os.path import subprocess import ctypes def name2lib(name): """Convert a name 'foo' into the OS dependent library name:: libfoo.so libfoo.dylib foo.dll """ _prefix = "" if os.name == 'nt' else 'lib' _dll = "dll" if os.name == '.nt' else '.so' if sys.platform == 'darwin': _dll = '.dylib' return _prefix + name + _dll def lib2name(lib): """Convert an OS dependent library name to the base name:: libfoo.so.0.1 => foo foo.dll => foo """ if lib.startswith('lib'): lib = lib[4:] return lib.split('.',1)[0] def expand(path): """Return the abspath for a given path """ return os.path.abspath(os.path.expanduser(path)) def find_library(libname, paths=[]): """Search the system (and optional paths) for a fully qualified library name. Uses system configurations, PATH, LD_LIBRARY_PATH and DY_LDLIBRARY_PATH:: find_library('foo') => /usr/lib/libfoo.so.0.1 Search order: * 'paths' tuple argument in order * env LD_LIBRARY_PATH in order * env DYLD_LIBRARY_PATH in order * env PATH in order * system paths as determined by ctypes .. NOTE:: On OSX, the system python will often not work due to env restrictions. Using virtualenv or similar will work around this restriction even if based on the system python. """ paths = [expand(p) for p in paths] name = lib2name(libname) env = os.environ.copy() LD=env.get('LD_LIBRARY_PATH', "") DY=env.get('DYLD_LIBRARY_PATH', "") PA=env.get('PATH', "") search_in = paths[:] if LD: search_in.append(LD) if DY: search_in.append(DY) if PA: search_in.append(PA) full_search_path = os.pathsep.join(search_in) search_env = 'LD_LIBRARY_PATH' cmd_prefix = '' if os.name == 'nt': search_env = 'PATH' elif sys.platform == 'darwin': search_env = 'DYLD_LIBRARY_PATH' cmd_prefix = 'export %s="%s"; ' % (search_env, full_search_path) env[search_env]=full_search_path ## OSX really confuses things. Only way to make it work. ## even plumbum fails. command = '%s"%s" -c "import ctypes.util; print(ctypes.util.find_library(\'%s\'))"' % ( cmd_prefix, sys.executable, name) sp = subprocess.Popen(command, shell=True, env=env, stdout=subprocess.PIPE) found = sp.communicate()[0].strip() if found == 'None': return None return found
0.349422
0.082846
from cleandata import tag_to_pos from cleandata import pos_to_tag from cleandata import tagid from cleandata import tagname import pandas as pd from collections import defaultdict import math import numpy as np import itertools import csv import sys import gc from heapq import nlargest comm = defaultdict(lambda: defaultdict(lambda:0)) # this function calculates google distance def gdistance(tag1,tag2): common = sum([x == y for x in tag_to_pos[tag1] for y in tag_to_pos[tag2]] ) comm[tag1][tag2] = comm[tag2][tag1] = common if(common == 0): return float('inf') nume = max(math.log(len(tag_to_pos[tag1])),math.log(len(tag_to_pos[tag2])))-math.log(common) #nume = max((len(tag_to_pos[tag1])),(len(tag_to_pos[tag2])))-(common) denom = math.log(len(pos_to_tag)) - min(math.log(len(tag_to_pos[tag1])),math.log(len(tag_to_pos[tag2]))) #denom = (len(pos_to_tag)) - min((len(tag_to_pos[tag1])),(len(tag_to_pos[tag2]))) return nume/denom # claculates subsumption def subsum(tag1,tag2): if(comm[tag1][tag2] == 0): return 0 num = sim[tag1][tag2] #den = 1 den = 0 for i in sim[tag2]: try: if(comm[tag2][i] != 0): den += sim[tag2][i] except: continue return (num/den) sim = defaultdict(lambda: defaultdict(lambda:0)) # similarity calculation for comb in itertools.combinations(tag_to_pos.keys(),2): #print(gdistance(comb[0],comb[1])) sim[comb[0]][comb[1]] = sim[comb[1]][comb[0]] = 1/(math.exp(gdistance(comb[0],comb[1]))) #print(sim) sim_new = {} comm_new = {} # converting defaultdict to dict so that it can be written to a pickle file. Or else create normal dict insted of defaultdict in the beginning itself. for i in sim.keys(): sim_new[i] = {} comm_new[i] = {} for j in sim[i].keys(): sim_new[i][j] = sim[i][j] comm_new[i][j] = comm[i][j] #print(sim_new) import pickle # wrting to pickle files with open('sim.p', 'wb') as fp: pickle.dump(sim_new, fp, protocol=pickle.HIGHEST_PROTOCOL) with open('comm.p', 'wb') as fp: pickle.dump(comm_new, fp, protocol=pickle.HIGHEST_PROTOCOL) print("sim done") # subsumption calculation p = defaultdict(lambda: defaultdict(lambda:0)) p_new = {} for comb in itertools.combinations(tag_to_pos.keys(),2): p[comb[0]][comb[1]] = subsum(comb[0],comb[1]) * 10000# multiplying by 10000 for scaling p_new[comb[0]][comb[1]] = p[comb[0]][comb[1]] #print(p) # wrting to a pickle file with open('sub.p', 'wb') as fp: pickle.dump(p_new, fp, protocol=pickle.HIGHEST_PROTOCOL) print("p done") h = defaultdict(lambda : 0) # finding entropy 'h' for each tag for i in tag_to_pos.keys(): for j in tag_to_pos.keys(): #print(h[i]) if(i!=j): #if(p[i][j] <= 0): #print(p[i][j],"..") h[i] -= p[i][j]*math.log( 1 + p[i][j]) #print(h) h = {k:v for k,v in sorted(h.items(),key = lambda item: item[1])} #print(h) print("h done") def N_large(c): count = len(p[c]) if count > 150: count = int(count/25) elif count > 100: count = int(count/20) elif count > 50: count = int(count/10) elif count > 10 : count = int(count/5) else: count = int(count/2) top = nlargest(count,p[c],key=p[c].get) return top v = set() filt = [] # forming edges for i in h: #print(i,h[i]) v.add(i) #print(tagname[i]) top = [] top = N_large(i) for j in top: news ={} if(h[i] < h[j] and comm[i][j] > 0):#(0.05)*(max(len(tag_to_pos[i]),len(tag_to_pos[j])))):############ should add some threshold news["Source"] = i news["Target"] = j news["Weight"] = p[i][j] filt.append(news) # wrting edges with open("./datacsv/edges.csv",'w') as csvfile: writer = csv.DictWriter(csvfile,delimiter = ',' ,fieldnames=['Source','Target','Weight']) writer.writeheader() writer.writerows(filt) ################# should also create nodes file df = pd.read_csv("./datacsv/Filtags.csv",header=0,delimiter=',') df.rename(columns = {'Id' : 'id','TagName' : 'label'},inplace = True) df.update('"' + df[['label']].astype(str) + '"') del df['Count'] print(df.to_string(index = False)) df.to_csv("./datacsv/nodes.csv",index=False,sep=',')
Ontology.py
from cleandata import tag_to_pos from cleandata import pos_to_tag from cleandata import tagid from cleandata import tagname import pandas as pd from collections import defaultdict import math import numpy as np import itertools import csv import sys import gc from heapq import nlargest comm = defaultdict(lambda: defaultdict(lambda:0)) # this function calculates google distance def gdistance(tag1,tag2): common = sum([x == y for x in tag_to_pos[tag1] for y in tag_to_pos[tag2]] ) comm[tag1][tag2] = comm[tag2][tag1] = common if(common == 0): return float('inf') nume = max(math.log(len(tag_to_pos[tag1])),math.log(len(tag_to_pos[tag2])))-math.log(common) #nume = max((len(tag_to_pos[tag1])),(len(tag_to_pos[tag2])))-(common) denom = math.log(len(pos_to_tag)) - min(math.log(len(tag_to_pos[tag1])),math.log(len(tag_to_pos[tag2]))) #denom = (len(pos_to_tag)) - min((len(tag_to_pos[tag1])),(len(tag_to_pos[tag2]))) return nume/denom # claculates subsumption def subsum(tag1,tag2): if(comm[tag1][tag2] == 0): return 0 num = sim[tag1][tag2] #den = 1 den = 0 for i in sim[tag2]: try: if(comm[tag2][i] != 0): den += sim[tag2][i] except: continue return (num/den) sim = defaultdict(lambda: defaultdict(lambda:0)) # similarity calculation for comb in itertools.combinations(tag_to_pos.keys(),2): #print(gdistance(comb[0],comb[1])) sim[comb[0]][comb[1]] = sim[comb[1]][comb[0]] = 1/(math.exp(gdistance(comb[0],comb[1]))) #print(sim) sim_new = {} comm_new = {} # converting defaultdict to dict so that it can be written to a pickle file. Or else create normal dict insted of defaultdict in the beginning itself. for i in sim.keys(): sim_new[i] = {} comm_new[i] = {} for j in sim[i].keys(): sim_new[i][j] = sim[i][j] comm_new[i][j] = comm[i][j] #print(sim_new) import pickle # wrting to pickle files with open('sim.p', 'wb') as fp: pickle.dump(sim_new, fp, protocol=pickle.HIGHEST_PROTOCOL) with open('comm.p', 'wb') as fp: pickle.dump(comm_new, fp, protocol=pickle.HIGHEST_PROTOCOL) print("sim done") # subsumption calculation p = defaultdict(lambda: defaultdict(lambda:0)) p_new = {} for comb in itertools.combinations(tag_to_pos.keys(),2): p[comb[0]][comb[1]] = subsum(comb[0],comb[1]) * 10000# multiplying by 10000 for scaling p_new[comb[0]][comb[1]] = p[comb[0]][comb[1]] #print(p) # wrting to a pickle file with open('sub.p', 'wb') as fp: pickle.dump(p_new, fp, protocol=pickle.HIGHEST_PROTOCOL) print("p done") h = defaultdict(lambda : 0) # finding entropy 'h' for each tag for i in tag_to_pos.keys(): for j in tag_to_pos.keys(): #print(h[i]) if(i!=j): #if(p[i][j] <= 0): #print(p[i][j],"..") h[i] -= p[i][j]*math.log( 1 + p[i][j]) #print(h) h = {k:v for k,v in sorted(h.items(),key = lambda item: item[1])} #print(h) print("h done") def N_large(c): count = len(p[c]) if count > 150: count = int(count/25) elif count > 100: count = int(count/20) elif count > 50: count = int(count/10) elif count > 10 : count = int(count/5) else: count = int(count/2) top = nlargest(count,p[c],key=p[c].get) return top v = set() filt = [] # forming edges for i in h: #print(i,h[i]) v.add(i) #print(tagname[i]) top = [] top = N_large(i) for j in top: news ={} if(h[i] < h[j] and comm[i][j] > 0):#(0.05)*(max(len(tag_to_pos[i]),len(tag_to_pos[j])))):############ should add some threshold news["Source"] = i news["Target"] = j news["Weight"] = p[i][j] filt.append(news) # wrting edges with open("./datacsv/edges.csv",'w') as csvfile: writer = csv.DictWriter(csvfile,delimiter = ',' ,fieldnames=['Source','Target','Weight']) writer.writeheader() writer.writerows(filt) ################# should also create nodes file df = pd.read_csv("./datacsv/Filtags.csv",header=0,delimiter=',') df.rename(columns = {'Id' : 'id','TagName' : 'label'},inplace = True) df.update('"' + df[['label']].astype(str) + '"') del df['Count'] print(df.to_string(index = False)) df.to_csv("./datacsv/nodes.csv",index=False,sep=',')
0.046965
0.522811
from flask import Flask from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) devices = {} # A dictionary of id to devices SERVER_CONFIG = {"ice_servers": [{"urls":["stun:stun.l.google.com:19302"]}], "message_type": "config"} def send_error(msg): print('ERROR -', msg) def send_server_config(ws): config_json = json.dumps(SERVER_CONFIG) ws.send(config_json) def send_data_ws(ws, data): data_json = json.dumps(data) ws.send(data_json) class Client: """Client class for users that connect to devices""" client_id = None device = None ws = None def __init__(self, ws): self.ws = ws def send_device_info(self): client_ws = self.ws device_info_msg = {} device_info_msg['message_type'] = 'device_info' device_info_msg['device_info'] = self.device.device_info send_data_ws(client_ws, device_info_msg) def forward_device_message(self, message): device_msg = {} device_msg['message_type'] = 'device_msg' device_msg['payload'] = message['payload'] send_data_ws(self.ws, device_msg) def handle_connect(self, message): """Connects client user to device""" if 'device_id' not in message: send_error('Missing device_id field.') return device_id = message['device_id'] if self.client_id: send_error('Attempt to connect to multiple devices over same websocket.') else: send_server_config(self.ws) if device_id not in devices: send_error(f'Device id {device_id} not registered.') else: self.device = devices[device_id] self.device.register_client(self) print(f'Connected client {self.client_id} to device {self.device.device_id}.') self.send_device_info() def handle_forward(self, message): """Handle forward for client""" if not self.client_id: send_error('No device associated to client.') elif 'payload' not in message: send_error('Missing payload field.') else: self.device.forward_client_message(self.client_id, message) print(f'Forwarded message from client {self.client_id} to device {self.device.device_id}.') def process_request(self, message): if 'message_type' not in message: send_error('Missing field message_type') elif message['message_type'] == 'connect': self.handle_connect(message) elif message['message_type'] == 'forward': self.handle_forward(message) else: send_error(f'Unknown message type: {message["message_type"]}') class Device: client_number = 1 device_id = None device_info = None clients = {} def __init__(self, ws): self.ws = ws def forward_client_message(self, client_id, message): client_msg = {} client_msg['message_type'] = 'client_msg' client_msg['client_id'] = client_id client_msg['payload'] = message['payload'] send_data_ws(self.ws, client_msg) def handle_registration(self, message): """Registers device id and info in device list and sends config""" if 'device_id' not in message: send_error('Missing device id in registration request') return device_id = message['device_id'] if message['device_id'] in devices: send_error(f'Device with id {device_id} already exists.') elif 'device_info' not in message: send_error('Missing device info in registration request.') else: devices[device_id] = self self.device_id = device_id self.device_info = message['device_info'] send_server_config(self.ws) print(f'Registered device with id {device_id}') def handle_forward(self, message): """Handles forward for device""" if 'client_id' not in message: send_error('Missing client id in forward message.') elif 'payload' not in message: send_error('Missing payload field in forward message.') elif message['client_id'] not in self.clients: send_error(f'Unregistered client id {message["client_id"]}.') else: client_id = message['client_id'] client = self.clients[client_id] client.forward_device_message(message) print(f'Forwarded message from device {self.device_id} to client {client_id}.') def process_request(self, message): if 'message_type' not in message: send_error('Missing field message_type') elif message['message_type'] == 'register': self.handle_registration(message) elif message['message_type'] == 'forward': self.handle_forward(message) else: send_error(f'Unknown message type: {message["message_type"]}') def register_client(self, client): client_id = self.client_number client.client_id = client_id self.clients[client_id] = client self.client_number += 1 def unregister_client(self, client_id): self.clients.pop(client_id) @sockets.route('/register_device') def register_device(ws): print('ws connected to /register_device') device = Device(ws) try: while not ws.closed: raw_message = ws.receive() message = json.loads(raw_message) device.process_request(message) except: if device.device_id: devices.pop(device.device_id) print(f'deleted device {device.device_id} from device list.') @sockets.route('/connect_client') def connect_client(ws): print('ws connected to /connect_client') client = Client(ws) try: while not ws.closed: raw_message = ws.receive() message = json.loads(raw_message) client.process_request(message) except: if client.device: device_id = client.device.device_id devices[device_id].unregister_client(client.client_id) print(f'unregistered client {client.client_id} from device {device_id}')
sig_server.py
from flask import Flask from flask_sockets import Sockets import json app = Flask(__name__) sockets = Sockets(app) devices = {} # A dictionary of id to devices SERVER_CONFIG = {"ice_servers": [{"urls":["stun:stun.l.google.com:19302"]}], "message_type": "config"} def send_error(msg): print('ERROR -', msg) def send_server_config(ws): config_json = json.dumps(SERVER_CONFIG) ws.send(config_json) def send_data_ws(ws, data): data_json = json.dumps(data) ws.send(data_json) class Client: """Client class for users that connect to devices""" client_id = None device = None ws = None def __init__(self, ws): self.ws = ws def send_device_info(self): client_ws = self.ws device_info_msg = {} device_info_msg['message_type'] = 'device_info' device_info_msg['device_info'] = self.device.device_info send_data_ws(client_ws, device_info_msg) def forward_device_message(self, message): device_msg = {} device_msg['message_type'] = 'device_msg' device_msg['payload'] = message['payload'] send_data_ws(self.ws, device_msg) def handle_connect(self, message): """Connects client user to device""" if 'device_id' not in message: send_error('Missing device_id field.') return device_id = message['device_id'] if self.client_id: send_error('Attempt to connect to multiple devices over same websocket.') else: send_server_config(self.ws) if device_id not in devices: send_error(f'Device id {device_id} not registered.') else: self.device = devices[device_id] self.device.register_client(self) print(f'Connected client {self.client_id} to device {self.device.device_id}.') self.send_device_info() def handle_forward(self, message): """Handle forward for client""" if not self.client_id: send_error('No device associated to client.') elif 'payload' not in message: send_error('Missing payload field.') else: self.device.forward_client_message(self.client_id, message) print(f'Forwarded message from client {self.client_id} to device {self.device.device_id}.') def process_request(self, message): if 'message_type' not in message: send_error('Missing field message_type') elif message['message_type'] == 'connect': self.handle_connect(message) elif message['message_type'] == 'forward': self.handle_forward(message) else: send_error(f'Unknown message type: {message["message_type"]}') class Device: client_number = 1 device_id = None device_info = None clients = {} def __init__(self, ws): self.ws = ws def forward_client_message(self, client_id, message): client_msg = {} client_msg['message_type'] = 'client_msg' client_msg['client_id'] = client_id client_msg['payload'] = message['payload'] send_data_ws(self.ws, client_msg) def handle_registration(self, message): """Registers device id and info in device list and sends config""" if 'device_id' not in message: send_error('Missing device id in registration request') return device_id = message['device_id'] if message['device_id'] in devices: send_error(f'Device with id {device_id} already exists.') elif 'device_info' not in message: send_error('Missing device info in registration request.') else: devices[device_id] = self self.device_id = device_id self.device_info = message['device_info'] send_server_config(self.ws) print(f'Registered device with id {device_id}') def handle_forward(self, message): """Handles forward for device""" if 'client_id' not in message: send_error('Missing client id in forward message.') elif 'payload' not in message: send_error('Missing payload field in forward message.') elif message['client_id'] not in self.clients: send_error(f'Unregistered client id {message["client_id"]}.') else: client_id = message['client_id'] client = self.clients[client_id] client.forward_device_message(message) print(f'Forwarded message from device {self.device_id} to client {client_id}.') def process_request(self, message): if 'message_type' not in message: send_error('Missing field message_type') elif message['message_type'] == 'register': self.handle_registration(message) elif message['message_type'] == 'forward': self.handle_forward(message) else: send_error(f'Unknown message type: {message["message_type"]}') def register_client(self, client): client_id = self.client_number client.client_id = client_id self.clients[client_id] = client self.client_number += 1 def unregister_client(self, client_id): self.clients.pop(client_id) @sockets.route('/register_device') def register_device(ws): print('ws connected to /register_device') device = Device(ws) try: while not ws.closed: raw_message = ws.receive() message = json.loads(raw_message) device.process_request(message) except: if device.device_id: devices.pop(device.device_id) print(f'deleted device {device.device_id} from device list.') @sockets.route('/connect_client') def connect_client(ws): print('ws connected to /connect_client') client = Client(ws) try: while not ws.closed: raw_message = ws.receive() message = json.loads(raw_message) client.process_request(message) except: if client.device: device_id = client.device.device_id devices[device_id].unregister_client(client.client_id) print(f'unregistered client {client.client_id} from device {device_id}')
0.417984
0.053849
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Index', '0002_indexpageviewkeybenfitsmodel_sort_id'), ] operations = [ migrations.CreateModel( name='IndexPageQAModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, null=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('sort_id', models.IntegerField(db_index=True, default=0, verbose_name='QA sort id')), ('qa_title', models.CharField(default='', max_length=64, unique=True, verbose_name='QA title')), ('qa_description', models.CharField(default='', max_length=1024, verbose_name='QA description')), ], options={ 'verbose_name': 'qas', 'verbose_name_plural': 'qas', 'db_table': 'armod_index_qa', }, ), migrations.AlterModelOptions( name='indexpageviewkeybenfitsmodel', options={'verbose_name': 'Index Keybenfits', 'verbose_name_plural': 'Index Keybenfits'}, ), migrations.AddField( model_name='indexpageviewkeybenfitsmodel', name='keybenfit_video_url', field=models.CharField(default='', max_length=256, verbose_name='Key benfit video url'), ), migrations.AlterField( model_name='indexpageviewkeybenfitsmodel', name='sort_id', field=models.IntegerField(db_index=True, default=0, verbose_name='Key benfit sort id'), ), migrations.AlterModelTable( name='indexpageviewkeybenfitsmodel', table='armod_index_key_benfits', ), ]
ARMODServers/Apps/Index/migrations/0003_auto_20210420_2141.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Index', '0002_indexpageviewkeybenfitsmodel_sort_id'), ] operations = [ migrations.CreateModel( name='IndexPageQAModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间')), ('update_time', models.DateTimeField(auto_now=True, null=True, verbose_name='更新时间')), ('is_delete', models.BooleanField(default=False, verbose_name='删除标记')), ('sort_id', models.IntegerField(db_index=True, default=0, verbose_name='QA sort id')), ('qa_title', models.CharField(default='', max_length=64, unique=True, verbose_name='QA title')), ('qa_description', models.CharField(default='', max_length=1024, verbose_name='QA description')), ], options={ 'verbose_name': 'qas', 'verbose_name_plural': 'qas', 'db_table': 'armod_index_qa', }, ), migrations.AlterModelOptions( name='indexpageviewkeybenfitsmodel', options={'verbose_name': 'Index Keybenfits', 'verbose_name_plural': 'Index Keybenfits'}, ), migrations.AddField( model_name='indexpageviewkeybenfitsmodel', name='keybenfit_video_url', field=models.CharField(default='', max_length=256, verbose_name='Key benfit video url'), ), migrations.AlterField( model_name='indexpageviewkeybenfitsmodel', name='sort_id', field=models.IntegerField(db_index=True, default=0, verbose_name='Key benfit sort id'), ), migrations.AlterModelTable( name='indexpageviewkeybenfitsmodel', table='armod_index_key_benfits', ), ]
0.551574
0.149469
import snake import pygame as p class OpSnake(snake.Snake): """ [0-3] 00 distWEsq, 01 distWCim, 02 distWDir, 03 distWBai, [4-7] 04 distWCimEsq, 05 distWCimDir, 06 distWBaiEsq, 07 distWBaiDir [8-11] 08 distEsq, 09 distCim, 10 distDir, 11 distBai [12-15] 12 distAEsq, 13 distACim, 14 distADir, 15 distABai [16-19] 16 distACimEsq, 17 distACimDir, 18 distABaiEsq, 19 distABaiDir, [20-21] 20 distAX, 21 distAY """ def bestKey(self,inputs,keys): def setFalse(keys): keys[p.K_UP] = False keys[p.K_DOWN] = False keys[p.K_LEFT] = False keys[p.K_RIGHT] = False return keys """ [0-3] 00 distWEsq, 01 distWCim, 02 distWDir, 03 distWBai, [8-11] 08 distEsq, 09 distCim, 10 distDir, 11 distBai """ # ------------------ Quinas # Esquerda Cima if inputs[0] == 0 and inputs[1] == 0: keys = setFalse(keys) # Dir Livre if inputs[10] == 0: keys[p.K_RIGHT] = True return keys # Bai Livre elif inputs[11] == 0: keys[p.K_DOWN] = True return keys # Esquerda Baixo if inputs[0] == 0 and inputs[3] == 0: keys = setFalse(keys) # Esq Livre if inputs[8] == 0: keys[p.K_LEFT] = True return keys # Cim Livre elif inputs[9] == 0: keys[p.K_UP] = True return keys # Dir Cima if inputs[2] == 0 and inputs[1] == 0: keys = setFalse(keys) # Esq Livre if inputs[8] == 0: keys[p.K_LEFT] = True return keys # Bai Livre elif inputs[11] == 0: keys[p.K_DOWN] = True return keys # Dir Bai if inputs[2] == 0 and inputs[3] == 0: keys = setFalse(keys) # Esq Livre if inputs[8] == 0: keys[p.K_LEFT] = True return # Cim Livre elif inputs[9] == 0: keys[p.K_UP] = True return keys """ [0-3] 00 distWEsq, 01 distWCim, 02 distWDir, 03 distWBai, [8-11] 08 distEsq, 09 distCim, 10 distDir, 11 distBai """ # ---------Paredes # Esq if inputs[0] == 0: keys = setFalse(keys) if inputs[9] == 0 or inputs[9] > inputs[11]: keys[p.K_UP] = True elif inputs[11] == 0 or inputs[11] > inputs[9]: keys[p.K_DOWN] = True return keys
opsnake.py
import snake import pygame as p class OpSnake(snake.Snake): """ [0-3] 00 distWEsq, 01 distWCim, 02 distWDir, 03 distWBai, [4-7] 04 distWCimEsq, 05 distWCimDir, 06 distWBaiEsq, 07 distWBaiDir [8-11] 08 distEsq, 09 distCim, 10 distDir, 11 distBai [12-15] 12 distAEsq, 13 distACim, 14 distADir, 15 distABai [16-19] 16 distACimEsq, 17 distACimDir, 18 distABaiEsq, 19 distABaiDir, [20-21] 20 distAX, 21 distAY """ def bestKey(self,inputs,keys): def setFalse(keys): keys[p.K_UP] = False keys[p.K_DOWN] = False keys[p.K_LEFT] = False keys[p.K_RIGHT] = False return keys """ [0-3] 00 distWEsq, 01 distWCim, 02 distWDir, 03 distWBai, [8-11] 08 distEsq, 09 distCim, 10 distDir, 11 distBai """ # ------------------ Quinas # Esquerda Cima if inputs[0] == 0 and inputs[1] == 0: keys = setFalse(keys) # Dir Livre if inputs[10] == 0: keys[p.K_RIGHT] = True return keys # Bai Livre elif inputs[11] == 0: keys[p.K_DOWN] = True return keys # Esquerda Baixo if inputs[0] == 0 and inputs[3] == 0: keys = setFalse(keys) # Esq Livre if inputs[8] == 0: keys[p.K_LEFT] = True return keys # Cim Livre elif inputs[9] == 0: keys[p.K_UP] = True return keys # Dir Cima if inputs[2] == 0 and inputs[1] == 0: keys = setFalse(keys) # Esq Livre if inputs[8] == 0: keys[p.K_LEFT] = True return keys # Bai Livre elif inputs[11] == 0: keys[p.K_DOWN] = True return keys # Dir Bai if inputs[2] == 0 and inputs[3] == 0: keys = setFalse(keys) # Esq Livre if inputs[8] == 0: keys[p.K_LEFT] = True return # Cim Livre elif inputs[9] == 0: keys[p.K_UP] = True return keys """ [0-3] 00 distWEsq, 01 distWCim, 02 distWDir, 03 distWBai, [8-11] 08 distEsq, 09 distCim, 10 distDir, 11 distBai """ # ---------Paredes # Esq if inputs[0] == 0: keys = setFalse(keys) if inputs[9] == 0 or inputs[9] > inputs[11]: keys[p.K_UP] = True elif inputs[11] == 0 or inputs[11] > inputs[9]: keys[p.K_DOWN] = True return keys
0.217587
0.331498
from __future__ import annotations import typing import zserio import tutorial.experience import tutorial.role class Employee: def __init__( self, age_: int = int(), name_: str = str(), salary_: int = int(), bonus_: typing.Optional[int] = None, role_: typing.Union[tutorial.role.Role, None] = None, skills_: typing.Optional[typing.List[tutorial.experience.Experience]] = None) -> None: self._age_ = age_ self._name_ = name_ self._salary_ = salary_ self._bonus_ = bonus_ self._role_ = role_ if skills_ is None: self._skills_ = None else: self._skills_ = zserio.array.Array(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), skills_, is_auto=True) @classmethod def from_reader( cls: typing.Type['Employee'], zserio_reader: zserio.BitStreamReader) -> 'Employee': instance = cls() instance.read(zserio_reader) return instance @classmethod def from_reader_packed( cls: typing.Type['Employee'], zserio_context_node: zserio.array.PackingContextNode, zserio_reader: zserio.BitStreamReader) -> 'Employee': instance = cls() instance.read_packed(zserio_context_node, zserio_reader) return instance def __eq__(self, other: object) -> bool: if isinstance(other, Employee): return (self._age_ == other._age_ and self._name_ == other._name_ and self._salary_ == other._salary_ and (not self.is_bonus_used() or self._bonus_ == other._bonus_) and self._role_ == other._role_ and (not self.is_skills_used() or self._skills_ == other._skills_)) return False def __hash__(self) -> int: result = zserio.hashcode.HASH_SEED result = zserio.hashcode.calc_hashcode(result, hash(self._age_)) result = zserio.hashcode.calc_hashcode(result, hash(self._name_)) result = zserio.hashcode.calc_hashcode(result, hash(self._salary_)) if self.is_bonus_used(): result = zserio.hashcode.calc_hashcode(result, hash(self._bonus_)) result = zserio.hashcode.calc_hashcode(result, hash(self._role_)) if self.is_skills_used(): result = zserio.hashcode.calc_hashcode(result, hash(self._skills_)) return result @property def age(self) -> int: return self._age_ @age.setter def age(self, age_: int) -> None: self._age_ = age_ @property def name(self) -> str: return self._name_ @name.setter def name(self, name_: str) -> None: self._name_ = name_ @property def salary(self) -> int: return self._salary_ @salary.setter def salary(self, salary_: int) -> None: self._salary_ = salary_ @property def bonus(self) -> typing.Optional[int]: return self._bonus_ @bonus.setter def bonus(self, bonus_: typing.Optional[int]) -> None: self._bonus_ = bonus_ def is_bonus_used(self) -> bool: return not self._bonus_ is None @property def role(self) -> typing.Union[tutorial.role.Role, None]: return self._role_ @role.setter def role(self, role_: typing.Union[tutorial.role.Role, None]) -> None: self._role_ = role_ @property def skills(self) -> typing.Optional[typing.List[tutorial.experience.Experience]]: return None if self._skills_ is None else self._skills_.raw_array @skills.setter def skills(self, skills_: typing.Optional[typing.List[tutorial.experience.Experience]]) -> None: if skills_ is None: self._skills_ = None else: self._skills_ = zserio.array.Array(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), skills_, is_auto=True) def is_skills_used(self) -> bool: return self.role == tutorial.role.Role.DEVELOPER @staticmethod def create_packing_context(context_node: zserio.array.PackingContextNode) -> None: context_node.create_child().create_context() context_node.create_child() context_node.create_child().create_context() context_node.create_child().create_context() tutorial.role.Role.create_packing_context(context_node.create_child()) context_node.create_child() def init_packing_context(self, context_node: zserio.array.PackingContextNode) -> None: zserio_ctx_node_age = context_node.children[0] zserio_ctx_node_age.context.init(self._age_) zserio_ctx_node_salary = context_node.children[2] zserio_ctx_node_salary.context.init(self._salary_) zserio_ctx_node_bonus = context_node.children[3] if self.is_bonus_used(): zserio_ctx_node_bonus.context.init(self._bonus_) zserio_ctx_node_role = context_node.children[4] self._role_.init_packing_context(zserio_ctx_node_role) def bitsizeof(self, bitposition: int = 0) -> int: end_bitposition = bitposition end_bitposition += 8 end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) end_bitposition += 16 end_bitposition += 1 if self.is_bonus_used(): end_bitposition += 16 end_bitposition += self._role_.bitsizeof(end_bitposition) if self.is_skills_used(): end_bitposition += self._skills_.bitsizeof(end_bitposition) return end_bitposition - bitposition def bitsizeof_packed(self, context_node: zserio.array.PackingContextNode, bitposition: int = 0) -> int: end_bitposition = bitposition zserio_ctx_node_age = context_node.children[0] end_bitposition += zserio_ctx_node_age.context.bitsizeof(zserio.array.BitFieldArrayTraits(8), end_bitposition, self._age_) end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) zserio_ctx_node_salary = context_node.children[2] end_bitposition += zserio_ctx_node_salary.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._salary_) zserio_ctx_node_bonus = context_node.children[3] end_bitposition += 1 if self.is_bonus_used(): end_bitposition += zserio_ctx_node_bonus.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._bonus_) zserio_ctx_node_role = context_node.children[4] end_bitposition += self._role_.bitsizeof_packed(zserio_ctx_node_role, end_bitposition) if self.is_skills_used(): end_bitposition += self._skills_.bitsizeof_packed(end_bitposition) return end_bitposition - bitposition def initialize_offsets(self, bitposition: int) -> int: end_bitposition = bitposition end_bitposition += 8 end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) end_bitposition += 16 end_bitposition += 1 if self.is_bonus_used(): end_bitposition += 16 end_bitposition = self._role_.initialize_offsets(end_bitposition) if self.is_skills_used(): end_bitposition = self._skills_.initialize_offsets(end_bitposition) return end_bitposition def initialize_offsets_packed(self, context_node: zserio.array.PackingContextNode, bitposition: int) -> int: end_bitposition = bitposition zserio_ctx_node_age = context_node.children[0] end_bitposition += zserio_ctx_node_age.context.bitsizeof(zserio.array.BitFieldArrayTraits(8), end_bitposition, self._age_) end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) zserio_ctx_node_salary = context_node.children[2] end_bitposition += zserio_ctx_node_salary.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._salary_) zserio_ctx_node_bonus = context_node.children[3] end_bitposition += 1 if self.is_bonus_used(): end_bitposition += zserio_ctx_node_bonus.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._bonus_) zserio_ctx_node_role = context_node.children[4] end_bitposition = self._role_.initialize_offsets_packed(zserio_ctx_node_role, end_bitposition) if self.is_skills_used(): end_bitposition = self._skills_.initialize_offsets_packed(end_bitposition) return end_bitposition def read(self, zserio_reader: zserio.BitStreamReader) -> None: self._age_ = zserio_reader.read_bits(8) # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") self._name_ = zserio_reader.read_string() self._salary_ = zserio_reader.read_bits(16) if zserio_reader.read_bool(): self._bonus_ = zserio_reader.read_bits(16) self._role_ = tutorial.role.Role.from_reader(zserio_reader) if self.is_skills_used(): self._skills_ = zserio.array.Array.from_reader(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), zserio_reader, is_auto=True) def read_packed(self, zserio_context_node: zserio.array.PackingContextNode, zserio_reader: zserio.BitStreamReader) -> None: zserio_ctx_node_age = zserio_context_node.children[0] self._age_ = zserio_ctx_node_age.context.read(zserio.array.BitFieldArrayTraits(8), zserio_reader) # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") self._name_ = zserio_reader.read_string() zserio_ctx_node_salary = zserio_context_node.children[2] self._salary_ = zserio_ctx_node_salary.context.read(zserio.array.BitFieldArrayTraits(16), zserio_reader) zserio_ctx_node_bonus = zserio_context_node.children[3] if zserio_reader.read_bool(): self._bonus_ = zserio_ctx_node_bonus.context.read(zserio.array.BitFieldArrayTraits(16), zserio_reader) zserio_ctx_node_role = zserio_context_node.children[4] self._role_ = tutorial.role.Role.from_reader_packed(zserio_ctx_node_role, zserio_reader) if self.is_skills_used(): self._skills_ = zserio.array.Array.from_reader_packed(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), zserio_reader, is_auto=True) def write(self, zserio_writer: zserio.BitStreamWriter, *, zserio_call_initialize_offsets: bool = True) -> None: del zserio_call_initialize_offsets # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") zserio_writer.write_bits(self._age_, 8) zserio_writer.write_string(self._name_) zserio_writer.write_bits(self._salary_, 16) if self.is_bonus_used(): zserio_writer.write_bool(True) zserio_writer.write_bits(self._bonus_, 16) else: zserio_writer.write_bool(False) self._role_.write(zserio_writer) if self.is_skills_used(): self._skills_.write(zserio_writer) def write_packed(self, zserio_context_node: zserio.array.PackingContextNode, zserio_writer: zserio.BitStreamWriter) -> None: zserio_ctx_node_age = zserio_context_node.children[0] # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") zserio_ctx_node_age.context.write(zserio.array.BitFieldArrayTraits(8), zserio_writer, self._age_) zserio_writer.write_string(self._name_) zserio_ctx_node_salary = zserio_context_node.children[2] zserio_ctx_node_salary.context.write(zserio.array.BitFieldArrayTraits(16), zserio_writer, self._salary_) zserio_ctx_node_bonus = zserio_context_node.children[3] if self.is_bonus_used(): zserio_writer.write_bool(True) zserio_ctx_node_bonus.context.write(zserio.array.BitFieldArrayTraits(16), zserio_writer, self._bonus_) else: zserio_writer.write_bool(False) zserio_ctx_node_role = zserio_context_node.children[4] self._role_.write_packed(zserio_ctx_node_role, zserio_writer) if self.is_skills_used(): self._skills_.write_packed(zserio_writer) def _element_creator_skills(self, zserio_reader: zserio.BitStreamReader, zserio_index: int) -> tutorial.experience.Experience: del zserio_index return tutorial.experience.Experience.from_reader(zserio_reader) def _packed_element_creator_skills( self, zserio_context_node: zserio.array.PackingContextNode, zserio_reader: zserio.BitStreamReader, zserio_index: int) -> tutorial.experience.Experience: del zserio_index return tutorial.experience.Experience.from_reader_packed(zserio_context_node, zserio_reader)
src/tutorial/employee.py
from __future__ import annotations import typing import zserio import tutorial.experience import tutorial.role class Employee: def __init__( self, age_: int = int(), name_: str = str(), salary_: int = int(), bonus_: typing.Optional[int] = None, role_: typing.Union[tutorial.role.Role, None] = None, skills_: typing.Optional[typing.List[tutorial.experience.Experience]] = None) -> None: self._age_ = age_ self._name_ = name_ self._salary_ = salary_ self._bonus_ = bonus_ self._role_ = role_ if skills_ is None: self._skills_ = None else: self._skills_ = zserio.array.Array(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), skills_, is_auto=True) @classmethod def from_reader( cls: typing.Type['Employee'], zserio_reader: zserio.BitStreamReader) -> 'Employee': instance = cls() instance.read(zserio_reader) return instance @classmethod def from_reader_packed( cls: typing.Type['Employee'], zserio_context_node: zserio.array.PackingContextNode, zserio_reader: zserio.BitStreamReader) -> 'Employee': instance = cls() instance.read_packed(zserio_context_node, zserio_reader) return instance def __eq__(self, other: object) -> bool: if isinstance(other, Employee): return (self._age_ == other._age_ and self._name_ == other._name_ and self._salary_ == other._salary_ and (not self.is_bonus_used() or self._bonus_ == other._bonus_) and self._role_ == other._role_ and (not self.is_skills_used() or self._skills_ == other._skills_)) return False def __hash__(self) -> int: result = zserio.hashcode.HASH_SEED result = zserio.hashcode.calc_hashcode(result, hash(self._age_)) result = zserio.hashcode.calc_hashcode(result, hash(self._name_)) result = zserio.hashcode.calc_hashcode(result, hash(self._salary_)) if self.is_bonus_used(): result = zserio.hashcode.calc_hashcode(result, hash(self._bonus_)) result = zserio.hashcode.calc_hashcode(result, hash(self._role_)) if self.is_skills_used(): result = zserio.hashcode.calc_hashcode(result, hash(self._skills_)) return result @property def age(self) -> int: return self._age_ @age.setter def age(self, age_: int) -> None: self._age_ = age_ @property def name(self) -> str: return self._name_ @name.setter def name(self, name_: str) -> None: self._name_ = name_ @property def salary(self) -> int: return self._salary_ @salary.setter def salary(self, salary_: int) -> None: self._salary_ = salary_ @property def bonus(self) -> typing.Optional[int]: return self._bonus_ @bonus.setter def bonus(self, bonus_: typing.Optional[int]) -> None: self._bonus_ = bonus_ def is_bonus_used(self) -> bool: return not self._bonus_ is None @property def role(self) -> typing.Union[tutorial.role.Role, None]: return self._role_ @role.setter def role(self, role_: typing.Union[tutorial.role.Role, None]) -> None: self._role_ = role_ @property def skills(self) -> typing.Optional[typing.List[tutorial.experience.Experience]]: return None if self._skills_ is None else self._skills_.raw_array @skills.setter def skills(self, skills_: typing.Optional[typing.List[tutorial.experience.Experience]]) -> None: if skills_ is None: self._skills_ = None else: self._skills_ = zserio.array.Array(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), skills_, is_auto=True) def is_skills_used(self) -> bool: return self.role == tutorial.role.Role.DEVELOPER @staticmethod def create_packing_context(context_node: zserio.array.PackingContextNode) -> None: context_node.create_child().create_context() context_node.create_child() context_node.create_child().create_context() context_node.create_child().create_context() tutorial.role.Role.create_packing_context(context_node.create_child()) context_node.create_child() def init_packing_context(self, context_node: zserio.array.PackingContextNode) -> None: zserio_ctx_node_age = context_node.children[0] zserio_ctx_node_age.context.init(self._age_) zserio_ctx_node_salary = context_node.children[2] zserio_ctx_node_salary.context.init(self._salary_) zserio_ctx_node_bonus = context_node.children[3] if self.is_bonus_used(): zserio_ctx_node_bonus.context.init(self._bonus_) zserio_ctx_node_role = context_node.children[4] self._role_.init_packing_context(zserio_ctx_node_role) def bitsizeof(self, bitposition: int = 0) -> int: end_bitposition = bitposition end_bitposition += 8 end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) end_bitposition += 16 end_bitposition += 1 if self.is_bonus_used(): end_bitposition += 16 end_bitposition += self._role_.bitsizeof(end_bitposition) if self.is_skills_used(): end_bitposition += self._skills_.bitsizeof(end_bitposition) return end_bitposition - bitposition def bitsizeof_packed(self, context_node: zserio.array.PackingContextNode, bitposition: int = 0) -> int: end_bitposition = bitposition zserio_ctx_node_age = context_node.children[0] end_bitposition += zserio_ctx_node_age.context.bitsizeof(zserio.array.BitFieldArrayTraits(8), end_bitposition, self._age_) end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) zserio_ctx_node_salary = context_node.children[2] end_bitposition += zserio_ctx_node_salary.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._salary_) zserio_ctx_node_bonus = context_node.children[3] end_bitposition += 1 if self.is_bonus_used(): end_bitposition += zserio_ctx_node_bonus.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._bonus_) zserio_ctx_node_role = context_node.children[4] end_bitposition += self._role_.bitsizeof_packed(zserio_ctx_node_role, end_bitposition) if self.is_skills_used(): end_bitposition += self._skills_.bitsizeof_packed(end_bitposition) return end_bitposition - bitposition def initialize_offsets(self, bitposition: int) -> int: end_bitposition = bitposition end_bitposition += 8 end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) end_bitposition += 16 end_bitposition += 1 if self.is_bonus_used(): end_bitposition += 16 end_bitposition = self._role_.initialize_offsets(end_bitposition) if self.is_skills_used(): end_bitposition = self._skills_.initialize_offsets(end_bitposition) return end_bitposition def initialize_offsets_packed(self, context_node: zserio.array.PackingContextNode, bitposition: int) -> int: end_bitposition = bitposition zserio_ctx_node_age = context_node.children[0] end_bitposition += zserio_ctx_node_age.context.bitsizeof(zserio.array.BitFieldArrayTraits(8), end_bitposition, self._age_) end_bitposition += zserio.bitsizeof.bitsizeof_string(self._name_) zserio_ctx_node_salary = context_node.children[2] end_bitposition += zserio_ctx_node_salary.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._salary_) zserio_ctx_node_bonus = context_node.children[3] end_bitposition += 1 if self.is_bonus_used(): end_bitposition += zserio_ctx_node_bonus.context.bitsizeof(zserio.array.BitFieldArrayTraits(16), end_bitposition, self._bonus_) zserio_ctx_node_role = context_node.children[4] end_bitposition = self._role_.initialize_offsets_packed(zserio_ctx_node_role, end_bitposition) if self.is_skills_used(): end_bitposition = self._skills_.initialize_offsets_packed(end_bitposition) return end_bitposition def read(self, zserio_reader: zserio.BitStreamReader) -> None: self._age_ = zserio_reader.read_bits(8) # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") self._name_ = zserio_reader.read_string() self._salary_ = zserio_reader.read_bits(16) if zserio_reader.read_bool(): self._bonus_ = zserio_reader.read_bits(16) self._role_ = tutorial.role.Role.from_reader(zserio_reader) if self.is_skills_used(): self._skills_ = zserio.array.Array.from_reader(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), zserio_reader, is_auto=True) def read_packed(self, zserio_context_node: zserio.array.PackingContextNode, zserio_reader: zserio.BitStreamReader) -> None: zserio_ctx_node_age = zserio_context_node.children[0] self._age_ = zserio_ctx_node_age.context.read(zserio.array.BitFieldArrayTraits(8), zserio_reader) # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") self._name_ = zserio_reader.read_string() zserio_ctx_node_salary = zserio_context_node.children[2] self._salary_ = zserio_ctx_node_salary.context.read(zserio.array.BitFieldArrayTraits(16), zserio_reader) zserio_ctx_node_bonus = zserio_context_node.children[3] if zserio_reader.read_bool(): self._bonus_ = zserio_ctx_node_bonus.context.read(zserio.array.BitFieldArrayTraits(16), zserio_reader) zserio_ctx_node_role = zserio_context_node.children[4] self._role_ = tutorial.role.Role.from_reader_packed(zserio_ctx_node_role, zserio_reader) if self.is_skills_used(): self._skills_ = zserio.array.Array.from_reader_packed(zserio.array.ObjectArrayTraits(self._element_creator_skills, self._packed_element_creator_skills, tutorial.experience.Experience.create_packing_context), zserio_reader, is_auto=True) def write(self, zserio_writer: zserio.BitStreamWriter, *, zserio_call_initialize_offsets: bool = True) -> None: del zserio_call_initialize_offsets # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") zserio_writer.write_bits(self._age_, 8) zserio_writer.write_string(self._name_) zserio_writer.write_bits(self._salary_, 16) if self.is_bonus_used(): zserio_writer.write_bool(True) zserio_writer.write_bits(self._bonus_, 16) else: zserio_writer.write_bool(False) self._role_.write(zserio_writer) if self.is_skills_used(): self._skills_.write(zserio_writer) def write_packed(self, zserio_context_node: zserio.array.PackingContextNode, zserio_writer: zserio.BitStreamWriter) -> None: zserio_ctx_node_age = zserio_context_node.children[0] # check constraint if not (self.age <= 65): raise zserio.PythonRuntimeException("Constraint violated for field Employee.age!") zserio_ctx_node_age.context.write(zserio.array.BitFieldArrayTraits(8), zserio_writer, self._age_) zserio_writer.write_string(self._name_) zserio_ctx_node_salary = zserio_context_node.children[2] zserio_ctx_node_salary.context.write(zserio.array.BitFieldArrayTraits(16), zserio_writer, self._salary_) zserio_ctx_node_bonus = zserio_context_node.children[3] if self.is_bonus_used(): zserio_writer.write_bool(True) zserio_ctx_node_bonus.context.write(zserio.array.BitFieldArrayTraits(16), zserio_writer, self._bonus_) else: zserio_writer.write_bool(False) zserio_ctx_node_role = zserio_context_node.children[4] self._role_.write_packed(zserio_ctx_node_role, zserio_writer) if self.is_skills_used(): self._skills_.write_packed(zserio_writer) def _element_creator_skills(self, zserio_reader: zserio.BitStreamReader, zserio_index: int) -> tutorial.experience.Experience: del zserio_index return tutorial.experience.Experience.from_reader(zserio_reader) def _packed_element_creator_skills( self, zserio_context_node: zserio.array.PackingContextNode, zserio_reader: zserio.BitStreamReader, zserio_index: int) -> tutorial.experience.Experience: del zserio_index return tutorial.experience.Experience.from_reader_packed(zserio_context_node, zserio_reader)
0.782579
0.26815
from rest_framework import serializers from groupon.services import create_groupon, update_groupon from wsc_django.utils.constant import DateFormat from wsc_django.utils.core import FuncField class AdminGrouponCreateSerializer(serializers.Serializer): """后台拼团活动创建序列化器""" price = FuncField(lambda value: round(float(value), 2), label="拼团价格") from_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动开始时间") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动结束时间") groupon_type = serializers.IntegerField(label="拼团活动类型 1:普通 2:老带新") success_size = serializers.IntegerField(label="成团人数") quantity_limit = serializers.IntegerField(label="成团数量上限") success_limit = serializers.IntegerField(label="成团上限") attend_limit = serializers.IntegerField(label="参团上限") success_valid_hour = serializers.IntegerField(label="开团有效时间") def create(self, validated_data): shop_id = self.context["self"].current_shop.id user_id = self.context["self"].current_user.id product = self.context["product"] groupon = create_groupon( shop_id, user_id, product, validated_data ) return groupon def update(self, instance, validated_data): shop_id = self.context["self"].current_shop.id user_id = self.context["self"].current_user.id product = self.context["product"] instance = update_groupon( shop_id, user_id, product, instance, validated_data ) return instance class SponsorSerializer(serializers.Serializer): """团长信息,只需基本信息,所以新建一个序列化器""" nickname = serializers.CharField(required=False, label="微信昵称") sex = serializers.IntegerField(required=False, label="性别") head_image_url = serializers.CharField(required=False, label="头像") class GrouponBasicSerializer(serializers.Serializer): """拼团活动基本信息序列化器类""" groupon_type = serializers.IntegerField(label="拼团活动类型 1:普通 2:老带新") success_valid_hour = serializers.IntegerField(label="开团有效时间") succeeded_count = serializers.IntegerField(label="成团数") success_limit = serializers.IntegerField(label="成团上限") class GrouponProductSerializer(serializers.Serializer): """拼团商品序列化器类""" product_id = serializers.IntegerField(source="id", label="货品ID") name = serializers.CharField(label="货品名称") price = FuncField(lambda value: round(float(value), 2), label="货品价格") status = serializers.IntegerField(read_only=True, label="货品状态") summary = serializers.CharField(label="货品简介") cover_image_url = serializers.CharField(label="货品封面图") class AdminGrouponsSerializer(GrouponBasicSerializer): """后台拼团活动列表序列化器类""" groupon_id = serializers.IntegerField(source="id", label="拼团id") product = GrouponProductSerializer(label="拼团商品信息") price = FuncField(lambda value: round(float(value), 2), label="拼团价格") attend_limit = serializers.IntegerField(label="参团上限") from_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动开始时间") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动结束时间") status = serializers.IntegerField(label="拼团活动状态 1:启用 2:停用 3:过期") is_editable = serializers.BooleanField(label="拼团是否可以编辑") class AdminGrouponSerializer(GrouponBasicSerializer): """后台拼团活动详情序列化器类""" groupon_id = serializers.IntegerField(source="id", label="拼团id") product = GrouponProductSerializer(label="拼团商品信息") price = FuncField(lambda value: round(float(value), 2), label="拼团价格") attend_limit = serializers.IntegerField(label="参团上限") from_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动开始时间") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动结束时间") status = serializers.IntegerField(label="拼团活动状态 1:启用 2:停用 3:过期") quantity_limit = serializers.IntegerField(label="成团数量上限") success_size = serializers.IntegerField(label="成团人数") class GrouponAttendBasicSerializer(serializers.Serializer): """拼团参与基本信息序列化器类""" groupon_attend_id = serializers.IntegerField(source="id", label="拼团参与id") size = serializers.IntegerField(label="拼团当前参与人数") success_size = serializers.IntegerField(label="成团人数") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团参与结束时间") class AdminGrouponAttendSerializer(GrouponAttendBasicSerializer): """后台拼团参与序列化器类""" anonymous_size = serializers.IntegerField(label="匿名用户数量") sponsor = SponsorSerializer(label="团长信息") status = serializers.IntegerField(label="拼团参与状态 1:拼团中 2:已成团 3:已失败") failed_reason = serializers.CharField(label="失败原因") groupon = GrouponBasicSerializer(label="团基本信息") create_time = serializers.DateTimeField(source="create_at", format=DateFormat.TIME, label="开团时间") success_time = serializers.DateTimeField( source="update_at", format=DateFormat.TIME, label="成团时间(数据改变时间)" )
wsc_django/wsc_django/apps/groupon/serializers.py
from rest_framework import serializers from groupon.services import create_groupon, update_groupon from wsc_django.utils.constant import DateFormat from wsc_django.utils.core import FuncField class AdminGrouponCreateSerializer(serializers.Serializer): """后台拼团活动创建序列化器""" price = FuncField(lambda value: round(float(value), 2), label="拼团价格") from_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动开始时间") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动结束时间") groupon_type = serializers.IntegerField(label="拼团活动类型 1:普通 2:老带新") success_size = serializers.IntegerField(label="成团人数") quantity_limit = serializers.IntegerField(label="成团数量上限") success_limit = serializers.IntegerField(label="成团上限") attend_limit = serializers.IntegerField(label="参团上限") success_valid_hour = serializers.IntegerField(label="开团有效时间") def create(self, validated_data): shop_id = self.context["self"].current_shop.id user_id = self.context["self"].current_user.id product = self.context["product"] groupon = create_groupon( shop_id, user_id, product, validated_data ) return groupon def update(self, instance, validated_data): shop_id = self.context["self"].current_shop.id user_id = self.context["self"].current_user.id product = self.context["product"] instance = update_groupon( shop_id, user_id, product, instance, validated_data ) return instance class SponsorSerializer(serializers.Serializer): """团长信息,只需基本信息,所以新建一个序列化器""" nickname = serializers.CharField(required=False, label="微信昵称") sex = serializers.IntegerField(required=False, label="性别") head_image_url = serializers.CharField(required=False, label="头像") class GrouponBasicSerializer(serializers.Serializer): """拼团活动基本信息序列化器类""" groupon_type = serializers.IntegerField(label="拼团活动类型 1:普通 2:老带新") success_valid_hour = serializers.IntegerField(label="开团有效时间") succeeded_count = serializers.IntegerField(label="成团数") success_limit = serializers.IntegerField(label="成团上限") class GrouponProductSerializer(serializers.Serializer): """拼团商品序列化器类""" product_id = serializers.IntegerField(source="id", label="货品ID") name = serializers.CharField(label="货品名称") price = FuncField(lambda value: round(float(value), 2), label="货品价格") status = serializers.IntegerField(read_only=True, label="货品状态") summary = serializers.CharField(label="货品简介") cover_image_url = serializers.CharField(label="货品封面图") class AdminGrouponsSerializer(GrouponBasicSerializer): """后台拼团活动列表序列化器类""" groupon_id = serializers.IntegerField(source="id", label="拼团id") product = GrouponProductSerializer(label="拼团商品信息") price = FuncField(lambda value: round(float(value), 2), label="拼团价格") attend_limit = serializers.IntegerField(label="参团上限") from_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动开始时间") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动结束时间") status = serializers.IntegerField(label="拼团活动状态 1:启用 2:停用 3:过期") is_editable = serializers.BooleanField(label="拼团是否可以编辑") class AdminGrouponSerializer(GrouponBasicSerializer): """后台拼团活动详情序列化器类""" groupon_id = serializers.IntegerField(source="id", label="拼团id") product = GrouponProductSerializer(label="拼团商品信息") price = FuncField(lambda value: round(float(value), 2), label="拼团价格") attend_limit = serializers.IntegerField(label="参团上限") from_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动开始时间") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团活动结束时间") status = serializers.IntegerField(label="拼团活动状态 1:启用 2:停用 3:过期") quantity_limit = serializers.IntegerField(label="成团数量上限") success_size = serializers.IntegerField(label="成团人数") class GrouponAttendBasicSerializer(serializers.Serializer): """拼团参与基本信息序列化器类""" groupon_attend_id = serializers.IntegerField(source="id", label="拼团参与id") size = serializers.IntegerField(label="拼团当前参与人数") success_size = serializers.IntegerField(label="成团人数") to_datetime = serializers.DateTimeField(format=DateFormat.TIME, label="拼团参与结束时间") class AdminGrouponAttendSerializer(GrouponAttendBasicSerializer): """后台拼团参与序列化器类""" anonymous_size = serializers.IntegerField(label="匿名用户数量") sponsor = SponsorSerializer(label="团长信息") status = serializers.IntegerField(label="拼团参与状态 1:拼团中 2:已成团 3:已失败") failed_reason = serializers.CharField(label="失败原因") groupon = GrouponBasicSerializer(label="团基本信息") create_time = serializers.DateTimeField(source="create_at", format=DateFormat.TIME, label="开团时间") success_time = serializers.DateTimeField( source="update_at", format=DateFormat.TIME, label="成团时间(数据改变时间)" )
0.551091
0.233073
import sys import socket import ipaddress import requests from urllib.parse import urlparse from tools.EMAIL.emailTools import ReadSenderEmail from time import sleep from colorama import Fore """ Check if site is under CloudFlare protection """ def __isCloudFlare(link): parsed_uri = urlparse(link) domain = "{uri.netloc}".format(uri=parsed_uri) try: origin = socket.gethostbyname(domain) iprange = requests.get("https://www.cloudflare.com/ips-v4").text ipv4 = [row.rstrip() for row in iprange.splitlines()] for i in range(len(ipv4)): if ipaddress.ip_address(origin) in ipaddress.ip_network(ipv4[i]): print( f"{Fore.RED}[!] {Fore.YELLOW}The site is protected by CloudFlare, attacks may not produce results.{Fore.RESET}" ) sleep(1) except socket.gaierror: return False def __GetAddressInfo(target): try: ip = target.split(":")[0] port = int(target.split(":")[1]) except IndexError: print(f"{Fore.RED}[!] {Fore.MAGENTA}You must enter ip and port{Fore.RESET}") sys.exit(1) else: return ip, port def __GetURLInfo(target): if not target.startswith("http"): target = f"http://{target}" return target def __GetEmailMessage(): server, username = ReadSenderEmail() subject = input(f"{Fore.BLUE}[?] {Fore.MAGENTA}Enter the Subject (leave blank for random value): ") body = input(f"{Fore.BLUE}[?] {Fore.MAGENTA}Enter Your Message (leave blank for random value): ") return [server, username, subject, body] def GetTargetAddress(target, method): if method == "SMS": if target.startswith("+"): target = target[1:] return target elif method == "EMAIL": email = __GetEmailMessage() email.append(target) return email elif method in ( "SYN", "UDP", "NTP", "POD", "MEMCACHED", "ICMP", "SLOWLORIS", ) and target.startswith("http"): parsed_uri = urlparse(target) domain = "{uri.netloc}".format(uri=parsed_uri) origin = socket.gethostbyname(domain) __isCloudFlare(domain) return origin, 80 elif method in ("SYN", "UDP", "NTP", "POD", "MEMCACHED", "ICMP", "SLOWLORIS"): return __GetAddressInfo(target) elif method == "HTTP": url = __GetURLInfo(target) __isCloudFlare(url) return url else: return target def InternetConnectionCheck(): try: requests.get("https://google.com", timeout=4) except: print( f"{Fore.RED}[!] {Fore.MAGENTA}Your device is not connected to the Internet{Fore.RESET}" ) sys.exit(1)
tools/ipTools.py
import sys import socket import ipaddress import requests from urllib.parse import urlparse from tools.EMAIL.emailTools import ReadSenderEmail from time import sleep from colorama import Fore """ Check if site is under CloudFlare protection """ def __isCloudFlare(link): parsed_uri = urlparse(link) domain = "{uri.netloc}".format(uri=parsed_uri) try: origin = socket.gethostbyname(domain) iprange = requests.get("https://www.cloudflare.com/ips-v4").text ipv4 = [row.rstrip() for row in iprange.splitlines()] for i in range(len(ipv4)): if ipaddress.ip_address(origin) in ipaddress.ip_network(ipv4[i]): print( f"{Fore.RED}[!] {Fore.YELLOW}The site is protected by CloudFlare, attacks may not produce results.{Fore.RESET}" ) sleep(1) except socket.gaierror: return False def __GetAddressInfo(target): try: ip = target.split(":")[0] port = int(target.split(":")[1]) except IndexError: print(f"{Fore.RED}[!] {Fore.MAGENTA}You must enter ip and port{Fore.RESET}") sys.exit(1) else: return ip, port def __GetURLInfo(target): if not target.startswith("http"): target = f"http://{target}" return target def __GetEmailMessage(): server, username = ReadSenderEmail() subject = input(f"{Fore.BLUE}[?] {Fore.MAGENTA}Enter the Subject (leave blank for random value): ") body = input(f"{Fore.BLUE}[?] {Fore.MAGENTA}Enter Your Message (leave blank for random value): ") return [server, username, subject, body] def GetTargetAddress(target, method): if method == "SMS": if target.startswith("+"): target = target[1:] return target elif method == "EMAIL": email = __GetEmailMessage() email.append(target) return email elif method in ( "SYN", "UDP", "NTP", "POD", "MEMCACHED", "ICMP", "SLOWLORIS", ) and target.startswith("http"): parsed_uri = urlparse(target) domain = "{uri.netloc}".format(uri=parsed_uri) origin = socket.gethostbyname(domain) __isCloudFlare(domain) return origin, 80 elif method in ("SYN", "UDP", "NTP", "POD", "MEMCACHED", "ICMP", "SLOWLORIS"): return __GetAddressInfo(target) elif method == "HTTP": url = __GetURLInfo(target) __isCloudFlare(url) return url else: return target def InternetConnectionCheck(): try: requests.get("https://google.com", timeout=4) except: print( f"{Fore.RED}[!] {Fore.MAGENTA}Your device is not connected to the Internet{Fore.RESET}" ) sys.exit(1)
0.111241
0.164449
import queue import time import numpy as np import voluptuous as vol from ledfx.color import COLORS, GRADIENTS from ledfx.effects.audio import AudioReactiveEffect from ledfx.effects.gradient import GradientEffect class Strobe(AudioReactiveEffect, GradientEffect): NAME = "Real Strobe" CONFIG_SCHEMA = vol.Schema( { vol.Optional( "gradient_name", description="Color scheme for bass strobe to cycle through", default="Dancefloor", ): vol.In(list(GRADIENTS.keys())), vol.Optional( "color_step", description="Amount of color change per bass strobe", default=0.0625, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=0.25)), vol.Optional( "bass_threshold", description="Cutoff for quiet sounds. Higher -> only loud sounds are detected", default=0.4, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), vol.Optional( "bass_strobe_decay_rate", description="Bass strobe decay rate. Higher -> decays faster.", default=0.5, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), vol.Optional( "strobe_color", description="Colour for note strobes", default="white", ): vol.In(list(COLORS.keys())), vol.Optional( "strobe_width", description="Note strobe width, in pixels", default=10, ): vol.All(vol.Coerce(int), vol.Range(min=0, max=1000)), vol.Optional( "strobe_decay_rate", description="Note strobe decay rate. Higher -> decays faster.", default=0.5, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), } ) def activate(self, pixel_count): super().activate(pixel_count) self.strobe_overlay = np.zeros(np.shape(self.pixels)) self.bass_strobe_overlay = np.zeros(np.shape(self.pixels)) self.onsets_queue = queue.Queue() def config_updated(self, config): self.bass_threshold = self._config["bass_threshold"] self.color_shift_step = self._config["color_step"] self.strobe_color = np.array( COLORS[self._config["strobe_color"]], dtype=float ) self.last_color_shift_time = 0 self.strobe_width = self._config["strobe_width"] self.color_shift_delay_in_seconds = 1 self.color_idx = 0 self.last_strobe_time = 0 self.strobe_wait_time = 0 self.strobe_decay_rate = 1 - self._config["strobe_decay_rate"] self.last_bass_strobe_time = 0 self.bass_strobe_wait_time = 0 self.bass_strobe_decay_rate = ( 1 - self._config["bass_strobe_decay_rate"] ) def get_pixels(self): pixels = np.copy(self.bass_strobe_overlay) if not self.onsets_queue.empty(): self.onsets_queue.get() strobe_width = min(self.strobe_width, self.pixel_count) length_diff = self.pixel_count - strobe_width position = ( 0 if length_diff == 0 else np.random.randint(self.pixel_count - strobe_width) ) self.strobe_overlay[ position : position + strobe_width ] = self.strobe_color pixels += self.strobe_overlay self.strobe_overlay *= self.strobe_decay_rate self.bass_strobe_overlay *= self.bass_strobe_decay_rate self.pixels = pixels return self.pixels def audio_data_updated(self, data): self._dirty = True currentTime = time.time() if ( currentTime - self.last_color_shift_time > self.color_shift_delay_in_seconds ): self.color_idx += self.color_shift_step self.color_idx = self.color_idx % 1 self.bass_strobe_color = self.get_gradient_color(self.color_idx) self.last_color_shift_time = currentTime lows_intensity = np.mean(data.melbank_lows()) if ( lows_intensity > self.bass_threshold and currentTime - self.last_bass_strobe_time > self.bass_strobe_wait_time ): self.bass_strobe_overlay = np.tile( self.bass_strobe_color, (self.pixel_count, 1) ) self.last_bass_strobe_time = currentTime onsets = data.onset() if ( onsets["high"] and currentTime - self.last_strobe_time > self.strobe_wait_time ): self.onsets_queue.put(True) self.last_strobe_time = currentTime
ledfx/effects/real_strobe(Reactive).py
import queue import time import numpy as np import voluptuous as vol from ledfx.color import COLORS, GRADIENTS from ledfx.effects.audio import AudioReactiveEffect from ledfx.effects.gradient import GradientEffect class Strobe(AudioReactiveEffect, GradientEffect): NAME = "Real Strobe" CONFIG_SCHEMA = vol.Schema( { vol.Optional( "gradient_name", description="Color scheme for bass strobe to cycle through", default="Dancefloor", ): vol.In(list(GRADIENTS.keys())), vol.Optional( "color_step", description="Amount of color change per bass strobe", default=0.0625, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=0.25)), vol.Optional( "bass_threshold", description="Cutoff for quiet sounds. Higher -> only loud sounds are detected", default=0.4, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), vol.Optional( "bass_strobe_decay_rate", description="Bass strobe decay rate. Higher -> decays faster.", default=0.5, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), vol.Optional( "strobe_color", description="Colour for note strobes", default="white", ): vol.In(list(COLORS.keys())), vol.Optional( "strobe_width", description="Note strobe width, in pixels", default=10, ): vol.All(vol.Coerce(int), vol.Range(min=0, max=1000)), vol.Optional( "strobe_decay_rate", description="Note strobe decay rate. Higher -> decays faster.", default=0.5, ): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), } ) def activate(self, pixel_count): super().activate(pixel_count) self.strobe_overlay = np.zeros(np.shape(self.pixels)) self.bass_strobe_overlay = np.zeros(np.shape(self.pixels)) self.onsets_queue = queue.Queue() def config_updated(self, config): self.bass_threshold = self._config["bass_threshold"] self.color_shift_step = self._config["color_step"] self.strobe_color = np.array( COLORS[self._config["strobe_color"]], dtype=float ) self.last_color_shift_time = 0 self.strobe_width = self._config["strobe_width"] self.color_shift_delay_in_seconds = 1 self.color_idx = 0 self.last_strobe_time = 0 self.strobe_wait_time = 0 self.strobe_decay_rate = 1 - self._config["strobe_decay_rate"] self.last_bass_strobe_time = 0 self.bass_strobe_wait_time = 0 self.bass_strobe_decay_rate = ( 1 - self._config["bass_strobe_decay_rate"] ) def get_pixels(self): pixels = np.copy(self.bass_strobe_overlay) if not self.onsets_queue.empty(): self.onsets_queue.get() strobe_width = min(self.strobe_width, self.pixel_count) length_diff = self.pixel_count - strobe_width position = ( 0 if length_diff == 0 else np.random.randint(self.pixel_count - strobe_width) ) self.strobe_overlay[ position : position + strobe_width ] = self.strobe_color pixels += self.strobe_overlay self.strobe_overlay *= self.strobe_decay_rate self.bass_strobe_overlay *= self.bass_strobe_decay_rate self.pixels = pixels return self.pixels def audio_data_updated(self, data): self._dirty = True currentTime = time.time() if ( currentTime - self.last_color_shift_time > self.color_shift_delay_in_seconds ): self.color_idx += self.color_shift_step self.color_idx = self.color_idx % 1 self.bass_strobe_color = self.get_gradient_color(self.color_idx) self.last_color_shift_time = currentTime lows_intensity = np.mean(data.melbank_lows()) if ( lows_intensity > self.bass_threshold and currentTime - self.last_bass_strobe_time > self.bass_strobe_wait_time ): self.bass_strobe_overlay = np.tile( self.bass_strobe_color, (self.pixel_count, 1) ) self.last_bass_strobe_time = currentTime onsets = data.onset() if ( onsets["high"] and currentTime - self.last_strobe_time > self.strobe_wait_time ): self.onsets_queue.put(True) self.last_strobe_time = currentTime
0.512449
0.24178
import collections class CyclicGraphError(Exception): pass class Digraph(object): """An acyclic, directed graph. >>> g = Digraph() >>> g.add_edge('a', 'b') >>> g.add_edge('a', 'c') >>> g.add_edge('b', 'c') You can use a digraph to compute topological orderings (eg. for dependencies): >>> g.sorted() ['a', 'b', 'c'] Graphs can contain unconnected nodes: >>> g.add_node('d') >>> 'd' in g.sorted() True """ def __init__(self, nodes=None, edges=None): self.outbound_edges = collections.defaultdict(set) self.inbound_edges = collections.defaultdict(set) self.nodes = set() if nodes is not None: self.nodes.update(nodes) if edges is not None: for edge in edges: self.add_edge(*edge) def add_node(self, node): self.nodes.add(node) def add_edge(self, outbound, inbound): self.add_node(inbound) self.add_node(outbound) self.outbound_edges[outbound].add(inbound) self.inbound_edges[inbound].add(outbound) def remove_edge(self, outbound, inbound): self.outbound_edges[outbound].remove(inbound) self.inbound_edges[inbound].remove(outbound) def edges(self): for node, outbounds in self.outbound_edges.items(): for outbound in outbounds: yield (node, outbound) def outbound_from(self, node): return set(self.outbound_edges[node]) def inbound_to(self, node): return set(self.inbound_edges[node]) def dup(self): return type(self)(self.nodes, self.edges()) def sorted(self): # Following topological sort taken from: # Kahn, <NAME>. (1962), "Topological sorting of large networks", # Communications of the ACM 5 (11): 558-562, doi:10.1145/368996.369025. # Scratch space, so we don't invalidate _this_ graph graph = self.dup() nodes = [] roots = set( node for node in graph.nodes if not graph.inbound_to(node) ) while roots: next_node = roots.pop() nodes.append(next_node) for node in graph.outbound_from(next_node): graph.remove_edge(next_node, node) if not graph.inbound_to(node): roots.add(node) assert not list(graph.edges()) return nodes
sparkplug/digraph.py
import collections class CyclicGraphError(Exception): pass class Digraph(object): """An acyclic, directed graph. >>> g = Digraph() >>> g.add_edge('a', 'b') >>> g.add_edge('a', 'c') >>> g.add_edge('b', 'c') You can use a digraph to compute topological orderings (eg. for dependencies): >>> g.sorted() ['a', 'b', 'c'] Graphs can contain unconnected nodes: >>> g.add_node('d') >>> 'd' in g.sorted() True """ def __init__(self, nodes=None, edges=None): self.outbound_edges = collections.defaultdict(set) self.inbound_edges = collections.defaultdict(set) self.nodes = set() if nodes is not None: self.nodes.update(nodes) if edges is not None: for edge in edges: self.add_edge(*edge) def add_node(self, node): self.nodes.add(node) def add_edge(self, outbound, inbound): self.add_node(inbound) self.add_node(outbound) self.outbound_edges[outbound].add(inbound) self.inbound_edges[inbound].add(outbound) def remove_edge(self, outbound, inbound): self.outbound_edges[outbound].remove(inbound) self.inbound_edges[inbound].remove(outbound) def edges(self): for node, outbounds in self.outbound_edges.items(): for outbound in outbounds: yield (node, outbound) def outbound_from(self, node): return set(self.outbound_edges[node]) def inbound_to(self, node): return set(self.inbound_edges[node]) def dup(self): return type(self)(self.nodes, self.edges()) def sorted(self): # Following topological sort taken from: # Kahn, <NAME>. (1962), "Topological sorting of large networks", # Communications of the ACM 5 (11): 558-562, doi:10.1145/368996.369025. # Scratch space, so we don't invalidate _this_ graph graph = self.dup() nodes = [] roots = set( node for node in graph.nodes if not graph.inbound_to(node) ) while roots: next_node = roots.pop() nodes.append(next_node) for node in graph.outbound_from(next_node): graph.remove_edge(next_node, node) if not graph.inbound_to(node): roots.add(node) assert not list(graph.edges()) return nodes
0.788217
0.27443
import sys import os import logging from glob import iglob from collections import Counter, OrderedDict def readable_file(fn): """Check if the file is readable""" fn = os.path.abspath(fn) if not os.path.isfile (fn) or not os.access (fn, os.R_OK): raise ont2cramError("File '{}' does not exist or is not readable".format(fn)) def writable_dir(fn): """Check if the dir is writable""" fn = os.path.abspath(fn) if not os.path.isdir(fn) or not os.access (fn, os.W_OK): raise ont2cramError("Directory '{}' does not exist or is not writable".format(fn)) def readable_dir(fn): """Check if the dir is readable""" fn = os.path.abspath(fn) if not os.path.isdir(fn) or not os.access (fn, os.R_OK): raise ont2cramError("Directory '{}' does not exist or is not readable".format(fn)) def mkdir (fn, exist_ok=False): """ Create directory recursivelly. Raise IO error if path exist or if error at creation """ try: os.makedirs (fn, exist_ok=exist_ok) except: raise ont2cramError ("Error creating output folder '{}'".format(fn)) def get_logger (name=None, verbose=False, quiet=False): """Set logger to appropriate log level""" logging.basicConfig(format='%(message)s') logger = logging.getLogger(name) # Define overall verbose level if verbose: logger.setLevel(logging.DEBUG) elif quiet: logger.setLevel(logging.WARNING) else: logger.setLevel(logging.INFO) return logger def recursive_file_gen (dir, ext): """ create a generator listing all files with a particular extension in a folder arborescence The recursivity is broken when at least 1 file with a particular extenssion is found. """ # In the case where the folder is a file if os.path.isdir(dir): # If matching files in the folder file_found=False for fn in iglob (os.path.join(dir, "*."+ext)): yield fn file_found=True # If no matching file go deeper until a leaf containing fast5 is found if not file_found: for item in listdir(dir): for fn in recursive_file_gen (os.path.join(dir, item), ext): yield fn def dict_to_str (d, tab="\t", ntab=0): """ Transform a multilevel dict to a tabulated str """ m = "" if isinstance(d, Counter): for i, j in d.most_common(): m += "{}{}: {:,}\n".format(tab*ntab, i, j) else: for i, j in d.items(): if isinstance(j, dict): j = dict_to_str(j, tab=tab, ntab=ntab+1) m += "{}{}\n{}".format(tab*ntab, i, j) else: m += "{}{}: {}\n".format(tab*ntab, i, j) return m class ont2cramError (Exception): """ Basic exception class for ont2cram package """ pass
ont2cram/common.py
import sys import os import logging from glob import iglob from collections import Counter, OrderedDict def readable_file(fn): """Check if the file is readable""" fn = os.path.abspath(fn) if not os.path.isfile (fn) or not os.access (fn, os.R_OK): raise ont2cramError("File '{}' does not exist or is not readable".format(fn)) def writable_dir(fn): """Check if the dir is writable""" fn = os.path.abspath(fn) if not os.path.isdir(fn) or not os.access (fn, os.W_OK): raise ont2cramError("Directory '{}' does not exist or is not writable".format(fn)) def readable_dir(fn): """Check if the dir is readable""" fn = os.path.abspath(fn) if not os.path.isdir(fn) or not os.access (fn, os.R_OK): raise ont2cramError("Directory '{}' does not exist or is not readable".format(fn)) def mkdir (fn, exist_ok=False): """ Create directory recursivelly. Raise IO error if path exist or if error at creation """ try: os.makedirs (fn, exist_ok=exist_ok) except: raise ont2cramError ("Error creating output folder '{}'".format(fn)) def get_logger (name=None, verbose=False, quiet=False): """Set logger to appropriate log level""" logging.basicConfig(format='%(message)s') logger = logging.getLogger(name) # Define overall verbose level if verbose: logger.setLevel(logging.DEBUG) elif quiet: logger.setLevel(logging.WARNING) else: logger.setLevel(logging.INFO) return logger def recursive_file_gen (dir, ext): """ create a generator listing all files with a particular extension in a folder arborescence The recursivity is broken when at least 1 file with a particular extenssion is found. """ # In the case where the folder is a file if os.path.isdir(dir): # If matching files in the folder file_found=False for fn in iglob (os.path.join(dir, "*."+ext)): yield fn file_found=True # If no matching file go deeper until a leaf containing fast5 is found if not file_found: for item in listdir(dir): for fn in recursive_file_gen (os.path.join(dir, item), ext): yield fn def dict_to_str (d, tab="\t", ntab=0): """ Transform a multilevel dict to a tabulated str """ m = "" if isinstance(d, Counter): for i, j in d.most_common(): m += "{}{}: {:,}\n".format(tab*ntab, i, j) else: for i, j in d.items(): if isinstance(j, dict): j = dict_to_str(j, tab=tab, ntab=ntab+1) m += "{}{}\n{}".format(tab*ntab, i, j) else: m += "{}{}: {}\n".format(tab*ntab, i, j) return m class ont2cramError (Exception): """ Basic exception class for ont2cram package """ pass
0.295636
0.069605
import agentos import click from datetime import datetime import gym import mlflow.projects import importlib.util from pathlib import Path CONDA_ENV_FILE = Path("./conda_env.yaml") CONDA_ENV_CONTENT = """{file_header} name: {name} dependencies: - pip - pip: - gym - agentos # Or, if you want to use your local copy of agentos, then # update the line below and replace the line above with it. #- -e path/to/agentos/git/repo """ MLFLOW_PROJECT_FILE = Path("./MLProject") MLFLOW_PROJECT_CONTENT = """{file_header} name: {name} conda_env: {conda_env} entry_points: main: command: "python main.py" """ AGENT_DEF_FILE = Path("./agent.py") # Default location of agent code. AGENT_MAIN_FILE = Path("./main.py") AGENT_MAIN = """{file_header} import agentos import random import gym # TODO: REPLACE THE EXAMPLE CODE BELOW WITH YOUR OWN! # A minimal 1D hallway env class. class MyEnv(gym.Env): def __init__(self): super().__init__() self.l_r_pos = 0 # left is neg, right is pos. def reset(self): self.l_r_pos = 0 return 0 def step(self, action): self.l_r_pos += action return self.l_r_pos, abs(self.l_r_pos), False, dict() # A minimal example agent class. class MyAgent(agentos.Agent): def __init__(self, env_class): super().__init__(env_class) self.step_count = 0 def advance(self): print("Taking step " + str(self.step_count)) pos_in_env, _, _, _ = self.env.step(random.choice([-1,1])) print("Position in env is now: " + str(pos_in_env)) self.step_count += 1 if __name__ == "__main__": agentos.run_agent(MyAgent, MyEnv, max_iters=5) """ INIT_FILES = { CONDA_ENV_FILE: CONDA_ENV_CONTENT, MLFLOW_PROJECT_FILE: MLFLOW_PROJECT_CONTENT, AGENT_MAIN_FILE: AGENT_MAIN, } @click.group() @click.version_option() def agentos_cmd(): pass def validate_agent_name(ctx, param, value): if " " in value or ":" in value or "/" in value: raise click.BadParameter("name may not contain ' ', ':', or '/'.") return value @agentos_cmd.command() @click.argument("dir_names", nargs=-1, metavar="DIR_NAMES") @click.option( "--name", "-n", metavar="AGENT_NAME", default="new_agent", callback=validate_agent_name, help="This is used as the name of the MLflow Project and " "Conda env for all *Directory Agents* being created. " "AGENT_NAME may not contain ' ', ':', or '/'.", ) def init(dir_names, name): """Initialize current (or specified) directory as an AgentOS agent. \b Arguments: [OPTIONAL] DIR_NAMES zero or more space separated directories to initialize. They will be created if they do not exist. Creates an agent main.py file, a conda env, and an MLflow project file in all directories specified, or if none are specified, then create the files in current directory. """ dirs = [Path(".")] if dir_names: dirs = [Path(d) for d in dir_names] for d in dirs: d.mkdir(parents=True, exist_ok=True) for file_path, content in INIT_FILES.items(): f = open(d / file_path, "w") now = datetime.now().strftime("%b %d, %Y %H:%M:%S") header = ( f"# This file was auto-generated by `agentos init` on {now}." ) f.write( content.format( name=name, conda_env=CONDA_ENV_FILE.name, file_header=header, ) ) f.flush() d = "current working directory" if d == Path(".") else d click.echo(f"Finished initializing AgentOS agent '{name}' in {d}.") def _get_subclass_from_file(filename, parent_class): """Return first subclass of `parent_class` found in filename, else None.""" path = Path(filename) assert path.is_file(), f"Make {path} is a valid file." assert path.suffix == ".py", "Filename must end in .py" spec = importlib.util.spec_from_file_location(path.stem, path.absolute()) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) for elt in module.__dict__.values(): if type(elt) is type and issubclass(elt, parent_class): print(f"Found first subclass class {elt}; returning it.") return elt @agentos_cmd.command() @click.argument("run_args", nargs=-1, metavar="RUN_ARGS") @click.option( "--hz", "-h", metavar="HZ", default=40, type=int, help="Frequency to call agent.advance().", ) @click.option( "--max-iters", "-m", metavar="MAX_STEPS", type=int, default=None, help="Stop running agent after this many calls to advance().", ) def run(run_args, hz, max_iters): """Run an AgentOS agent (agentos.Agent) with an environment (gym.Env). \b Arguments: RUN_ARGS: 0, 1, or 2 space delimited arguments, parsed as follows: \b If no args are specified, look for default files defining agent: - look for file named `MLProject` or `main.py` in the current working directory and if found, run this directory as an MLflow project. - Try to use MLProject file first, using whatever it defines as main entry point, and if that doesn't exist then run using MLflow without MLProject passing main.py as the entry point (note that this will ignore a conda environment file if one exists and MLflow will create a new essentially empty conda env). - else, look for file named `agent.py` in current working directory and, if found, then behave in the same was as if 1 argument (i.e., `agent.py`) was provided, as described below. Else, if 1 arg is specified, interpret it as `agent_filename`: - if it is a directory name, assume it is an AgentOS agent dir, and behavior is equivalent of navigating into that directory and running `agentos run` (without arguments) in it (see above). - if it is a file name, the file must contain an agent class and env class definition. AgentOS searches that file for the first subclass of agentos.Agent, as well as first subclass of gym.Env and calls agentos.run_agent() passing in the agent and env classes found. Else, if 2 args specified, interpret as either filenames or py classes. - assume the first arg specifies the agent and second specifies the Env. The following parsing rules are applied independently to each of the two args (e.g., filenames and classes can be mixed): - if the arg is a filename: Look for the first instance of the appropriate subclass (either agentos.Agent or gym.env) in the file and use that as the argument to agentos.run_agent. - else: Assume the arg is in the form [package.][module.]classname and that it is available in this python environments path. """ def _handle_no_run_args(dirname=None): if dirname: agent_dir = Path(dirname) assert agent_dir.is_dir() else: agent_dir = Path("./") if (agent_dir / MLFLOW_PROJECT_FILE).is_file(): print("Running agent in this dir via MLflow.") mlflow.projects.run(str(agent_dir.absolute())) return elif (agent_dir / AGENT_MAIN_FILE).is_file(): print( f"Running agent in this dir via MLflow with " f"entry point {AGENT_MAIN_FILE}." ) mlflow.projects.run( str(agent_dir.absolute()), entry_point=AGENT_MAIN_FILE.name ) else: if not (agent_dir / AGENT_DEF_FILE).is_file(): raise click.UsageError( "No args were passed to run, so one " f"of {MLFLOW_PROJECT_FILE}, " f"{AGENT_MAIN_FILE}, " f"{AGENT_DEF_FILE} must exist." ) _handle_single_run_arg(agent_dir / AGENT_DEF_FILE) def _handle_single_run_arg(filename): """The file must contain: - 1 or more agentos.Agent subclass - 1 or more gym.Env subclass. """ agent_cls = _get_subclass_from_file(filename, agentos.Agent) env_cls = _get_subclass_from_file(filename, gym.Env) assert agent_cls and env_cls, ( f" {filename} must contain >= 1 agentos.Agent subclass " f"and >= 1 gym.Env subclass." ) agentos.run_agent(agent_cls, env_cls, hz=hz, max_iters=max_iters) if len(run_args) == 0: _handle_no_run_args() elif len(run_args) == 1: if Path(run_args[0]).is_dir(): _handle_no_run_args(run_args[0]) if Path(run_args[0]).is_file(): _handle_single_run_arg(run_args[0]) else: raise click.UsageError( "1 argument was passed to run; it must be " "a filename and it is not. (The file " "should define your agent class.)" ) elif len(run_args) == 2: agent_arg, env_arg = run_args[0], run_args[1] if Path(agent_arg).is_file(): agent_cls = _get_subclass_from_file(agent_arg, agentos.Agent) assert ( agent_cls ), f"{agent_arg} must contain a subclass of agentos.Agent" else: ag_mod_name = ".".join(agent_arg.split(".")[:-1]) ag_cls_name = agent_arg.split(".")[-1] ag_mod = importlib.import_module(ag_mod_name) agent_cls = getattr(ag_mod, ag_cls_name) if Path(env_arg).is_file(): env_cls = _get_subclass_from_file(env_arg, gym.Env) assert env_cls, f"{env_arg} must contain a subclass of gym.Env" else: env_mod_name = ".".join(env_arg.split(".")[:-1]) env_cls_name = env_arg.split(".")[-1] env_mod = importlib.import_module(env_mod_name) env_cls = getattr(env_mod, env_cls_name) agentos.run_agent(agent_cls, env_cls, hz=hz, max_iters=max_iters) else: raise click.UsageError("run command can take 0, 1, or 2 arguments.") if __name__ == "__main__": agentos_cmd()
agentos/cli.py
import agentos import click from datetime import datetime import gym import mlflow.projects import importlib.util from pathlib import Path CONDA_ENV_FILE = Path("./conda_env.yaml") CONDA_ENV_CONTENT = """{file_header} name: {name} dependencies: - pip - pip: - gym - agentos # Or, if you want to use your local copy of agentos, then # update the line below and replace the line above with it. #- -e path/to/agentos/git/repo """ MLFLOW_PROJECT_FILE = Path("./MLProject") MLFLOW_PROJECT_CONTENT = """{file_header} name: {name} conda_env: {conda_env} entry_points: main: command: "python main.py" """ AGENT_DEF_FILE = Path("./agent.py") # Default location of agent code. AGENT_MAIN_FILE = Path("./main.py") AGENT_MAIN = """{file_header} import agentos import random import gym # TODO: REPLACE THE EXAMPLE CODE BELOW WITH YOUR OWN! # A minimal 1D hallway env class. class MyEnv(gym.Env): def __init__(self): super().__init__() self.l_r_pos = 0 # left is neg, right is pos. def reset(self): self.l_r_pos = 0 return 0 def step(self, action): self.l_r_pos += action return self.l_r_pos, abs(self.l_r_pos), False, dict() # A minimal example agent class. class MyAgent(agentos.Agent): def __init__(self, env_class): super().__init__(env_class) self.step_count = 0 def advance(self): print("Taking step " + str(self.step_count)) pos_in_env, _, _, _ = self.env.step(random.choice([-1,1])) print("Position in env is now: " + str(pos_in_env)) self.step_count += 1 if __name__ == "__main__": agentos.run_agent(MyAgent, MyEnv, max_iters=5) """ INIT_FILES = { CONDA_ENV_FILE: CONDA_ENV_CONTENT, MLFLOW_PROJECT_FILE: MLFLOW_PROJECT_CONTENT, AGENT_MAIN_FILE: AGENT_MAIN, } @click.group() @click.version_option() def agentos_cmd(): pass def validate_agent_name(ctx, param, value): if " " in value or ":" in value or "/" in value: raise click.BadParameter("name may not contain ' ', ':', or '/'.") return value @agentos_cmd.command() @click.argument("dir_names", nargs=-1, metavar="DIR_NAMES") @click.option( "--name", "-n", metavar="AGENT_NAME", default="new_agent", callback=validate_agent_name, help="This is used as the name of the MLflow Project and " "Conda env for all *Directory Agents* being created. " "AGENT_NAME may not contain ' ', ':', or '/'.", ) def init(dir_names, name): """Initialize current (or specified) directory as an AgentOS agent. \b Arguments: [OPTIONAL] DIR_NAMES zero or more space separated directories to initialize. They will be created if they do not exist. Creates an agent main.py file, a conda env, and an MLflow project file in all directories specified, or if none are specified, then create the files in current directory. """ dirs = [Path(".")] if dir_names: dirs = [Path(d) for d in dir_names] for d in dirs: d.mkdir(parents=True, exist_ok=True) for file_path, content in INIT_FILES.items(): f = open(d / file_path, "w") now = datetime.now().strftime("%b %d, %Y %H:%M:%S") header = ( f"# This file was auto-generated by `agentos init` on {now}." ) f.write( content.format( name=name, conda_env=CONDA_ENV_FILE.name, file_header=header, ) ) f.flush() d = "current working directory" if d == Path(".") else d click.echo(f"Finished initializing AgentOS agent '{name}' in {d}.") def _get_subclass_from_file(filename, parent_class): """Return first subclass of `parent_class` found in filename, else None.""" path = Path(filename) assert path.is_file(), f"Make {path} is a valid file." assert path.suffix == ".py", "Filename must end in .py" spec = importlib.util.spec_from_file_location(path.stem, path.absolute()) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) for elt in module.__dict__.values(): if type(elt) is type and issubclass(elt, parent_class): print(f"Found first subclass class {elt}; returning it.") return elt @agentos_cmd.command() @click.argument("run_args", nargs=-1, metavar="RUN_ARGS") @click.option( "--hz", "-h", metavar="HZ", default=40, type=int, help="Frequency to call agent.advance().", ) @click.option( "--max-iters", "-m", metavar="MAX_STEPS", type=int, default=None, help="Stop running agent after this many calls to advance().", ) def run(run_args, hz, max_iters): """Run an AgentOS agent (agentos.Agent) with an environment (gym.Env). \b Arguments: RUN_ARGS: 0, 1, or 2 space delimited arguments, parsed as follows: \b If no args are specified, look for default files defining agent: - look for file named `MLProject` or `main.py` in the current working directory and if found, run this directory as an MLflow project. - Try to use MLProject file first, using whatever it defines as main entry point, and if that doesn't exist then run using MLflow without MLProject passing main.py as the entry point (note that this will ignore a conda environment file if one exists and MLflow will create a new essentially empty conda env). - else, look for file named `agent.py` in current working directory and, if found, then behave in the same was as if 1 argument (i.e., `agent.py`) was provided, as described below. Else, if 1 arg is specified, interpret it as `agent_filename`: - if it is a directory name, assume it is an AgentOS agent dir, and behavior is equivalent of navigating into that directory and running `agentos run` (without arguments) in it (see above). - if it is a file name, the file must contain an agent class and env class definition. AgentOS searches that file for the first subclass of agentos.Agent, as well as first subclass of gym.Env and calls agentos.run_agent() passing in the agent and env classes found. Else, if 2 args specified, interpret as either filenames or py classes. - assume the first arg specifies the agent and second specifies the Env. The following parsing rules are applied independently to each of the two args (e.g., filenames and classes can be mixed): - if the arg is a filename: Look for the first instance of the appropriate subclass (either agentos.Agent or gym.env) in the file and use that as the argument to agentos.run_agent. - else: Assume the arg is in the form [package.][module.]classname and that it is available in this python environments path. """ def _handle_no_run_args(dirname=None): if dirname: agent_dir = Path(dirname) assert agent_dir.is_dir() else: agent_dir = Path("./") if (agent_dir / MLFLOW_PROJECT_FILE).is_file(): print("Running agent in this dir via MLflow.") mlflow.projects.run(str(agent_dir.absolute())) return elif (agent_dir / AGENT_MAIN_FILE).is_file(): print( f"Running agent in this dir via MLflow with " f"entry point {AGENT_MAIN_FILE}." ) mlflow.projects.run( str(agent_dir.absolute()), entry_point=AGENT_MAIN_FILE.name ) else: if not (agent_dir / AGENT_DEF_FILE).is_file(): raise click.UsageError( "No args were passed to run, so one " f"of {MLFLOW_PROJECT_FILE}, " f"{AGENT_MAIN_FILE}, " f"{AGENT_DEF_FILE} must exist." ) _handle_single_run_arg(agent_dir / AGENT_DEF_FILE) def _handle_single_run_arg(filename): """The file must contain: - 1 or more agentos.Agent subclass - 1 or more gym.Env subclass. """ agent_cls = _get_subclass_from_file(filename, agentos.Agent) env_cls = _get_subclass_from_file(filename, gym.Env) assert agent_cls and env_cls, ( f" {filename} must contain >= 1 agentos.Agent subclass " f"and >= 1 gym.Env subclass." ) agentos.run_agent(agent_cls, env_cls, hz=hz, max_iters=max_iters) if len(run_args) == 0: _handle_no_run_args() elif len(run_args) == 1: if Path(run_args[0]).is_dir(): _handle_no_run_args(run_args[0]) if Path(run_args[0]).is_file(): _handle_single_run_arg(run_args[0]) else: raise click.UsageError( "1 argument was passed to run; it must be " "a filename and it is not. (The file " "should define your agent class.)" ) elif len(run_args) == 2: agent_arg, env_arg = run_args[0], run_args[1] if Path(agent_arg).is_file(): agent_cls = _get_subclass_from_file(agent_arg, agentos.Agent) assert ( agent_cls ), f"{agent_arg} must contain a subclass of agentos.Agent" else: ag_mod_name = ".".join(agent_arg.split(".")[:-1]) ag_cls_name = agent_arg.split(".")[-1] ag_mod = importlib.import_module(ag_mod_name) agent_cls = getattr(ag_mod, ag_cls_name) if Path(env_arg).is_file(): env_cls = _get_subclass_from_file(env_arg, gym.Env) assert env_cls, f"{env_arg} must contain a subclass of gym.Env" else: env_mod_name = ".".join(env_arg.split(".")[:-1]) env_cls_name = env_arg.split(".")[-1] env_mod = importlib.import_module(env_mod_name) env_cls = getattr(env_mod, env_cls_name) agentos.run_agent(agent_cls, env_cls, hz=hz, max_iters=max_iters) else: raise click.UsageError("run command can take 0, 1, or 2 arguments.") if __name__ == "__main__": agentos_cmd()
0.428951
0.227191
from django.db import models from django.utils import timezone from django.utils.text import slugify from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from .markup import markup class CategoryQuerySet(models.QuerySet): def search(self, term): return self.filter(name__icontains=term) class Category(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, editable=False) objects = CategoryQuerySet().as_manager() class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('category', args=[self.slug]) class TagQuerySet(models.QuerySet): def search(self, term): return self.filter(name__icontains=term) class Tag(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, editable=False) objects = TagQuerySet().as_manager() def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self, self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('tag', args=[self.slug]) class ArticleQuerySet(models.QuerySet): def published(self): return self.filter(date__lte=timezone.now()) def search(self, term): return self.published().filter(title__icontains=term) def prev(self, date): """ Return previous posts relative to `date` """ return self.published().filter(date__lt=date) def next(self, date): """ Return next posts relative to `date` """ return self.published().filter(date__gt=date) class Article(models.Model): title = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, editable=False) date = models.DateTimeField(default=timezone.now) tags = models.ManyToManyField(Tag) category = models.ForeignKey(Category) content = models.TextField() content_html = models.TextField(editable=False, blank=True) objects = ArticleQuerySet().as_manager() class Meta: ordering = ('-date',) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) self.content_html = markup(self.content) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('article', args=[self.slug]) def is_published(self): return self.date <= timezone.now() def prev(self): """ return previous article relative to `self`. Im not sure about this method. Is there a better one? Maybe Manager should take care of this... """ try: return Article.objects.prev(self.date).first() except IndexError as e: return 0 def next(self): try: return Article.objects.next(self.date).last() except IndexError as e: return 0
blog/models.py
from django.db import models from django.utils import timezone from django.utils.text import slugify from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from .markup import markup class CategoryQuerySet(models.QuerySet): def search(self, term): return self.filter(name__icontains=term) class Category(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, editable=False) objects = CategoryQuerySet().as_manager() class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('category', args=[self.slug]) class TagQuerySet(models.QuerySet): def search(self, term): return self.filter(name__icontains=term) class Tag(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, editable=False) objects = TagQuerySet().as_manager() def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self, self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('tag', args=[self.slug]) class ArticleQuerySet(models.QuerySet): def published(self): return self.filter(date__lte=timezone.now()) def search(self, term): return self.published().filter(title__icontains=term) def prev(self, date): """ Return previous posts relative to `date` """ return self.published().filter(date__lt=date) def next(self, date): """ Return next posts relative to `date` """ return self.published().filter(date__gt=date) class Article(models.Model): title = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, editable=False) date = models.DateTimeField(default=timezone.now) tags = models.ManyToManyField(Tag) category = models.ForeignKey(Category) content = models.TextField() content_html = models.TextField(editable=False, blank=True) objects = ArticleQuerySet().as_manager() class Meta: ordering = ('-date',) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) self.content_html = markup(self.content) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('article', args=[self.slug]) def is_published(self): return self.date <= timezone.now() def prev(self): """ return previous article relative to `self`. Im not sure about this method. Is there a better one? Maybe Manager should take care of this... """ try: return Article.objects.prev(self.date).first() except IndexError as e: return 0 def next(self): try: return Article.objects.next(self.date).last() except IndexError as e: return 0
0.529993
0.123445
from __future__ import annotations import difflib import re from collections import Counter from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from textwrap import indent import uharfbuzz as hb import yaml from fontTools import unicodedata from data import mongolian from utils import joining_form_to_joinedness, slice_joining_form scripting_dir = Path(__file__).parent tagging_dir = scripting_dir / "tagging" project_dir = scripting_dir / ".." repo_dir = scripting_dir / ".." / ".." private_repo_dir = repo_dir / ".." / "mongolian-private" class Shaper: def __init__(self, path: Path): self.path = path face = hb.Face(path.read_bytes()) # type: ignore self.font = hb.Font(face) # type: ignore hb.ot_font_set_funcs(self.font) # type: ignore def shape_text_to_glyph_names( self, text: str, features: dict = None, gid_to_name: dict[int, str] = None, ) -> list[str]: buffer = hb.Buffer() # type: ignore buffer.add_str(text) buffer.guess_segment_properties() hb.shape(self.font, buffer, features) # type: ignore names = [] for info, position in zip(buffer.glyph_infos, buffer.glyph_positions): gid = info.codepoint if gid_to_name is None: name = self.font.get_glyph_name(gid) else: name = gid_to_name.get(gid, f"gid{gid}") if name == "space" and position.x_advance == 0: # HarfBuzz pseudo space for invisible glyphs name = "_invisible" names.append(name) return names @dataclass class Testee: name: str shaper: Shaper gid_to_name: dict[int, str] | None = None name_to_standard: dict[str, str] | None = None normalizer: Callable[[list[str]], list[str]] = lambda x: x def shape(self, string: str) -> list[str]: glyph_names = self.shaper.shape_text_to_glyph_names(string, gid_to_name=self.gid_to_name) if self.name_to_standard is not None: glyph_names = [self.name_to_standard.get(i) or i for i in glyph_names] glyph_names = self.normalizer(glyph_names) glyph_names = general_normalizer(glyph_names) return glyph_names corpus_loader_by_tag = { "combined": ( lambda: "\n".join(v() for k, v in corpus_loader_by_tag.items() if k != "combined") ), "jirimutu": ( lambda: "\n".join( (private_repo_dir / f"misc/jirimutu/mongol_corpus/almas_{i:03}.txt").read_text() for i in range(1, 65) ) ), "badamsuren": ( lambda: (private_repo_dir / "misc/badamsuren/Badamsuren.txt").read_text() ), } def main(): microsoft = Testee( name="microsoft", shaper=Shaper(private_repo_dir / "misc/gregeck/20210527/monbaiti.ttf"), gid_to_name=yaml.safe_load((tagging_dir / "microsoft.yaml").read_text()) | { 257: "a.A_A.isol", 262: "a.A.init", 274: "e.A.isol", 704: "y.I.fina", }, normalizer=microsoft_normalizer, ) eac = Testee( name="eac", shaper=Shaper(private_repo_dir / "misc/liangjinbao/20210303/MongolQaganTig.ttf"), name_to_standard=yaml.safe_load((tagging_dir / "eac.yaml").read_text()), normalizer=eac_normalizer, ) utn = Testee( name="utn", shaper=Shaper(project_dir / "products" / "DummyStateless-Regular.otf"), normalizer=utn_normalizer, ) for corpus_tag in [ "jirimutu", "badamsuren", ]: test(eac, utn, corpus_tag) for alt in [eac, utn]: test(microsoft, alt, corpus_tag) def test(baseline: Testee, alt: Testee, corpus_tag: str): print("===") print(f"Shaping models: {baseline.name} vs. {alt.name}") print(f"Corpus: {corpus_tag}") print("---") filename = f"{baseline.name}-vs-{alt.name}-with-{corpus_tag}-corpus.txt" with (scripting_dir / ".." / "reports" / filename).open("w") as f: text = corpus_loader_by_tag[corpus_tag]() cases = Counter[str]( i.group(0) for i in re.finditer(r"\u202F?[\u200C\u200D\u180A-\u180E\u1807\u1820-\u1842]+", text) ) total = sum(cases.values()) message = f"Total word count: {total}" print(message) print(message, file=f) passed = 0 for index, (case, count) in enumerate(cases.most_common()): baseline_shaping = baseline.shape(case) alt_shaping = alt.shape(case) if baseline_shaping == alt_shaping: passed += count else: string_notation = ", ".join( cp_to_name.get(i) or unicodedata.name(i, f"U+{ord(i):04X}") for i in case ) percentage = round(count / total * 100, 4) if percentage >= 0.01: message = f"Failed: case {index} (word count {count} ≈ {percentage} %): {string_notation}" print(message) print(message, file=f) for line in [*difflib.unified_diff(baseline_shaping, alt_shaping, lineterm="")][3:]: print(indent(line, " " * 4), file=f) else: print(f"Failed: case {index} (word count {count} < 0.01 %): {string_notation}", file=f) print("---") failed = total - passed for message in [ f"Failed word count: {failed}/{total} = {failed / total * 100} %", f"Passed word count: {passed}/{total} = {passed / total * 100} %", ]: print(message) print(message, file=f) print("===") cp_to_name = {chr(character.cp): character_id for character_id, character in mongolian.characters.items()} def split_ligature(name: str) -> list[str]: name_elements = name.split(".") if not len(name_elements) == 3: return [name] _, graphic, joining_form = name_elements graphic_parts = graphic.split("_") joining_forms = slice_joining_form(joining_form, len(graphic_parts)) return [".".join(i) for i in zip(graphic_parts, joining_forms)] def general_normalizer(names: list[str]) -> list[str]: names_to_drop = { "_invisible", } name_to_standard = { f"K2.{i}": f"K.{i}" for i in joining_form_to_joinedness.keys() } confusables_to_neutralized = { (f"{i}.isol", f"{i}.fina"): f"{i}.isol/fina" for i in ["Aa", "I", "U"] } | { (f"{i}.init", f"{i}.medi"): f"{i}.init/medi" for i in [ "I", "O", "B", "P", "G", "Gx", "T", "D", "Ch", "Y", "R", "W", "F", "K", "C", "Z", "Rh", ] } normalized = [] for name in names: if name in names_to_drop: continue name = name_to_standard.get(name) or name for confusables, neutralized in confusables_to_neutralized.items(): if name in confusables: normalized.append(neutralized) break else: normalized.append(name) return normalized def microsoft_normalizer(names: list[str]) -> list[str]: part_to_standard = { f"Hx.{i}": f"Gh.{i}" for i in joining_form_to_joinedness.keys() } normalized = [] for name in names: for part in split_ligature(name): normalized.append(part_to_standard.get(part) or part) return normalized def eac_normalizer(names: list[str]) -> list[str]: name_to_standard = { "a.Aa.fina": "a.Aa.isol", "e.Aa.fina": "e.Aa.isol", } normalized = [] for name in names: name = name_to_standard.get(name) or name normalized.extend(split_ligature(name)) return normalized def utn_normalizer(names: list[str]) -> list[str]: names_to_drop = { "_nil", "_fvs1", "_fvs2", "_fvs3", "_fvs4", "_masculine", } name_to_standard = { "_nnbsp": "nnbsp", } normalized = [] for name in names: if name in names_to_drop: continue name = name_to_standard.get(name) or name normalized.extend(split_ligature(name)) return normalized if __name__ == "__main__": main()
font-tooling/scripting/real_text_test.py
from __future__ import annotations import difflib import re from collections import Counter from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from textwrap import indent import uharfbuzz as hb import yaml from fontTools import unicodedata from data import mongolian from utils import joining_form_to_joinedness, slice_joining_form scripting_dir = Path(__file__).parent tagging_dir = scripting_dir / "tagging" project_dir = scripting_dir / ".." repo_dir = scripting_dir / ".." / ".." private_repo_dir = repo_dir / ".." / "mongolian-private" class Shaper: def __init__(self, path: Path): self.path = path face = hb.Face(path.read_bytes()) # type: ignore self.font = hb.Font(face) # type: ignore hb.ot_font_set_funcs(self.font) # type: ignore def shape_text_to_glyph_names( self, text: str, features: dict = None, gid_to_name: dict[int, str] = None, ) -> list[str]: buffer = hb.Buffer() # type: ignore buffer.add_str(text) buffer.guess_segment_properties() hb.shape(self.font, buffer, features) # type: ignore names = [] for info, position in zip(buffer.glyph_infos, buffer.glyph_positions): gid = info.codepoint if gid_to_name is None: name = self.font.get_glyph_name(gid) else: name = gid_to_name.get(gid, f"gid{gid}") if name == "space" and position.x_advance == 0: # HarfBuzz pseudo space for invisible glyphs name = "_invisible" names.append(name) return names @dataclass class Testee: name: str shaper: Shaper gid_to_name: dict[int, str] | None = None name_to_standard: dict[str, str] | None = None normalizer: Callable[[list[str]], list[str]] = lambda x: x def shape(self, string: str) -> list[str]: glyph_names = self.shaper.shape_text_to_glyph_names(string, gid_to_name=self.gid_to_name) if self.name_to_standard is not None: glyph_names = [self.name_to_standard.get(i) or i for i in glyph_names] glyph_names = self.normalizer(glyph_names) glyph_names = general_normalizer(glyph_names) return glyph_names corpus_loader_by_tag = { "combined": ( lambda: "\n".join(v() for k, v in corpus_loader_by_tag.items() if k != "combined") ), "jirimutu": ( lambda: "\n".join( (private_repo_dir / f"misc/jirimutu/mongol_corpus/almas_{i:03}.txt").read_text() for i in range(1, 65) ) ), "badamsuren": ( lambda: (private_repo_dir / "misc/badamsuren/Badamsuren.txt").read_text() ), } def main(): microsoft = Testee( name="microsoft", shaper=Shaper(private_repo_dir / "misc/gregeck/20210527/monbaiti.ttf"), gid_to_name=yaml.safe_load((tagging_dir / "microsoft.yaml").read_text()) | { 257: "a.A_A.isol", 262: "a.A.init", 274: "e.A.isol", 704: "y.I.fina", }, normalizer=microsoft_normalizer, ) eac = Testee( name="eac", shaper=Shaper(private_repo_dir / "misc/liangjinbao/20210303/MongolQaganTig.ttf"), name_to_standard=yaml.safe_load((tagging_dir / "eac.yaml").read_text()), normalizer=eac_normalizer, ) utn = Testee( name="utn", shaper=Shaper(project_dir / "products" / "DummyStateless-Regular.otf"), normalizer=utn_normalizer, ) for corpus_tag in [ "jirimutu", "badamsuren", ]: test(eac, utn, corpus_tag) for alt in [eac, utn]: test(microsoft, alt, corpus_tag) def test(baseline: Testee, alt: Testee, corpus_tag: str): print("===") print(f"Shaping models: {baseline.name} vs. {alt.name}") print(f"Corpus: {corpus_tag}") print("---") filename = f"{baseline.name}-vs-{alt.name}-with-{corpus_tag}-corpus.txt" with (scripting_dir / ".." / "reports" / filename).open("w") as f: text = corpus_loader_by_tag[corpus_tag]() cases = Counter[str]( i.group(0) for i in re.finditer(r"\u202F?[\u200C\u200D\u180A-\u180E\u1807\u1820-\u1842]+", text) ) total = sum(cases.values()) message = f"Total word count: {total}" print(message) print(message, file=f) passed = 0 for index, (case, count) in enumerate(cases.most_common()): baseline_shaping = baseline.shape(case) alt_shaping = alt.shape(case) if baseline_shaping == alt_shaping: passed += count else: string_notation = ", ".join( cp_to_name.get(i) or unicodedata.name(i, f"U+{ord(i):04X}") for i in case ) percentage = round(count / total * 100, 4) if percentage >= 0.01: message = f"Failed: case {index} (word count {count} ≈ {percentage} %): {string_notation}" print(message) print(message, file=f) for line in [*difflib.unified_diff(baseline_shaping, alt_shaping, lineterm="")][3:]: print(indent(line, " " * 4), file=f) else: print(f"Failed: case {index} (word count {count} < 0.01 %): {string_notation}", file=f) print("---") failed = total - passed for message in [ f"Failed word count: {failed}/{total} = {failed / total * 100} %", f"Passed word count: {passed}/{total} = {passed / total * 100} %", ]: print(message) print(message, file=f) print("===") cp_to_name = {chr(character.cp): character_id for character_id, character in mongolian.characters.items()} def split_ligature(name: str) -> list[str]: name_elements = name.split(".") if not len(name_elements) == 3: return [name] _, graphic, joining_form = name_elements graphic_parts = graphic.split("_") joining_forms = slice_joining_form(joining_form, len(graphic_parts)) return [".".join(i) for i in zip(graphic_parts, joining_forms)] def general_normalizer(names: list[str]) -> list[str]: names_to_drop = { "_invisible", } name_to_standard = { f"K2.{i}": f"K.{i}" for i in joining_form_to_joinedness.keys() } confusables_to_neutralized = { (f"{i}.isol", f"{i}.fina"): f"{i}.isol/fina" for i in ["Aa", "I", "U"] } | { (f"{i}.init", f"{i}.medi"): f"{i}.init/medi" for i in [ "I", "O", "B", "P", "G", "Gx", "T", "D", "Ch", "Y", "R", "W", "F", "K", "C", "Z", "Rh", ] } normalized = [] for name in names: if name in names_to_drop: continue name = name_to_standard.get(name) or name for confusables, neutralized in confusables_to_neutralized.items(): if name in confusables: normalized.append(neutralized) break else: normalized.append(name) return normalized def microsoft_normalizer(names: list[str]) -> list[str]: part_to_standard = { f"Hx.{i}": f"Gh.{i}" for i in joining_form_to_joinedness.keys() } normalized = [] for name in names: for part in split_ligature(name): normalized.append(part_to_standard.get(part) or part) return normalized def eac_normalizer(names: list[str]) -> list[str]: name_to_standard = { "a.Aa.fina": "a.Aa.isol", "e.Aa.fina": "e.Aa.isol", } normalized = [] for name in names: name = name_to_standard.get(name) or name normalized.extend(split_ligature(name)) return normalized def utn_normalizer(names: list[str]) -> list[str]: names_to_drop = { "_nil", "_fvs1", "_fvs2", "_fvs3", "_fvs4", "_masculine", } name_to_standard = { "_nnbsp": "nnbsp", } normalized = [] for name in names: if name in names_to_drop: continue name = name_to_standard.get(name) or name normalized.extend(split_ligature(name)) return normalized if __name__ == "__main__": main()
0.643105
0.15511
class MediatorInterface: """ The Mediator interface declares a method used by components to notify the mediator about various events. The mediator may react to these events and pass the execution to other components. """ def notify(self, sender: object, event: str) -> None: raise NotImplementedError() class ConcreteMediator(MediatorInterface): def __init__(self, component_1: 'Component1', component_2: 'Component2') -> None: self._component_1 = component_1 self._component_2 = component_2 self._component_1.set_mediator(self) self._component_2.set_mediator(self) def notify(self, sender: object, event: str) -> None: if event == 'A': print('Mediator reacts on A and triggers following operations:') self._component_2.do_c() elif event == 'D': print('Mediator reacts on D and triggers following operations:') self._component_1.do_b() self._component_2.do_c() class BaseComponent: """ The Base Component provides the basic functionality of storing a mediator's instance inside component objects. """ def __init__(self, mediator: MediatorInterface = None) -> None: self._mediator = mediator def set_mediator(self, mediator: MediatorInterface) -> None: self._mediator = mediator class Component1(BaseComponent): """ Concrete Components implement various functionality. They don't depend on other components. They also don't depend on any concrete mediator classes. """ def do_a(self) -> None: print('Component 1 does A.') self._mediator.notify(self, 'A') def do_b(self) -> None: print('Component 1 does B.') self._mediator.notify(self, 'B') class Component2(BaseComponent): def do_c(self) -> None: print('Component 2 does C.') self._mediator.notify(self, 'C') def do_d(self) -> None: print('Component 2 does D.') self._mediator.notify(self, 'D') class Demo: def run(self) -> None: _component1 = Component1() _component2 = Component2() _mediator: MediatorInterface = ConcreteMediator(_component1, _component2) print("Client triggers operation A.") _component1.do_a() print('\n', end="") print("Client triggers operation D.") _component2.do_d() demo: Demo = Demo() demo.run()
behavioral/mediator/refactoring-guru.py
class MediatorInterface: """ The Mediator interface declares a method used by components to notify the mediator about various events. The mediator may react to these events and pass the execution to other components. """ def notify(self, sender: object, event: str) -> None: raise NotImplementedError() class ConcreteMediator(MediatorInterface): def __init__(self, component_1: 'Component1', component_2: 'Component2') -> None: self._component_1 = component_1 self._component_2 = component_2 self._component_1.set_mediator(self) self._component_2.set_mediator(self) def notify(self, sender: object, event: str) -> None: if event == 'A': print('Mediator reacts on A and triggers following operations:') self._component_2.do_c() elif event == 'D': print('Mediator reacts on D and triggers following operations:') self._component_1.do_b() self._component_2.do_c() class BaseComponent: """ The Base Component provides the basic functionality of storing a mediator's instance inside component objects. """ def __init__(self, mediator: MediatorInterface = None) -> None: self._mediator = mediator def set_mediator(self, mediator: MediatorInterface) -> None: self._mediator = mediator class Component1(BaseComponent): """ Concrete Components implement various functionality. They don't depend on other components. They also don't depend on any concrete mediator classes. """ def do_a(self) -> None: print('Component 1 does A.') self._mediator.notify(self, 'A') def do_b(self) -> None: print('Component 1 does B.') self._mediator.notify(self, 'B') class Component2(BaseComponent): def do_c(self) -> None: print('Component 2 does C.') self._mediator.notify(self, 'C') def do_d(self) -> None: print('Component 2 does D.') self._mediator.notify(self, 'D') class Demo: def run(self) -> None: _component1 = Component1() _component2 = Component2() _mediator: MediatorInterface = ConcreteMediator(_component1, _component2) print("Client triggers operation A.") _component1.do_a() print('\n', end="") print("Client triggers operation D.") _component2.do_d() demo: Demo = Demo() demo.run()
0.643553
0.498474
import traceback from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.template.response import TemplateResponse from django.conf import settings from django import http from django.contrib import messages from django.contrib.auth.decorators import permission_required from django import forms from django.views.decorators.csrf import csrf_exempt from .models import User, SocialHandle class SocialInline(admin.TabularInline): model = SocialHandle class User2CreationForm(UserCreationForm): class Meta: model = User fields = ("username", "email", "verified_email") def clean_username(self): username = self.cleaned_data["username"] try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError( self.error_messages['duplicate_username'], code='duplicate_username') class User2ChangeForm(UserChangeForm): class Meta: model = User fields = '__all__' permission_required('profiles.change_user') class CurrentSpeakerFilter(admin.SimpleListFilter): title = 'Current Speaker' parameter_name = 'current' def lookups(self, request, model_admin): return (('1', 'Current Speakers'),) def queryset(self, request, queryset): if self.value() == '1': return queryset.filter( session__status='accepted', session__conference__slug=settings.DEFAULT_CONF).exclude( session__stype='lightning') @admin.register(User) class User2Admin(UserAdmin): list_display = ('username', 'email', 'name', 'phone', 'current_speaker', 'is_staff', 'is_superuser') #list_filter = (CurrentSpeakerFilter,) search_fields = ('name', 'email', 'phone') inlines = (SocialInline,) form = User2ChangeForm add_form = User2CreationForm fieldsets = ( (None, { 'fields': ('username', 'password') }), ('Personal info', { 'fields': ('name', 'title', 'location', 'email', 'verified_email', 'phone', 'website', 'avatar', 'biography') }), ('Permissions', { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups') }), ('Important dates', { 'fields': ('last_login', 'date_joined', 'from_import') }), ) readonly_fields = ('last_login', 'date_joined', 'from_import') add_fieldsets = ((None, { 'classes': ('wide',), 'fields': ('username', 'email', 'verified_email', '<PASSWORD>', '<PASSWORD>') }),) def current_speaker(self, obj): return 'coming soon' if obj.session_set.filter( status='accepted', conference__slug=settings.DEFAULT_CONF).exclude( stype='lightning').count() > 0: return '<strong style="color: green;">&#10003;</strong>' return '<strong style="color: red;">&times;</strong>' current_speaker.allow_tags = True
conference/profiles/admin.py
import traceback from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.template.response import TemplateResponse from django.conf import settings from django import http from django.contrib import messages from django.contrib.auth.decorators import permission_required from django import forms from django.views.decorators.csrf import csrf_exempt from .models import User, SocialHandle class SocialInline(admin.TabularInline): model = SocialHandle class User2CreationForm(UserCreationForm): class Meta: model = User fields = ("username", "email", "verified_email") def clean_username(self): username = self.cleaned_data["username"] try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError( self.error_messages['duplicate_username'], code='duplicate_username') class User2ChangeForm(UserChangeForm): class Meta: model = User fields = '__all__' permission_required('profiles.change_user') class CurrentSpeakerFilter(admin.SimpleListFilter): title = 'Current Speaker' parameter_name = 'current' def lookups(self, request, model_admin): return (('1', 'Current Speakers'),) def queryset(self, request, queryset): if self.value() == '1': return queryset.filter( session__status='accepted', session__conference__slug=settings.DEFAULT_CONF).exclude( session__stype='lightning') @admin.register(User) class User2Admin(UserAdmin): list_display = ('username', 'email', 'name', 'phone', 'current_speaker', 'is_staff', 'is_superuser') #list_filter = (CurrentSpeakerFilter,) search_fields = ('name', 'email', 'phone') inlines = (SocialInline,) form = User2ChangeForm add_form = User2CreationForm fieldsets = ( (None, { 'fields': ('username', 'password') }), ('Personal info', { 'fields': ('name', 'title', 'location', 'email', 'verified_email', 'phone', 'website', 'avatar', 'biography') }), ('Permissions', { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups') }), ('Important dates', { 'fields': ('last_login', 'date_joined', 'from_import') }), ) readonly_fields = ('last_login', 'date_joined', 'from_import') add_fieldsets = ((None, { 'classes': ('wide',), 'fields': ('username', 'email', 'verified_email', '<PASSWORD>', '<PASSWORD>') }),) def current_speaker(self, obj): return 'coming soon' if obj.session_set.filter( status='accepted', conference__slug=settings.DEFAULT_CONF).exclude( stype='lightning').count() > 0: return '<strong style="color: green;">&#10003;</strong>' return '<strong style="color: red;">&times;</strong>' current_speaker.allow_tags = True
0.347537
0.053899
import os import logging import time log = logging.getLogger(__name__) def batch_dl2_to_sensitivity( dl2_directory, offset_gammas, job_ids_from_dl1_dl2, log_from_dl1_dl2, source_env, prod_id, ): """ Batches the dl2_to_sensitivity stage (`stages.script_dl2_to_sensitivity` based in the pyIRF iib) once the dl1_to_dl2 stage had finished. Parameters ---------- dl2_directory: str Base path to DL2 directory to be formatted with particle type offset_gammas: list list off gamma offsets job_ids_from_dl1_dl2: str Comma-separated string with the job ids from the dl1_to_dl2 stage to be used as a slurm dependency to schedule the current stage log_from_dl1_dl2: dict Dictionary from dl1_to_dl2 stage with particle path information source_env: str source environment to select the desired conda environment (source .bashrc + conda activate $ENV) prod_id: str String with prod_id prefix to complete 'file-naming' Returns ------- log_dl2_to_sensitivity: dict Dictionary with job_id-slurm command key-value pair used for logging jobid_for_check: str Comma-separated jobids batched in the current stage debug_log: dict Dictionary with the job-id and stage explanation to be stored in the debug file """ log.info("==== START {} ====".format("batch mc_dl2_to_sensitivity")) time.sleep(1) debug_log = {} jobid_for_check = [] log_dl2_to_sensitivity = {} for off in offset_gammas: job_logs, jobid = dl2_to_sensitivity( dl2_directory, log_from_dl1_dl2, gamma_offset=off, prod_id=prod_id, source_env=source_env, wait_jobs_dl1_dl2=job_ids_from_dl1_dl2, ) jobid_for_check.append(jobid) log_dl2_to_sensitivity[f"gamma_{off}"] = job_logs debug_log[jobid] = ( f"Gamma_{off} job_ids from the dl2_to_sensitivity stage and the plot_irfs script that " f"depends on the dl1_to_dl2 stage job_ids; {job_ids_from_dl1_dl2}" ) log.info("Jobs for gamma offset {} have been submitted".format(off)) log.debug( f"Gamma_{off} job_ids from the dl2_to_sensitivity stage and the plot_irfs script that " f"depends on the dl1_to_dl2 stage job_ids; {job_ids_from_dl1_dl2}" ) jobid_for_check = ",".join(jobid_for_check) log.info("==== END {} ====".format("batch mc_dl2_to_sensitivity")) return log_dl2_to_sensitivity, jobid_for_check, debug_log def compose_sensitivity_outdir(dl2_dir, gamma_offset): """ Compute the sensitivity output directory depending on the type of gamma file Parameters ---------- dl2_dir: str Base path to DL2 directory gamma_offset: str String to indicate the gamma offset. Either 'off0.0deg' or 'off0.4deg' Returns ------- output_sensitivity_dir: str Absolute path in where to store the sensitivity.fits.fz files """ allowed_gamma_off = ["off0.0deg", "off0.4deg"] if gamma_offset not in allowed_gamma_off: log.info( f'Please select a valid gamma_offset to compute the IRFS: {" or ".join(allowed_gamma_off)}' ) exit(-1) output_sensitivity_dir = os.path.join( dl2_dir.replace("/DL2/", "/IRF/").replace("/{}/", "/"), gamma_offset ) os.makedirs(output_sensitivity_dir, exist_ok=True) return output_sensitivity_dir def sensitivity_io( dl2_directory, log_from_dl1_dl2, gamma_offset="off0.0deg", prod_id=None ): """ Manages the i/o arguments and parameters to be passed to the batch_dl2_to_sensitivity function. Parameters ---------- dl2_directory: str Base path to DL2 directory log_from_dl1_dl2: dict Dictionary with particle abs path created in previous stages #TODO to be changed by a glob.glob ? gamma_offset: str String to indicate the gamma offset if gamma_point_like == True. Either 'off0.0deg' or 'off0.4deg' prod_id: str String with prod_id prefix to complete 'file-naming' Returns ------- gamma_file: str Absolute path to DL2 gamma test file proton_file: str Absolute path to DL2 proton test file electron_file: str Absolute path to DL2 electron test file output_directory: str Absolute path with output directory output_sensitivity_filename: str Output filename """ output_directory = compose_sensitivity_outdir(dl2_directory, gamma_offset) # Find paths to DL2 files proton_file = log_from_dl1_dl2["proton"]["dl2_test_path"] electron_file = log_from_dl1_dl2["electron"]["dl2_test_path"] if gamma_offset == "off0.0deg": gamma_file = log_from_dl1_dl2["gamma_off0.0deg"]["dl2_test_path"] else: # gamma_offset == 'off0.4deg'. No other case possible, it has been checked in 'compose_sensitivity_outdir' gamma_file = log_from_dl1_dl2["gamma_off0.4deg"]["dl2_test_path"] # Create output filenames if prod_id is None: output_sensitivity_filename = os.path.join( output_directory, "sensitivity.fits.gz" ) else: output_sensitivity_filename = os.path.join( output_directory, f'{prod_id.replace(".", "")}_gamma_{gamma_offset.replace(".", "")}_sensitivity.fits.gz', ) return ( gamma_file, proton_file, electron_file, output_directory, output_sensitivity_filename, ) def dl2_to_sensitivity( dl2_dir, log_from_dl1_dl2, gamma_offset="off0.0deg", prod_id=None, source_env="", wait_jobs_dl1_dl2="", ): """ Function to run the `script_dl2_to_sensitivity` for the gamma (and the different gamma offsets) and gamma-diffuse particles. Creates the sensitivity *.fits.gz files and the corresponding sensitivity curve plot. Parameters ---------- dl2_dir: str Base path to DL2 directory log_from_dl1_dl2: dict Dictionary with particle abs path created in previous stages #TODO to be changed by a glob.glob ? gamma_offset: str String to indicate the gamma offset if gamma_point_like == True. Either 'off0.0deg' or 'off0.4deg' prod_id: str String with prod_id prefix to complete 'filenaming' source_env: str Source environment (source .bashrc + conda activate env) to be used in the slurm cmd wait_jobs_dl1_dl2: str Comma-separated string with the jobs (dependency) to wait for before launching the cmd Returns ------- log_dl2_to_sensitivity: dict Dictionary with job_id-slurm command key-value pair used for logging job_id: str String with job_ids batched by the dl2_to_sensitivity script """ log_dl2_to_sensitivity = {} jobids_dl2_to_sensitivity = [] job_name = gamma_offset.replace(".", "").replace("off", "").replace("deg", "") g_file, p_file, e_file, out_dir, out_file = sensitivity_io( dl2_dir, log_from_dl1_dl2, gamma_offset, prod_id ) # TODO Move the base commands into scripts so that we can use subprocess properly(makes splitting the string easier) # create sensitivity files base_cmd_sens = f"lstmcpipe_dl2_to_sensitivity -g {g_file} -p {p_file} -e {e_file} -o {out_file}" jobo_sens = os.path.join(out_dir, f"job_dl2_to_sensitivity_gamma_{gamma_offset}.o") jobe_sens = os.path.join(out_dir, f"job_dl2_to_sensitivity_gamma_{gamma_offset}.e") cmd_sens = ( f"sbatch --parsable -p short --dependency=afterok:{wait_jobs_dl1_dl2} -e {jobe_sens} -o {jobo_sens} " f' -J {job_name}_sensitivity --wrap="{source_env} {base_cmd_sens}"' ) job_id_dl2_sens = os.popen(cmd_sens).read().strip("\n") log_dl2_to_sensitivity[job_id_dl2_sens] = cmd_sens jobids_dl2_to_sensitivity.append(job_id_dl2_sens) # Create plot from sensitivity files base_cmd_plot = ( f'lstmcpipe_plot_irfs -f {out_file} -o {out_file.replace(".fits.gz", ".png")}' ) jobe_plot = os.path.join(out_dir, f"job_plot_sensitivity_gamma_{gamma_offset}.e") jobo_plot = os.path.join(out_dir, f"job_plot_sensitivity_gamma_{gamma_offset}.o") cmd_plot = ( f"sbatch --parsable -p short --dependency=afterok:{job_id_dl2_sens} -e {jobe_plot} -o {jobo_plot}" f' -J {job_name}_sens_plot --wrap="export MPLBACKEND=Agg; {source_env} {base_cmd_plot}"' ) job_id_plot_sens = os.popen(cmd_plot).read().strip("\n") log_dl2_to_sensitivity[job_id_plot_sens] = cmd_plot jobids_dl2_to_sensitivity.append(job_id_plot_sens) return log_dl2_to_sensitivity, ",".join(jobids_dl2_to_sensitivity)
lstmcpipe/stages/mc_dl2_to_sensitivity.py
import os import logging import time log = logging.getLogger(__name__) def batch_dl2_to_sensitivity( dl2_directory, offset_gammas, job_ids_from_dl1_dl2, log_from_dl1_dl2, source_env, prod_id, ): """ Batches the dl2_to_sensitivity stage (`stages.script_dl2_to_sensitivity` based in the pyIRF iib) once the dl1_to_dl2 stage had finished. Parameters ---------- dl2_directory: str Base path to DL2 directory to be formatted with particle type offset_gammas: list list off gamma offsets job_ids_from_dl1_dl2: str Comma-separated string with the job ids from the dl1_to_dl2 stage to be used as a slurm dependency to schedule the current stage log_from_dl1_dl2: dict Dictionary from dl1_to_dl2 stage with particle path information source_env: str source environment to select the desired conda environment (source .bashrc + conda activate $ENV) prod_id: str String with prod_id prefix to complete 'file-naming' Returns ------- log_dl2_to_sensitivity: dict Dictionary with job_id-slurm command key-value pair used for logging jobid_for_check: str Comma-separated jobids batched in the current stage debug_log: dict Dictionary with the job-id and stage explanation to be stored in the debug file """ log.info("==== START {} ====".format("batch mc_dl2_to_sensitivity")) time.sleep(1) debug_log = {} jobid_for_check = [] log_dl2_to_sensitivity = {} for off in offset_gammas: job_logs, jobid = dl2_to_sensitivity( dl2_directory, log_from_dl1_dl2, gamma_offset=off, prod_id=prod_id, source_env=source_env, wait_jobs_dl1_dl2=job_ids_from_dl1_dl2, ) jobid_for_check.append(jobid) log_dl2_to_sensitivity[f"gamma_{off}"] = job_logs debug_log[jobid] = ( f"Gamma_{off} job_ids from the dl2_to_sensitivity stage and the plot_irfs script that " f"depends on the dl1_to_dl2 stage job_ids; {job_ids_from_dl1_dl2}" ) log.info("Jobs for gamma offset {} have been submitted".format(off)) log.debug( f"Gamma_{off} job_ids from the dl2_to_sensitivity stage and the plot_irfs script that " f"depends on the dl1_to_dl2 stage job_ids; {job_ids_from_dl1_dl2}" ) jobid_for_check = ",".join(jobid_for_check) log.info("==== END {} ====".format("batch mc_dl2_to_sensitivity")) return log_dl2_to_sensitivity, jobid_for_check, debug_log def compose_sensitivity_outdir(dl2_dir, gamma_offset): """ Compute the sensitivity output directory depending on the type of gamma file Parameters ---------- dl2_dir: str Base path to DL2 directory gamma_offset: str String to indicate the gamma offset. Either 'off0.0deg' or 'off0.4deg' Returns ------- output_sensitivity_dir: str Absolute path in where to store the sensitivity.fits.fz files """ allowed_gamma_off = ["off0.0deg", "off0.4deg"] if gamma_offset not in allowed_gamma_off: log.info( f'Please select a valid gamma_offset to compute the IRFS: {" or ".join(allowed_gamma_off)}' ) exit(-1) output_sensitivity_dir = os.path.join( dl2_dir.replace("/DL2/", "/IRF/").replace("/{}/", "/"), gamma_offset ) os.makedirs(output_sensitivity_dir, exist_ok=True) return output_sensitivity_dir def sensitivity_io( dl2_directory, log_from_dl1_dl2, gamma_offset="off0.0deg", prod_id=None ): """ Manages the i/o arguments and parameters to be passed to the batch_dl2_to_sensitivity function. Parameters ---------- dl2_directory: str Base path to DL2 directory log_from_dl1_dl2: dict Dictionary with particle abs path created in previous stages #TODO to be changed by a glob.glob ? gamma_offset: str String to indicate the gamma offset if gamma_point_like == True. Either 'off0.0deg' or 'off0.4deg' prod_id: str String with prod_id prefix to complete 'file-naming' Returns ------- gamma_file: str Absolute path to DL2 gamma test file proton_file: str Absolute path to DL2 proton test file electron_file: str Absolute path to DL2 electron test file output_directory: str Absolute path with output directory output_sensitivity_filename: str Output filename """ output_directory = compose_sensitivity_outdir(dl2_directory, gamma_offset) # Find paths to DL2 files proton_file = log_from_dl1_dl2["proton"]["dl2_test_path"] electron_file = log_from_dl1_dl2["electron"]["dl2_test_path"] if gamma_offset == "off0.0deg": gamma_file = log_from_dl1_dl2["gamma_off0.0deg"]["dl2_test_path"] else: # gamma_offset == 'off0.4deg'. No other case possible, it has been checked in 'compose_sensitivity_outdir' gamma_file = log_from_dl1_dl2["gamma_off0.4deg"]["dl2_test_path"] # Create output filenames if prod_id is None: output_sensitivity_filename = os.path.join( output_directory, "sensitivity.fits.gz" ) else: output_sensitivity_filename = os.path.join( output_directory, f'{prod_id.replace(".", "")}_gamma_{gamma_offset.replace(".", "")}_sensitivity.fits.gz', ) return ( gamma_file, proton_file, electron_file, output_directory, output_sensitivity_filename, ) def dl2_to_sensitivity( dl2_dir, log_from_dl1_dl2, gamma_offset="off0.0deg", prod_id=None, source_env="", wait_jobs_dl1_dl2="", ): """ Function to run the `script_dl2_to_sensitivity` for the gamma (and the different gamma offsets) and gamma-diffuse particles. Creates the sensitivity *.fits.gz files and the corresponding sensitivity curve plot. Parameters ---------- dl2_dir: str Base path to DL2 directory log_from_dl1_dl2: dict Dictionary with particle abs path created in previous stages #TODO to be changed by a glob.glob ? gamma_offset: str String to indicate the gamma offset if gamma_point_like == True. Either 'off0.0deg' or 'off0.4deg' prod_id: str String with prod_id prefix to complete 'filenaming' source_env: str Source environment (source .bashrc + conda activate env) to be used in the slurm cmd wait_jobs_dl1_dl2: str Comma-separated string with the jobs (dependency) to wait for before launching the cmd Returns ------- log_dl2_to_sensitivity: dict Dictionary with job_id-slurm command key-value pair used for logging job_id: str String with job_ids batched by the dl2_to_sensitivity script """ log_dl2_to_sensitivity = {} jobids_dl2_to_sensitivity = [] job_name = gamma_offset.replace(".", "").replace("off", "").replace("deg", "") g_file, p_file, e_file, out_dir, out_file = sensitivity_io( dl2_dir, log_from_dl1_dl2, gamma_offset, prod_id ) # TODO Move the base commands into scripts so that we can use subprocess properly(makes splitting the string easier) # create sensitivity files base_cmd_sens = f"lstmcpipe_dl2_to_sensitivity -g {g_file} -p {p_file} -e {e_file} -o {out_file}" jobo_sens = os.path.join(out_dir, f"job_dl2_to_sensitivity_gamma_{gamma_offset}.o") jobe_sens = os.path.join(out_dir, f"job_dl2_to_sensitivity_gamma_{gamma_offset}.e") cmd_sens = ( f"sbatch --parsable -p short --dependency=afterok:{wait_jobs_dl1_dl2} -e {jobe_sens} -o {jobo_sens} " f' -J {job_name}_sensitivity --wrap="{source_env} {base_cmd_sens}"' ) job_id_dl2_sens = os.popen(cmd_sens).read().strip("\n") log_dl2_to_sensitivity[job_id_dl2_sens] = cmd_sens jobids_dl2_to_sensitivity.append(job_id_dl2_sens) # Create plot from sensitivity files base_cmd_plot = ( f'lstmcpipe_plot_irfs -f {out_file} -o {out_file.replace(".fits.gz", ".png")}' ) jobe_plot = os.path.join(out_dir, f"job_plot_sensitivity_gamma_{gamma_offset}.e") jobo_plot = os.path.join(out_dir, f"job_plot_sensitivity_gamma_{gamma_offset}.o") cmd_plot = ( f"sbatch --parsable -p short --dependency=afterok:{job_id_dl2_sens} -e {jobe_plot} -o {jobo_plot}" f' -J {job_name}_sens_plot --wrap="export MPLBACKEND=Agg; {source_env} {base_cmd_plot}"' ) job_id_plot_sens = os.popen(cmd_plot).read().strip("\n") log_dl2_to_sensitivity[job_id_plot_sens] = cmd_plot jobids_dl2_to_sensitivity.append(job_id_plot_sens) return log_dl2_to_sensitivity, ",".join(jobids_dl2_to_sensitivity)
0.781497
0.311178
import requests class Behaviour: """ This class offers methods to manage a behaviours ``from datavillage_sdk.user.behaviour import Behaviour`` ``behaviour = Behaviour()`` """ def __init__(self): super().__init__() def create_behaviour( self, user, consent_receipt_processing, behaviour, user_access_token ): """Create a new behaviour :param user: unique user identifier :type user: string :param consent_receipt_processing: consent receipt ID :type consent_receipt_processing: string :param behaviour: base64 encoded JSON-LD :type behaviour: base64 :param user_access_token: user access token :type user_access_token: string :return: behaviour instance :rtype: object """ token = "Bearer" + user_access_token url = ( "https://api.datavillage.me/behaviors/" + user + "/" + consent_receipt_processing ) payload = behaviour headers = {"Content-Type": "application/json", "Authorization": token} response = requests.request("POST", url, headers=headers, data=payload) return response def get_behaviour(self, user_id, consent_receipt, behaviour_id): """Get Behaviour :param user_id: unique user identifier :type user_id: string :param consent_receipt: consent receipt ID :type consent_receipt: string :param behaviour_id: behavior_id :type behaviour_id: string :return: behaviour instance :rtype: object """ url = "https://api.datavillage.me/behaviors/{{user_id}}/{{consent_receipt}}/{{behavior_id}}" payload = {} headers = {"Content-Type": "application/json"} response = requests.request("GET", url, headers=headers, data=payload) return response def get_all_behaviour(self, user_id, consent_receipt_processing): """Get Behaviour :param user_id: unique user identifier :type user_id: string :param consent_receipt_processing: consent receipt :type consent_receipt: string :return: behaviour instance :rtype: object """ url = "https://api.datavillage.me/behaviors/{{user_id}}/{{consent_receipt_processing}}" payload = {} headers = {"Content-Type": "application/json"} response = requests.request("GET", url, headers=headers, data=payload) return response
datavillage_sdk/user/behaviour.py
import requests class Behaviour: """ This class offers methods to manage a behaviours ``from datavillage_sdk.user.behaviour import Behaviour`` ``behaviour = Behaviour()`` """ def __init__(self): super().__init__() def create_behaviour( self, user, consent_receipt_processing, behaviour, user_access_token ): """Create a new behaviour :param user: unique user identifier :type user: string :param consent_receipt_processing: consent receipt ID :type consent_receipt_processing: string :param behaviour: base64 encoded JSON-LD :type behaviour: base64 :param user_access_token: user access token :type user_access_token: string :return: behaviour instance :rtype: object """ token = "Bearer" + user_access_token url = ( "https://api.datavillage.me/behaviors/" + user + "/" + consent_receipt_processing ) payload = behaviour headers = {"Content-Type": "application/json", "Authorization": token} response = requests.request("POST", url, headers=headers, data=payload) return response def get_behaviour(self, user_id, consent_receipt, behaviour_id): """Get Behaviour :param user_id: unique user identifier :type user_id: string :param consent_receipt: consent receipt ID :type consent_receipt: string :param behaviour_id: behavior_id :type behaviour_id: string :return: behaviour instance :rtype: object """ url = "https://api.datavillage.me/behaviors/{{user_id}}/{{consent_receipt}}/{{behavior_id}}" payload = {} headers = {"Content-Type": "application/json"} response = requests.request("GET", url, headers=headers, data=payload) return response def get_all_behaviour(self, user_id, consent_receipt_processing): """Get Behaviour :param user_id: unique user identifier :type user_id: string :param consent_receipt_processing: consent receipt :type consent_receipt: string :return: behaviour instance :rtype: object """ url = "https://api.datavillage.me/behaviors/{{user_id}}/{{consent_receipt_processing}}" payload = {} headers = {"Content-Type": "application/json"} response = requests.request("GET", url, headers=headers, data=payload) return response
0.799794
0.333802
import json import string import sys class Definition(object): __tsdoc_weight__ = -100 # Classes DEF_UNKNOWN = -1 DEF_DESCRIPTION = 0 DEF_VARIABLE = 1 DEF_CONSTANT = 2 DEF_FUNCTION = 3 DEF_TYPE = 4 def_class = DEF_UNKNOWN def __init__(self): self.code = '' self.name = '' self.tags = [] self.source = '' self.lineno = -1 def set_source(self, source, lineno): self.source = source self.lineno = lineno def set_name(self, name): if isinstance(name, str): name = name.strip() self.name = name def set_code(self, code): self.code = code @staticmethod def _serialize_object(value): if isinstance(value, list): return map(Definition._serialize_object, value) elif isinstance(value, Definition): return value.serialize(is_root = False) return value def serialize(self, is_root = True): klass = self.__class__ object = {'class': klass.__name__, 'name': self.name} if is_root: object.update({'code': self.code, 'source': self.source, 'lineno': self.lineno}) for field in klass.__tsdoc_fields__: value = getattr(self, field) object[field] = Definition._serialize_object(value) return object def post_deserialize(self): pass class DocText(Definition): def_class = Definition.DEF_DESCRIPTION class Param(Definition): __tsdoc_fields__ = ['type', 'name', 'description'] ARGUMENT = 0 MEMBER = 1 VALUE = 2 def __init__(self, type, name, description): Definition.__init__(self) self.type = type self.name = name self.description = description class Note(Definition): __tsdoc_fields__ = ['type', 'note'] TEXT = 0 NOTE = 1 RETURN = 2 REFERENCE = 3 def __init__(self, type, note): Definition.__init__(self) self.type = type self.note = note __tsdoc_fields__ = ['params', 'notes'] __tsdoc_weight__ = 0 def __init__(self): Definition.__init__(self) self.module = None self.params = [] self.notes = [] def add_param(self, type, name, description): self.params.append(DocText.Param(type, name, description)) def get_params(self, type): return [param for param in self.params if param.type == type] def add_note(self, type, note): self.notes.append(DocText.Note(type, note)) def get_notes(self, type): return [note for note in self.notes if note.type == type] def set_module(self, module): self.module = module class TypeVar(Definition): __tsdoc_fields__ = ['types', 'tv_class', 'value'] __tsdoc_weight__ = 10 VARIABLE = 0 ARGUMENT = 1 TYPEDEF = 2 def __init__(self): Definition.__init__(self) self.types = [] self.value = None self.tv_class = TypeVar.VARIABLE def add_type(self, name): self.types.append(name) def set_value(self, value): self.value = value def set_class(self, tv_class): self.tv_class = tv_class if tv_class == TypeVar.TYPEDEF: self.def_class = Definition.DEF_TYPE else: self.def_class = Definition.DEF_VARIABLE def post_deserialize(self): return self.set_class(self.tv_class) class Function(Definition): __tsdoc_fields__ = ['retvalue', 'args', 'specifiers'] __tsdoc_weight__ = 100 def_class = Definition.DEF_FUNCTION def __init__(self): Definition.__init__(self) self.retvalue = [] self.args = [] self.specifiers = [] def add_arg(self, arg): self.args.append(arg) def add_retvalue(self, retvalue): self.retvalue.append(retvalue) def set_specifiers(self, specifiers): self.specifiers = specifiers def add_type(self, type): self.types.append(type) class Macro(Definition): __tsdoc_fields__ = [] __tsdoc_weight__ = 100 def_class = Definition.DEF_FUNCTION class Enumeration(Definition): __tsdoc_fields__ = ['values', 'aliases'] __tsdoc_weight__ = 50 def_class = Definition.DEF_TYPE def __init__(self): Definition.__init__(self) self.values = [] self.aliases = [] def add_value(self, value): self.values.append(value) def set_aliases(self, aliases): self.aliases = aliases class ComplexType(Definition): __tsdoc_fields__ = ['members', 'aliases', 'type'] __tsdoc_weight__ = 50 STRUCT = 1 UNION = 2 def_class = Definition.DEF_TYPE def __init__(self): Definition.__init__(self) self.type = 0 self.members = [] self.aliases = [] def set_type(self, type): self.type = type def add_member(self, member): self.members.append(member) def set_aliases(self, aliases): self.aliases = aliases class Value(Definition): __tsdoc_fields__ = ['value'] __tsdoc_weight__ = 20 def_class = Definition.DEF_CONSTANT def __init__(self): Definition.__init__(self) self.value = None def set_value(self, value): self.value = value _def_classes_root = [DocText, TypeVar, Function, Macro, Enumeration, ComplexType, Value] _def_classes = dict((klass.__name__, klass) for klass in _def_classes_root) _def_classes['Param'] = DocText.Param _def_classes['Note'] = DocText.Note class DefinitionGroup: def __init__(self, defs): self.defs = defs def __iter__(self): return iter(self.defs) def get_names(self): names = [] for defobj in self.defs: name = defobj.name if isinstance(name, list): name = ' '.join(name) if name: names.append(name) return set(names) def header(self): for defobj in self.defs: if isinstance(defobj, DocText) and defobj.name: return defobj.name return ', '.join(self.get_names()) def get_weight(self): return max(defobj.__tsdoc_weight__ for defobj in self.defs) def find_leaders(self): weight = -1000 leaders = [] for defobj in self.defs: if defobj.__tsdoc_weight__ > weight: weight = defobj.__tsdoc_weight__ leaders = [defobj] elif defobj.__tsdoc_weight__ == weight: leaders.append(defobj) return leaders def merge(self, other): for defobj in other.defs: if isinstance(defobj, DocText): self.defs.insert(0, defobj) def split(self, names): defs = self.defs[:] new_defs = [] for defobj in self.defs: if defobj.name in names: self.defs.remove(defobj) new_defs.append(defobj) return DefinitionGroup(new_defs) def serialize(self): def_list = [] for defobj in self.defs: def_list.append(defobj.serialize()) return def_list def have_doctext(self): return any(isinstance(defobj, DocText) for defobj in self.defs) class TSDoc: def __init__(self, module, groups, sources = [], header = None, docspace = ''): self.module = module self.groups = groups self.sources = sources self.header = header self.docspace = docspace def find_header(self): self.header = self.module for group in self.groups: for defobj in group.defs: if not isinstance(defobj, DocText): continue if defobj.module is not None: self.header = defobj.module return def set_docspace(self, docspace): self.docspace = docspace def set_sources(self, sources): self.sources = sources def serialize(self): groups = [group.serialize() for group in self.groups] node = {'module': self.module, 'docspace': self.docspace, 'header': self.header, 'sources': self.sources, 'groups': groups } return node @staticmethod def _deserialize_object(obj): if isinstance(obj, list): return map(TSDoc._deserialize_object, obj) elif isinstance(obj, dict): klass_name = obj['class'] klass = _def_classes[klass_name] defobj = klass.__new__(klass) fields = klass.__tsdoc_fields__ + ['name'] opt_fields = ['code', 'source', 'line'] for field in fields + opt_fields: if field not in obj and field in opt_fields: continue obj1 = obj[field] obj1 = TSDoc._deserialize_object(obj1) setattr(defobj, field, obj1) defobj.post_deserialize() return defobj return obj @staticmethod def deserialize(uobj): obj = dict([(str(k), v) for k, v in uobj.items()]) tsdoc = TSDoc(**obj) groups = [] for groupdecl in tsdoc.groups: defs = [] for defdecl in groupdecl: defobj = TSDoc._deserialize_object(defdecl) defs.append(defobj) groups.append(DefinitionGroup(defs)) tsdoc.groups = groups return tsdoc
tsdoc/tsdoc/__init__.py
import json import string import sys class Definition(object): __tsdoc_weight__ = -100 # Classes DEF_UNKNOWN = -1 DEF_DESCRIPTION = 0 DEF_VARIABLE = 1 DEF_CONSTANT = 2 DEF_FUNCTION = 3 DEF_TYPE = 4 def_class = DEF_UNKNOWN def __init__(self): self.code = '' self.name = '' self.tags = [] self.source = '' self.lineno = -1 def set_source(self, source, lineno): self.source = source self.lineno = lineno def set_name(self, name): if isinstance(name, str): name = name.strip() self.name = name def set_code(self, code): self.code = code @staticmethod def _serialize_object(value): if isinstance(value, list): return map(Definition._serialize_object, value) elif isinstance(value, Definition): return value.serialize(is_root = False) return value def serialize(self, is_root = True): klass = self.__class__ object = {'class': klass.__name__, 'name': self.name} if is_root: object.update({'code': self.code, 'source': self.source, 'lineno': self.lineno}) for field in klass.__tsdoc_fields__: value = getattr(self, field) object[field] = Definition._serialize_object(value) return object def post_deserialize(self): pass class DocText(Definition): def_class = Definition.DEF_DESCRIPTION class Param(Definition): __tsdoc_fields__ = ['type', 'name', 'description'] ARGUMENT = 0 MEMBER = 1 VALUE = 2 def __init__(self, type, name, description): Definition.__init__(self) self.type = type self.name = name self.description = description class Note(Definition): __tsdoc_fields__ = ['type', 'note'] TEXT = 0 NOTE = 1 RETURN = 2 REFERENCE = 3 def __init__(self, type, note): Definition.__init__(self) self.type = type self.note = note __tsdoc_fields__ = ['params', 'notes'] __tsdoc_weight__ = 0 def __init__(self): Definition.__init__(self) self.module = None self.params = [] self.notes = [] def add_param(self, type, name, description): self.params.append(DocText.Param(type, name, description)) def get_params(self, type): return [param for param in self.params if param.type == type] def add_note(self, type, note): self.notes.append(DocText.Note(type, note)) def get_notes(self, type): return [note for note in self.notes if note.type == type] def set_module(self, module): self.module = module class TypeVar(Definition): __tsdoc_fields__ = ['types', 'tv_class', 'value'] __tsdoc_weight__ = 10 VARIABLE = 0 ARGUMENT = 1 TYPEDEF = 2 def __init__(self): Definition.__init__(self) self.types = [] self.value = None self.tv_class = TypeVar.VARIABLE def add_type(self, name): self.types.append(name) def set_value(self, value): self.value = value def set_class(self, tv_class): self.tv_class = tv_class if tv_class == TypeVar.TYPEDEF: self.def_class = Definition.DEF_TYPE else: self.def_class = Definition.DEF_VARIABLE def post_deserialize(self): return self.set_class(self.tv_class) class Function(Definition): __tsdoc_fields__ = ['retvalue', 'args', 'specifiers'] __tsdoc_weight__ = 100 def_class = Definition.DEF_FUNCTION def __init__(self): Definition.__init__(self) self.retvalue = [] self.args = [] self.specifiers = [] def add_arg(self, arg): self.args.append(arg) def add_retvalue(self, retvalue): self.retvalue.append(retvalue) def set_specifiers(self, specifiers): self.specifiers = specifiers def add_type(self, type): self.types.append(type) class Macro(Definition): __tsdoc_fields__ = [] __tsdoc_weight__ = 100 def_class = Definition.DEF_FUNCTION class Enumeration(Definition): __tsdoc_fields__ = ['values', 'aliases'] __tsdoc_weight__ = 50 def_class = Definition.DEF_TYPE def __init__(self): Definition.__init__(self) self.values = [] self.aliases = [] def add_value(self, value): self.values.append(value) def set_aliases(self, aliases): self.aliases = aliases class ComplexType(Definition): __tsdoc_fields__ = ['members', 'aliases', 'type'] __tsdoc_weight__ = 50 STRUCT = 1 UNION = 2 def_class = Definition.DEF_TYPE def __init__(self): Definition.__init__(self) self.type = 0 self.members = [] self.aliases = [] def set_type(self, type): self.type = type def add_member(self, member): self.members.append(member) def set_aliases(self, aliases): self.aliases = aliases class Value(Definition): __tsdoc_fields__ = ['value'] __tsdoc_weight__ = 20 def_class = Definition.DEF_CONSTANT def __init__(self): Definition.__init__(self) self.value = None def set_value(self, value): self.value = value _def_classes_root = [DocText, TypeVar, Function, Macro, Enumeration, ComplexType, Value] _def_classes = dict((klass.__name__, klass) for klass in _def_classes_root) _def_classes['Param'] = DocText.Param _def_classes['Note'] = DocText.Note class DefinitionGroup: def __init__(self, defs): self.defs = defs def __iter__(self): return iter(self.defs) def get_names(self): names = [] for defobj in self.defs: name = defobj.name if isinstance(name, list): name = ' '.join(name) if name: names.append(name) return set(names) def header(self): for defobj in self.defs: if isinstance(defobj, DocText) and defobj.name: return defobj.name return ', '.join(self.get_names()) def get_weight(self): return max(defobj.__tsdoc_weight__ for defobj in self.defs) def find_leaders(self): weight = -1000 leaders = [] for defobj in self.defs: if defobj.__tsdoc_weight__ > weight: weight = defobj.__tsdoc_weight__ leaders = [defobj] elif defobj.__tsdoc_weight__ == weight: leaders.append(defobj) return leaders def merge(self, other): for defobj in other.defs: if isinstance(defobj, DocText): self.defs.insert(0, defobj) def split(self, names): defs = self.defs[:] new_defs = [] for defobj in self.defs: if defobj.name in names: self.defs.remove(defobj) new_defs.append(defobj) return DefinitionGroup(new_defs) def serialize(self): def_list = [] for defobj in self.defs: def_list.append(defobj.serialize()) return def_list def have_doctext(self): return any(isinstance(defobj, DocText) for defobj in self.defs) class TSDoc: def __init__(self, module, groups, sources = [], header = None, docspace = ''): self.module = module self.groups = groups self.sources = sources self.header = header self.docspace = docspace def find_header(self): self.header = self.module for group in self.groups: for defobj in group.defs: if not isinstance(defobj, DocText): continue if defobj.module is not None: self.header = defobj.module return def set_docspace(self, docspace): self.docspace = docspace def set_sources(self, sources): self.sources = sources def serialize(self): groups = [group.serialize() for group in self.groups] node = {'module': self.module, 'docspace': self.docspace, 'header': self.header, 'sources': self.sources, 'groups': groups } return node @staticmethod def _deserialize_object(obj): if isinstance(obj, list): return map(TSDoc._deserialize_object, obj) elif isinstance(obj, dict): klass_name = obj['class'] klass = _def_classes[klass_name] defobj = klass.__new__(klass) fields = klass.__tsdoc_fields__ + ['name'] opt_fields = ['code', 'source', 'line'] for field in fields + opt_fields: if field not in obj and field in opt_fields: continue obj1 = obj[field] obj1 = TSDoc._deserialize_object(obj1) setattr(defobj, field, obj1) defobj.post_deserialize() return defobj return obj @staticmethod def deserialize(uobj): obj = dict([(str(k), v) for k, v in uobj.items()]) tsdoc = TSDoc(**obj) groups = [] for groupdecl in tsdoc.groups: defs = [] for defdecl in groupdecl: defobj = TSDoc._deserialize_object(defdecl) defs.append(defobj) groups.append(DefinitionGroup(defs)) tsdoc.groups = groups return tsdoc
0.301362
0.076064
from string import Template from PyPDF2 import PdfFileReader, PdfFileWriter def __reorganization( source_path: str, target_path: str, pages=list[int], ): """ 重组 PDF 的 IO 操作函数, 将 pages 中的所有页面数(合法) 拆分为一个新的PDF. Args: source_path (str): 源文件路径 target_path (str): 目标文件路径 pages ([type], optional): 需要的pages. Defaults to list[int]. """ target_pdf = PdfFileWriter() with open(source_path, "rb") as source_file: source_pdf = PdfFileReader(source_file) for page in pages: if 0 <= page < source_pdf.getNumPages(): target_pdf.addPage(source_pdf.getPage(page)) with open(target_path, "wb") as target_file: target_pdf.write(target_file) def split_step(start, end, step): for i in range(start, end, step): yield list(range(i, i + step)) def split_pieces(start, end, piece): total = end - start step = total // piece if total > piece else 1 for i in range(start, end, step): yield list(range(i, i + step)) def split_mark_points(start, end, points): points = sorted(list(set(points) | {end} - {start})) idx = start for point in points: yield list(range(idx, point)) idx = point def split_pdf( source_path: str, target_path: str = None, diff_name: Template = Template("${path}_part-${num}"), start: int = 0, end: int = None, mod: str = "step", arg=None, ): """ split_pdf 拆分PDF. 有三种拆分方式: 1. 一共分成几块. 2. 以几页一组. 3. 以特定的几组点分割数组. Args: source_path (str): 源文件路径 target_path (str, optional): 目标文件路径. Defaults to None. diff_name (Template, optional): part 后缀模版. Defaults to Template("_part-"). start (int, optional): 开始页面. Defaults to 0. end (int, optional): 结束页面. Defaults to None. mod (str, optional): 拆分模式. Defaults to "piece". Raises: ValueError: [description] """ if end is None: with open(source_path, "rb") as source_file: end = PdfFileReader(source_file).getNumPages() if target_path is None: target_path = ".".join(source_path.split(".")[:-1]) if mod == "piece": if arg is None: arg = 4 gen = split_pieces(start, end, arg) elif mod == "points": gen = split_mark_points(start, end, arg) elif mod == "step": if arg is None: arg = 20 gen = split_step(start, end, arg) else: raise ValueError("Unknown mod for split PDF") for part, pages in enumerate(gen): __reorganization( source_path=source_path, target_path=diff_name.substitute(path=target_path, num=part) + ".pdf", pages=pages, ) if __name__ == "__main__": split_pdf( source_path="/Users/rs/Downloads/12-hypothesis-Practical Statistics for Field Biology_wrapper(1).pdf", target_path=None, start=0, end=None, mod="step", arg=1, )
tools/pdf/split_pdf.py
from string import Template from PyPDF2 import PdfFileReader, PdfFileWriter def __reorganization( source_path: str, target_path: str, pages=list[int], ): """ 重组 PDF 的 IO 操作函数, 将 pages 中的所有页面数(合法) 拆分为一个新的PDF. Args: source_path (str): 源文件路径 target_path (str): 目标文件路径 pages ([type], optional): 需要的pages. Defaults to list[int]. """ target_pdf = PdfFileWriter() with open(source_path, "rb") as source_file: source_pdf = PdfFileReader(source_file) for page in pages: if 0 <= page < source_pdf.getNumPages(): target_pdf.addPage(source_pdf.getPage(page)) with open(target_path, "wb") as target_file: target_pdf.write(target_file) def split_step(start, end, step): for i in range(start, end, step): yield list(range(i, i + step)) def split_pieces(start, end, piece): total = end - start step = total // piece if total > piece else 1 for i in range(start, end, step): yield list(range(i, i + step)) def split_mark_points(start, end, points): points = sorted(list(set(points) | {end} - {start})) idx = start for point in points: yield list(range(idx, point)) idx = point def split_pdf( source_path: str, target_path: str = None, diff_name: Template = Template("${path}_part-${num}"), start: int = 0, end: int = None, mod: str = "step", arg=None, ): """ split_pdf 拆分PDF. 有三种拆分方式: 1. 一共分成几块. 2. 以几页一组. 3. 以特定的几组点分割数组. Args: source_path (str): 源文件路径 target_path (str, optional): 目标文件路径. Defaults to None. diff_name (Template, optional): part 后缀模版. Defaults to Template("_part-"). start (int, optional): 开始页面. Defaults to 0. end (int, optional): 结束页面. Defaults to None. mod (str, optional): 拆分模式. Defaults to "piece". Raises: ValueError: [description] """ if end is None: with open(source_path, "rb") as source_file: end = PdfFileReader(source_file).getNumPages() if target_path is None: target_path = ".".join(source_path.split(".")[:-1]) if mod == "piece": if arg is None: arg = 4 gen = split_pieces(start, end, arg) elif mod == "points": gen = split_mark_points(start, end, arg) elif mod == "step": if arg is None: arg = 20 gen = split_step(start, end, arg) else: raise ValueError("Unknown mod for split PDF") for part, pages in enumerate(gen): __reorganization( source_path=source_path, target_path=diff_name.substitute(path=target_path, num=part) + ".pdf", pages=pages, ) if __name__ == "__main__": split_pdf( source_path="/Users/rs/Downloads/12-hypothesis-Practical Statistics for Field Biology_wrapper(1).pdf", target_path=None, start=0, end=None, mod="step", arg=1, )
0.441191
0.182407
def call(self, inputs, states, training=None): # use implementation=1 h_tm1 = states[0] # previous memory dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=3) rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( h_tm1, training, count=3) if self.use_bias: if not self.reset_after: input_bias, recurrent_bias = self.bias, None else: input_bias, recurrent_bias = array_ops.unstack(self.bias) if self.implementation == 1: if 0. < self.dropout < 1.: inputs_z = inputs * dp_mask[0] inputs_r = inputs * dp_mask[1] inputs_h = inputs * dp_mask[2] else: inputs_z = inputs inputs_r = inputs inputs_h = inputs x_z = K.dot(inputs_z, self.kernel[:, :self.units]) x_r = K.dot(inputs_r, self.kernel[:, self.units:self.units * 2]) x_h = K.dot(inputs_h, self.kernel[:, self.units * 2:]) if self.use_bias: x_z = K.bias_add(x_z, input_bias[:self.units]) x_r = K.bias_add(x_r, input_bias[self.units: self.units * 2]) x_h = K.bias_add(x_h, input_bias[self.units * 2:]) if 0. < self.recurrent_dropout < 1.: h_tm1_z = h_tm1 * rec_dp_mask[0] h_tm1_r = h_tm1 * rec_dp_mask[1] h_tm1_h = h_tm1 * rec_dp_mask[2] else: h_tm1_z = h_tm1 h_tm1_r = h_tm1 h_tm1_h = h_tm1 recurrent_z = K.dot(h_tm1_z, self.recurrent_kernel[:, :self.units]) recurrent_r = K.dot(h_tm1_r, self.recurrent_kernel[:, self.units:self.units * 2]) if self.reset_after and self.use_bias: recurrent_z = K.bias_add(recurrent_z, recurrent_bias[:self.units]) recurrent_r = K.bias_add(recurrent_r, recurrent_bias[self.units:self.units * 2]) z = self.recurrent_activation(x_z + recurrent_z) r = self.recurrent_activation(x_r + recurrent_r) # reset gate applied after/before matrix multiplication if self.reset_after: recurrent_h = K.dot(h_tm1_h, self.recurrent_kernel[:, self.units * 2:]) if self.use_bias: recurrent_h = K.bias_add(recurrent_h, recurrent_bias[self.units * 2:]) recurrent_h = r * recurrent_h else: recurrent_h = K.dot(r * h_tm1_h, self.recurrent_kernel[:, self.units * 2:]) hh = self.activation(x_h + recurrent_h) else: if 0. < self.dropout < 1.: inputs = inputs * dp_mask[0] # inputs projected by all gate matrices at once matrix_x = K.dot(inputs, self.kernel) if self.use_bias: # biases: bias_z_i, bias_r_i, bias_h_i matrix_x = K.bias_add(matrix_x, input_bias) x_z, x_r, x_h = array_ops.split(matrix_x, 3, axis=-1) if self.reset_after: # hidden state projected by all gate matrices at once matrix_inner = K.dot(h_tm1, self.recurrent_kernel) if self.use_bias: matrix_inner = K.bias_add(matrix_inner, recurrent_bias) else: # hidden state projected separately for update/reset and new matrix_inner = K.dot(h_tm1, self.recurrent_kernel[:, :2 * self.units]) recurrent_z, recurrent_r, recurrent_h = array_ops.split( matrix_inner, [self.units, self.units, -1], axis=-1) z = self.recurrent_activation(x_z + recurrent_z) r = self.recurrent_activation(x_r + recurrent_r) if self.reset_after: recurrent_h = r * recurrent_h else: recurrent_h = K.dot(r * h_tm1, self.recurrent_kernel[:, 2 * self.units:]) hh = self.activation(x_h + recurrent_h) # previous and candidate state mixed by update gate h = z * h_tm1 + (1 - z) * hh return h, [h]
repo_files/to add/GRU.py
def call(self, inputs, states, training=None): # use implementation=1 h_tm1 = states[0] # previous memory dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=3) rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( h_tm1, training, count=3) if self.use_bias: if not self.reset_after: input_bias, recurrent_bias = self.bias, None else: input_bias, recurrent_bias = array_ops.unstack(self.bias) if self.implementation == 1: if 0. < self.dropout < 1.: inputs_z = inputs * dp_mask[0] inputs_r = inputs * dp_mask[1] inputs_h = inputs * dp_mask[2] else: inputs_z = inputs inputs_r = inputs inputs_h = inputs x_z = K.dot(inputs_z, self.kernel[:, :self.units]) x_r = K.dot(inputs_r, self.kernel[:, self.units:self.units * 2]) x_h = K.dot(inputs_h, self.kernel[:, self.units * 2:]) if self.use_bias: x_z = K.bias_add(x_z, input_bias[:self.units]) x_r = K.bias_add(x_r, input_bias[self.units: self.units * 2]) x_h = K.bias_add(x_h, input_bias[self.units * 2:]) if 0. < self.recurrent_dropout < 1.: h_tm1_z = h_tm1 * rec_dp_mask[0] h_tm1_r = h_tm1 * rec_dp_mask[1] h_tm1_h = h_tm1 * rec_dp_mask[2] else: h_tm1_z = h_tm1 h_tm1_r = h_tm1 h_tm1_h = h_tm1 recurrent_z = K.dot(h_tm1_z, self.recurrent_kernel[:, :self.units]) recurrent_r = K.dot(h_tm1_r, self.recurrent_kernel[:, self.units:self.units * 2]) if self.reset_after and self.use_bias: recurrent_z = K.bias_add(recurrent_z, recurrent_bias[:self.units]) recurrent_r = K.bias_add(recurrent_r, recurrent_bias[self.units:self.units * 2]) z = self.recurrent_activation(x_z + recurrent_z) r = self.recurrent_activation(x_r + recurrent_r) # reset gate applied after/before matrix multiplication if self.reset_after: recurrent_h = K.dot(h_tm1_h, self.recurrent_kernel[:, self.units * 2:]) if self.use_bias: recurrent_h = K.bias_add(recurrent_h, recurrent_bias[self.units * 2:]) recurrent_h = r * recurrent_h else: recurrent_h = K.dot(r * h_tm1_h, self.recurrent_kernel[:, self.units * 2:]) hh = self.activation(x_h + recurrent_h) else: if 0. < self.dropout < 1.: inputs = inputs * dp_mask[0] # inputs projected by all gate matrices at once matrix_x = K.dot(inputs, self.kernel) if self.use_bias: # biases: bias_z_i, bias_r_i, bias_h_i matrix_x = K.bias_add(matrix_x, input_bias) x_z, x_r, x_h = array_ops.split(matrix_x, 3, axis=-1) if self.reset_after: # hidden state projected by all gate matrices at once matrix_inner = K.dot(h_tm1, self.recurrent_kernel) if self.use_bias: matrix_inner = K.bias_add(matrix_inner, recurrent_bias) else: # hidden state projected separately for update/reset and new matrix_inner = K.dot(h_tm1, self.recurrent_kernel[:, :2 * self.units]) recurrent_z, recurrent_r, recurrent_h = array_ops.split( matrix_inner, [self.units, self.units, -1], axis=-1) z = self.recurrent_activation(x_z + recurrent_z) r = self.recurrent_activation(x_r + recurrent_r) if self.reset_after: recurrent_h = r * recurrent_h else: recurrent_h = K.dot(r * h_tm1, self.recurrent_kernel[:, 2 * self.units:]) hh = self.activation(x_h + recurrent_h) # previous and candidate state mixed by update gate h = z * h_tm1 + (1 - z) * hh return h, [h]
0.557845
0.4831
import numpy as np from scipy.optimize import linear_sum_assignment from collections import defaultdict from utils.utils import parse_camera_param def global2pixel(person_coords, camera_id, camera_param_dict): # det : X Y Z world_coord = person_coords / camera_param_dict['discretization_factor'] + camera_param_dict['min_volume'] trans_coord = world_coord - camera_param_dict[camera_id]['Translation'] uvw = np.linalg.inv(camera_param_dict[camera_id]['Rotation']) @ trans_coord.transpose(1, 0) uvw = uvw.transpose(1, 0) pixel_coords = uvw / camera_param_dict[camera_id]['FInv'] / uvw[:, 2:3] + camera_param_dict[camera_id]['C'] return pixel_coords[:, :2] def batch_euc_dist(point1, point2): point1_reshape = point1[:, np.newaxis, :] point2_reshape = point2[np.newaxis, :, :] sub = point1_reshape - point2_reshape dist = np.linalg.norm(sub, ord=2, axis=-1) return dist def batch_cosine_dist(feat1, feat2): assert feat1.shape[1] == feat2.shape[1] feat1 = feat1 / np.linalg.norm(feat1, ord=2, axis=-1, keepdims=True) feat2 = feat2 / np.linalg.norm(feat2, ord=2, axis=-1, keepdims=True) sim_matrix = feat1 @ feat2.T return 1 - sim_matrix def batch_ious(det, gt): det[:, 2:4] += det[:, :2] gt[:, 2:4] += gt[:, :2] det = det[:, np.newaxis, :] gt = gt[np.newaxis, :, :] max_x1 = np.maximum(det[..., 0], gt[..., 0]) min_x2 = np.minimum(det[..., 2], gt[..., 2]) max_y1 = np.maximum(det[..., 1], gt[..., 1]) min_y2 = np.minimum(det[..., 3], gt[..., 3]) i = np.maximum(min_y2 - max_y1, 0) * np.maximum(min_x2 - max_x1, 0) a1 = (det[..., 2] - det[..., 0]) * (det[..., 3] - det[..., 1]) a2 = (gt[..., 3] - gt[..., 1]) * (gt[...,2] - gt[..., 0]) u = a1 + a2 - i return i / u def cos_match(det, res, unmatched_rids, unmatched_cids, cos_th): if len(unmatched_rids) == 0 or len(unmatched_cids) == 0: return np.array([], dtype=int), np.array([], dtype=int) sub_det = det[unmatched_rids, :] sub_res = res[unmatched_cids, :] cosine_dist = batch_cosine_dist(sub_det, sub_res) matched_rids, matched_cids = linear_sum_assignment(cosine_dist) mask = cosine_dist[matched_rids, matched_cids] < cos_th matched_rids = matched_rids[mask] matched_cids = matched_cids[mask] matched_rids = unmatched_rids[matched_rids] matched_cids = unmatched_cids[matched_cids] return matched_rids, matched_cids def pos_match(det, res, unmatched_rids, unmatched_cids, pos_th): if len(unmatched_rids) == 0 or len(unmatched_cids) == 0: return np.array([], dtype=int), np.array([], dtype=int) sub_det = det[unmatched_rids, :] sub_res = res[unmatched_cids, :] euc_dist = batch_euc_dist(sub_det, sub_res) matched_rids, matched_cids = linear_sum_assignment(euc_dist) mask = euc_dist[matched_rids, matched_cids] < pos_th matched_rids = matched_rids[mask] matched_cids = matched_cids[mask] matched_rids = unmatched_rids[matched_rids] matched_cids = unmatched_cids[matched_cids] return matched_rids, matched_cids def track1to2_track(dets, track1_res, camera_id, camera_param_file, cos_th, pos_th, cos_first=True): #track1_res: fid, tid, Y, X, Z #dets: fid, cat, x, y, w, h, score, feat camera_param_dict = parse_camera_param(camera_param_file) data_for_projection = np.concatenate((track1_res[:, 3:4], track1_res[:, 2:3], track1_res[:, 4:5]), axis=1) pixel_coord = global2pixel(data_for_projection, camera_id, camera_param_dict) track1_pixel_res = np.hstack((track1_res[:, :2], pixel_coord))# x, y det_head_point_x = dets[:, 2] + dets[:, 4] / 2 det_head_point_y = dets[:, 3] + dets[:, 5] / 2 det_head_point = np.hstack((det_head_point_x.reshape(-1, 1), det_head_point_y.reshape(-1, 1))) det_head = np.hstack((dets[:, 0:1], det_head_point)) fids = np.unique(track1_pixel_res[:, 0]) res = [] tracks_dict = {} new_tid = 100 for fid in sorted(fids): sub_det_head = det_head[det_head[:, 0] == fid] sub_det = dets[dets[:, 0] == fid] sub_track1_res = track1_res[track1_res[:, 0] == fid] if len(sub_det_head) == 0: continue det_size = len(sub_det) res_size = len(sub_track1_res) det_point = sub_det_head[:, 1:3] track1res = track1_pixel_res[track1_pixel_res[:, 0] == fid] tids = track1res[:, 1] track1res_point = track1res[:, 2:4] unmatched_rids = np.arange(det_size).astype(int) unmatched_cids = np.arange(res_size).astype(int) if cos_first: matched_rids, matched_cids = cos_match(sub_det[:, 7:], sub_track1_res[:, 5:], unmatched_rids, unmatched_cids, cos_th) else: matched_rids, matched_cids = pos_match(det_point, track1res_point, unmatched_rids, unmatched_cids, pos_th) unmatched_rids = set(list(range(det_size))) - set(matched_rids.tolist()) unmatched_rids = np.array(list(unmatched_rids)).astype(int) unmatched_cids = set(list(range(res_size))) - set(matched_cids.tolist()) unmatched_cids = np.array(list(unmatched_cids)).astype(int) if cos_first: matched_rids2, matched_cids2 = pos_match(det_point, track1res_point, unmatched_rids, unmatched_cids, pos_th) else: matched_rids2, matched_cids2 = cos_match(sub_det[:, 7:], sub_track1_res[:, 5:], unmatched_rids, unmatched_cids, cos_th) matched_rids = np.hstack((matched_rids, matched_rids2)) matched_cids = np.hstack((matched_cids, matched_cids2)) matched_tids = tids[matched_cids] det_res = sub_det[matched_rids, 1:] track_res = np.concatenate((sub_det[matched_rids, 0:1], matched_tids.reshape(-1, 1), det_res), axis=1) res.append(track_res) res = np.concatenate(res, axis=0) return res
track1to2/track1to2_track.py
import numpy as np from scipy.optimize import linear_sum_assignment from collections import defaultdict from utils.utils import parse_camera_param def global2pixel(person_coords, camera_id, camera_param_dict): # det : X Y Z world_coord = person_coords / camera_param_dict['discretization_factor'] + camera_param_dict['min_volume'] trans_coord = world_coord - camera_param_dict[camera_id]['Translation'] uvw = np.linalg.inv(camera_param_dict[camera_id]['Rotation']) @ trans_coord.transpose(1, 0) uvw = uvw.transpose(1, 0) pixel_coords = uvw / camera_param_dict[camera_id]['FInv'] / uvw[:, 2:3] + camera_param_dict[camera_id]['C'] return pixel_coords[:, :2] def batch_euc_dist(point1, point2): point1_reshape = point1[:, np.newaxis, :] point2_reshape = point2[np.newaxis, :, :] sub = point1_reshape - point2_reshape dist = np.linalg.norm(sub, ord=2, axis=-1) return dist def batch_cosine_dist(feat1, feat2): assert feat1.shape[1] == feat2.shape[1] feat1 = feat1 / np.linalg.norm(feat1, ord=2, axis=-1, keepdims=True) feat2 = feat2 / np.linalg.norm(feat2, ord=2, axis=-1, keepdims=True) sim_matrix = feat1 @ feat2.T return 1 - sim_matrix def batch_ious(det, gt): det[:, 2:4] += det[:, :2] gt[:, 2:4] += gt[:, :2] det = det[:, np.newaxis, :] gt = gt[np.newaxis, :, :] max_x1 = np.maximum(det[..., 0], gt[..., 0]) min_x2 = np.minimum(det[..., 2], gt[..., 2]) max_y1 = np.maximum(det[..., 1], gt[..., 1]) min_y2 = np.minimum(det[..., 3], gt[..., 3]) i = np.maximum(min_y2 - max_y1, 0) * np.maximum(min_x2 - max_x1, 0) a1 = (det[..., 2] - det[..., 0]) * (det[..., 3] - det[..., 1]) a2 = (gt[..., 3] - gt[..., 1]) * (gt[...,2] - gt[..., 0]) u = a1 + a2 - i return i / u def cos_match(det, res, unmatched_rids, unmatched_cids, cos_th): if len(unmatched_rids) == 0 or len(unmatched_cids) == 0: return np.array([], dtype=int), np.array([], dtype=int) sub_det = det[unmatched_rids, :] sub_res = res[unmatched_cids, :] cosine_dist = batch_cosine_dist(sub_det, sub_res) matched_rids, matched_cids = linear_sum_assignment(cosine_dist) mask = cosine_dist[matched_rids, matched_cids] < cos_th matched_rids = matched_rids[mask] matched_cids = matched_cids[mask] matched_rids = unmatched_rids[matched_rids] matched_cids = unmatched_cids[matched_cids] return matched_rids, matched_cids def pos_match(det, res, unmatched_rids, unmatched_cids, pos_th): if len(unmatched_rids) == 0 or len(unmatched_cids) == 0: return np.array([], dtype=int), np.array([], dtype=int) sub_det = det[unmatched_rids, :] sub_res = res[unmatched_cids, :] euc_dist = batch_euc_dist(sub_det, sub_res) matched_rids, matched_cids = linear_sum_assignment(euc_dist) mask = euc_dist[matched_rids, matched_cids] < pos_th matched_rids = matched_rids[mask] matched_cids = matched_cids[mask] matched_rids = unmatched_rids[matched_rids] matched_cids = unmatched_cids[matched_cids] return matched_rids, matched_cids def track1to2_track(dets, track1_res, camera_id, camera_param_file, cos_th, pos_th, cos_first=True): #track1_res: fid, tid, Y, X, Z #dets: fid, cat, x, y, w, h, score, feat camera_param_dict = parse_camera_param(camera_param_file) data_for_projection = np.concatenate((track1_res[:, 3:4], track1_res[:, 2:3], track1_res[:, 4:5]), axis=1) pixel_coord = global2pixel(data_for_projection, camera_id, camera_param_dict) track1_pixel_res = np.hstack((track1_res[:, :2], pixel_coord))# x, y det_head_point_x = dets[:, 2] + dets[:, 4] / 2 det_head_point_y = dets[:, 3] + dets[:, 5] / 2 det_head_point = np.hstack((det_head_point_x.reshape(-1, 1), det_head_point_y.reshape(-1, 1))) det_head = np.hstack((dets[:, 0:1], det_head_point)) fids = np.unique(track1_pixel_res[:, 0]) res = [] tracks_dict = {} new_tid = 100 for fid in sorted(fids): sub_det_head = det_head[det_head[:, 0] == fid] sub_det = dets[dets[:, 0] == fid] sub_track1_res = track1_res[track1_res[:, 0] == fid] if len(sub_det_head) == 0: continue det_size = len(sub_det) res_size = len(sub_track1_res) det_point = sub_det_head[:, 1:3] track1res = track1_pixel_res[track1_pixel_res[:, 0] == fid] tids = track1res[:, 1] track1res_point = track1res[:, 2:4] unmatched_rids = np.arange(det_size).astype(int) unmatched_cids = np.arange(res_size).astype(int) if cos_first: matched_rids, matched_cids = cos_match(sub_det[:, 7:], sub_track1_res[:, 5:], unmatched_rids, unmatched_cids, cos_th) else: matched_rids, matched_cids = pos_match(det_point, track1res_point, unmatched_rids, unmatched_cids, pos_th) unmatched_rids = set(list(range(det_size))) - set(matched_rids.tolist()) unmatched_rids = np.array(list(unmatched_rids)).astype(int) unmatched_cids = set(list(range(res_size))) - set(matched_cids.tolist()) unmatched_cids = np.array(list(unmatched_cids)).astype(int) if cos_first: matched_rids2, matched_cids2 = pos_match(det_point, track1res_point, unmatched_rids, unmatched_cids, pos_th) else: matched_rids2, matched_cids2 = cos_match(sub_det[:, 7:], sub_track1_res[:, 5:], unmatched_rids, unmatched_cids, cos_th) matched_rids = np.hstack((matched_rids, matched_rids2)) matched_cids = np.hstack((matched_cids, matched_cids2)) matched_tids = tids[matched_cids] det_res = sub_det[matched_rids, 1:] track_res = np.concatenate((sub_det[matched_rids, 0:1], matched_tids.reshape(-1, 1), det_res), axis=1) res.append(track_res) res = np.concatenate(res, axis=0) return res
0.663669
0.553324
import logging import os import uuid from flask import Flask, render_template, request, send_from_directory from flask_assets import Environment from pyhocon import ConfigTree from search_ui import ClientError, SearchEngine from search_ui.util import PreferredMime logger = logging.getLogger('search-ui') # flask webserver app = Flask(__name__) app.secret_key = str(uuid.uuid4()) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True assets = Environment(app) assets.debug = False # search engine engine = None # type: SearchEngine @app.route("/") def index(): """the start page, where the user may enter the first query""" return render_template('search-startpage.html') @app.route("/search") def search(): """the search interface. Executes the query and returns the search results as HTML or JSON""" search_request = engine.parse_search_request(request) if not search_request.follow_up: q = search_request.query author = ', author: "{}"'.format(q.author) if q.author else "" date = ', date: {} to {}'.format(q.date_after or "any", q.date_before or "any") \ if (q.date_after or q.date_before) else "" logger.info('search query from {} (session: {}, step: {}, query: "{}"{}{})' .format(request.remote_addr, search_request.sid, q.step, q.query, author, date)) mime = PreferredMime(request) if mime.pref_json: return engine.search_json(search_request) else: return engine.search_html(search_request) @app.errorhandler(ClientError) def handle_es_request_error(error): """ handle all sorts of client errors (ClientError is a custom exception that is raised whenever the search fails due to client errors) """ return str(error), 400 @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico') def main(conf: ConfigTree = None): global engine engine = SearchEngine.from_config(conf) config = engine.config logger.info("search engine initialized, launching webserver...") app.run(debug=config.get_bool('webserver.debug'), host=config.get('webserver.host'), port=config.get_int('webserver.port'), threaded=True)
search_ui/app.py
import logging import os import uuid from flask import Flask, render_template, request, send_from_directory from flask_assets import Environment from pyhocon import ConfigTree from search_ui import ClientError, SearchEngine from search_ui.util import PreferredMime logger = logging.getLogger('search-ui') # flask webserver app = Flask(__name__) app.secret_key = str(uuid.uuid4()) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True assets = Environment(app) assets.debug = False # search engine engine = None # type: SearchEngine @app.route("/") def index(): """the start page, where the user may enter the first query""" return render_template('search-startpage.html') @app.route("/search") def search(): """the search interface. Executes the query and returns the search results as HTML or JSON""" search_request = engine.parse_search_request(request) if not search_request.follow_up: q = search_request.query author = ', author: "{}"'.format(q.author) if q.author else "" date = ', date: {} to {}'.format(q.date_after or "any", q.date_before or "any") \ if (q.date_after or q.date_before) else "" logger.info('search query from {} (session: {}, step: {}, query: "{}"{}{})' .format(request.remote_addr, search_request.sid, q.step, q.query, author, date)) mime = PreferredMime(request) if mime.pref_json: return engine.search_json(search_request) else: return engine.search_html(search_request) @app.errorhandler(ClientError) def handle_es_request_error(error): """ handle all sorts of client errors (ClientError is a custom exception that is raised whenever the search fails due to client errors) """ return str(error), 400 @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico') def main(conf: ConfigTree = None): global engine engine = SearchEngine.from_config(conf) config = engine.config logger.info("search engine initialized, launching webserver...") app.run(debug=config.get_bool('webserver.debug'), host=config.get('webserver.host'), port=config.get_int('webserver.port'), threaded=True)
0.42477
0.059976
import os import logging from google.cloud import vision from ..storage import StoragePrefix, StorageFile from . import utils logger = logging.getLogger(__name__) class PDFAnalyzer: # How many pages should be grouped into each json output file. BATCH_SIZE = 100 # Supported mime_types are: 'application/pdf' and 'image/tiff' MIME_TYPE = 'application/pdf' _credentials = None @classmethod def get_credentials(cls): if not cls._credentials: file_path = os.environ.get("GOOGLE_VISION_API_CREDENTIALS") if not file_path: raise AttributeError( "GOOGLE_VISION_API_CREDENTIALS environment variable must be configured for Vision API." ) if not os.path.exists(file_path): raise FileNotFoundError("File not found: %s" % file_path) logger.debug("Loading credentials from %s ..." % file_path) cls._credentials = utils.load_credentials(file_path) return cls._credentials def __init__(self, input_uri, output_uri=None): self.input_uri = input_uri if output_uri: self.output_uri = output_uri else: self.output_uri = input_uri + ".json" self.operation = None def detect_text(self): client = vision.ImageAnnotatorClient(credentials=self.get_credentials()) feature = vision.types.Feature( type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION ) gcs_source = vision.types.GcsSource(uri=self.input_uri) input_config = vision.types.InputConfig( gcs_source=gcs_source, mime_type=self.MIME_TYPE ) gcs_destination = vision.types.GcsDestination(uri=self.output_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=self.BATCH_SIZE) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config) self.operation = client.async_batch_annotate_files( requests=[async_request]) return self def wait(self): self.operation.result(timeout=420) return self def get_results(self): results = None for f in StoragePrefix(self.output_uri).files: result = StorageFile.load_json(f.uri, encoding='utf-8') if results is None: results = result else: responses = results.get("responses", []) responses.extend(result.get("responses", [])) results["responses"] = responses return results
gcp/vision.py
import os import logging from google.cloud import vision from ..storage import StoragePrefix, StorageFile from . import utils logger = logging.getLogger(__name__) class PDFAnalyzer: # How many pages should be grouped into each json output file. BATCH_SIZE = 100 # Supported mime_types are: 'application/pdf' and 'image/tiff' MIME_TYPE = 'application/pdf' _credentials = None @classmethod def get_credentials(cls): if not cls._credentials: file_path = os.environ.get("GOOGLE_VISION_API_CREDENTIALS") if not file_path: raise AttributeError( "GOOGLE_VISION_API_CREDENTIALS environment variable must be configured for Vision API." ) if not os.path.exists(file_path): raise FileNotFoundError("File not found: %s" % file_path) logger.debug("Loading credentials from %s ..." % file_path) cls._credentials = utils.load_credentials(file_path) return cls._credentials def __init__(self, input_uri, output_uri=None): self.input_uri = input_uri if output_uri: self.output_uri = output_uri else: self.output_uri = input_uri + ".json" self.operation = None def detect_text(self): client = vision.ImageAnnotatorClient(credentials=self.get_credentials()) feature = vision.types.Feature( type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION ) gcs_source = vision.types.GcsSource(uri=self.input_uri) input_config = vision.types.InputConfig( gcs_source=gcs_source, mime_type=self.MIME_TYPE ) gcs_destination = vision.types.GcsDestination(uri=self.output_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=self.BATCH_SIZE) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config) self.operation = client.async_batch_annotate_files( requests=[async_request]) return self def wait(self): self.operation.result(timeout=420) return self def get_results(self): results = None for f in StoragePrefix(self.output_uri).files: result = StorageFile.load_json(f.uri, encoding='utf-8') if results is None: results = result else: responses = results.get("responses", []) responses.extend(result.get("responses", [])) results["responses"] = responses return results
0.42656
0.085061
class Node: def __init__(self,val,parent=None,rnk=0): self.Value=val self.Parent=parent self.child=0 self.Rank=rnk self.TotalChildrens=0 self.childNodes=[] def AddMultiLayer(self,values): n=len(values) node=self.addNode(values[0]) if n==1: return else: node.AddMultiLayer(values[1:]) self.refresh() def addNode(self,val): if(self.hasChildValue(val)): return self.getChild(val) self.childNodes.append(Node(val,self,self.Rank+1)) self.child+=1 self.TotalChildrens+=1 return self.childNodes[self.child-1] def removeNode(self,val): for i in range(self.child): if(self.childNodes[i].Value==val): self.TotalChildrens-=(self.childNodes[i].TotalChildrens+1) self.childNodes.pop(i) def refresh(self): num=self.child for childrens in self.childNodes: childrens.refresh() num+=childrens.TotalChildrens self.TotalChildrens=num def hasChildValue(self,val): for i in range(self.child): if(self.childNodes[i].Value==val): return True return False def getChild(self,val): for i in range(self.child): if(self.childNodes[i].Value==val): return self.childNodes[i] def show(self): print("Value="+self.Value) print("childNodes="+str(self.child)) print("Total childNodes="+str(self.TotalChildrens)) def showAll(self): self.show() for child in self.childNodes: child.showAll() def showTree(self): print(chr(195)+chr(196)*self.Rank+">"+(chr(196)*2)+"("+str(self.child)+"/"+str(self.TotalChildrens)+")"+("-"*3)+self.Value) for child in self.childNodes: child.showTree() def getMainChild(self): if self.child==0: return None child=self.childNodes[0] for i in range(self.child): max=self.childNodes[0].TotalChildrens if(self.childNodes[i].TotalChildrens>max): max=self.childNodes[i].TotalChildrens child=self.childNodes[i] return child def getLeaves(self,prev=[]): for i in range(self.child): if(self.childNodes[i].child==0): prev.append(self.childNodes[i]) else: prev=self.childNodes[i].getLeaves(prev) return prev def CollectAll(self,deliminator=''): lis=[] leaves=self.getLeaves() for node in leaves: link=node.Value par=node.Parent r=node.Rank-self.Rank for i in range(r): link=par.Value+deliminator+link par=par.Parent lis.append(link) return lis def collectLeaf(self,deliminator=''): link=self.Value par=self.Parent r=self.Rank for i in range(r): link=par.Value+deliminator+link par=par.Parent return link if __name__=="__main__": pass
Tree.py
class Node: def __init__(self,val,parent=None,rnk=0): self.Value=val self.Parent=parent self.child=0 self.Rank=rnk self.TotalChildrens=0 self.childNodes=[] def AddMultiLayer(self,values): n=len(values) node=self.addNode(values[0]) if n==1: return else: node.AddMultiLayer(values[1:]) self.refresh() def addNode(self,val): if(self.hasChildValue(val)): return self.getChild(val) self.childNodes.append(Node(val,self,self.Rank+1)) self.child+=1 self.TotalChildrens+=1 return self.childNodes[self.child-1] def removeNode(self,val): for i in range(self.child): if(self.childNodes[i].Value==val): self.TotalChildrens-=(self.childNodes[i].TotalChildrens+1) self.childNodes.pop(i) def refresh(self): num=self.child for childrens in self.childNodes: childrens.refresh() num+=childrens.TotalChildrens self.TotalChildrens=num def hasChildValue(self,val): for i in range(self.child): if(self.childNodes[i].Value==val): return True return False def getChild(self,val): for i in range(self.child): if(self.childNodes[i].Value==val): return self.childNodes[i] def show(self): print("Value="+self.Value) print("childNodes="+str(self.child)) print("Total childNodes="+str(self.TotalChildrens)) def showAll(self): self.show() for child in self.childNodes: child.showAll() def showTree(self): print(chr(195)+chr(196)*self.Rank+">"+(chr(196)*2)+"("+str(self.child)+"/"+str(self.TotalChildrens)+")"+("-"*3)+self.Value) for child in self.childNodes: child.showTree() def getMainChild(self): if self.child==0: return None child=self.childNodes[0] for i in range(self.child): max=self.childNodes[0].TotalChildrens if(self.childNodes[i].TotalChildrens>max): max=self.childNodes[i].TotalChildrens child=self.childNodes[i] return child def getLeaves(self,prev=[]): for i in range(self.child): if(self.childNodes[i].child==0): prev.append(self.childNodes[i]) else: prev=self.childNodes[i].getLeaves(prev) return prev def CollectAll(self,deliminator=''): lis=[] leaves=self.getLeaves() for node in leaves: link=node.Value par=node.Parent r=node.Rank-self.Rank for i in range(r): link=par.Value+deliminator+link par=par.Parent lis.append(link) return lis def collectLeaf(self,deliminator=''): link=self.Value par=self.Parent r=self.Rank for i in range(r): link=par.Value+deliminator+link par=par.Parent return link if __name__=="__main__": pass
0.125259
0.18591
import subprocess def sort(input_): """Invoke sorter on `lines`, return sorted lines.""" process = subprocess.Popen( ['./mesos_include_sorter.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = process.communicate(input=input_.encode())[0] return output.decode() def test_top_level_grouping(): """Test that includes are grouped by high-level categories.""" input_ = \ '#include <project.hpp>\n' \ '#include <string>\n' \ '#include <string.h>\n' expected = \ '#include <string.h>\n' \ '\n' \ '#include <string>\n' \ '\n' \ '#include <project.hpp>\n' assert sort(input_) == expected def test_sorting(): """Test alphabetic sorting inside a category.""" input_ = \ '#include <b.hpp>\n' \ '#include <a.hpp>\n' expected = \ '#include <a.hpp>\n' \ '#include <b.hpp>\n' assert sort(input_) == expected def test_depth_sectioning(): """Test sectioning by file depth.""" input_ = \ '#include <a.hpp>\n' \ '#include <a/a.hpp>\n' \ '#include <b/b.hpp>\n' \ '#include <b.hpp>\n' expected = \ '#include <a.hpp>\n' \ '#include <b.hpp>\n' \ '\n' \ '#include <a/a.hpp>\n' \ '\n' \ '#include <b/b.hpp>\n' assert sort(input_) == expected def test_relatives_sorted(): """Test sorting of files with relative paths.""" input_ = \ '#include "a.hpp"\n' \ '#include <b.hpp>\n' expected = \ '#include <b.hpp>\n' \ '\n' \ '#include "a.hpp"\n' assert sort(input_) == expected def test_special_h_files(): """ Test treatment of special files ending in `.h` which are not system headers. """ input_ = \ '#include <string.h>\n' \ '#include <gtest/gtest.h>\n' expected = \ '#include <string.h>\n' \ '\n' \ '#include <gtest/gtest.h>\n' assert sort(input_) == expected def test_empty_line_handling(): """Test handling of empty lines.""" input_ = \ '#include <string>\n' \ '\n' \ '#include <string.h>\n' expected = \ '#include <string.h>\n' \ '\n' \ '#include <string>\n' assert sort(input_) == expected
test_mesos_include_sorter.py
import subprocess def sort(input_): """Invoke sorter on `lines`, return sorted lines.""" process = subprocess.Popen( ['./mesos_include_sorter.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = process.communicate(input=input_.encode())[0] return output.decode() def test_top_level_grouping(): """Test that includes are grouped by high-level categories.""" input_ = \ '#include <project.hpp>\n' \ '#include <string>\n' \ '#include <string.h>\n' expected = \ '#include <string.h>\n' \ '\n' \ '#include <string>\n' \ '\n' \ '#include <project.hpp>\n' assert sort(input_) == expected def test_sorting(): """Test alphabetic sorting inside a category.""" input_ = \ '#include <b.hpp>\n' \ '#include <a.hpp>\n' expected = \ '#include <a.hpp>\n' \ '#include <b.hpp>\n' assert sort(input_) == expected def test_depth_sectioning(): """Test sectioning by file depth.""" input_ = \ '#include <a.hpp>\n' \ '#include <a/a.hpp>\n' \ '#include <b/b.hpp>\n' \ '#include <b.hpp>\n' expected = \ '#include <a.hpp>\n' \ '#include <b.hpp>\n' \ '\n' \ '#include <a/a.hpp>\n' \ '\n' \ '#include <b/b.hpp>\n' assert sort(input_) == expected def test_relatives_sorted(): """Test sorting of files with relative paths.""" input_ = \ '#include "a.hpp"\n' \ '#include <b.hpp>\n' expected = \ '#include <b.hpp>\n' \ '\n' \ '#include "a.hpp"\n' assert sort(input_) == expected def test_special_h_files(): """ Test treatment of special files ending in `.h` which are not system headers. """ input_ = \ '#include <string.h>\n' \ '#include <gtest/gtest.h>\n' expected = \ '#include <string.h>\n' \ '\n' \ '#include <gtest/gtest.h>\n' assert sort(input_) == expected def test_empty_line_handling(): """Test handling of empty lines.""" input_ = \ '#include <string>\n' \ '\n' \ '#include <string.h>\n' expected = \ '#include <string.h>\n' \ '\n' \ '#include <string>\n' assert sort(input_) == expected
0.788909
0.319009
from . import api import argparse import os.path import sys parsing_errors = False def is_valid_file(parser, arg): """Check if the file exists and return its path. Otherwise raise error.""" if not arg: return arg if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg def default_dagfile(): """Get default DAG file path: the first *.dagpy file in the current folder.""" global parsing_errors for file in os.listdir('./'): if file.endswith('.dagpy'): return file print('No default dagpy file found. Please specify it with [-d] flag.') parsing_errors = True def run_default(args): """Running the script without any args.""" print('Run {} -h for help.'.format(module_name)) sys.exit() def run_create(args): """dagpy create""" print('Creating new project: {}'.format(args.name)) api.new_project(args.name, args.run) def run_view(args): """dagpy view""" print('Displaying DAG from {}. Please wait while the visualization framework is initialized.'.format(args.dag_fpathname)) api.display_dag(args.dag_fpathname, flow = args.blocks) def run_exec(args): """dagpy execute""" if args.exec_all: print('Executing all blocks.\n\n') elif args.blocks: print('Executing blocks: {} and all their dependencies.\n\n'.format(', '.join(args.blocks))) else: print('No blocks specified. To run all blocks use --all. To run selected, specify them.') return api.execute_blocks(args.dag_fpathname, args.blocks, exec_all=args.exec_all) def run_makeflow(args): """dagpy makeflow""" print('Making flow {} for blocks: {}'.format(args.flow_name, ', '.join(args.blocks))) api.create_flow(args.dag_fpathname, args.blocks, args.flow_name, run=args.run) def run_submitflow(args): """dagpy submitflow""" print('Commiting flow from {}'.format(args.flow_notebook)) api.update_from_flow(args.dag_fpathname, args.flow_notebook) def run_blockrm(args): """dagpy remove""" print('Removing block {} from {}'.format(args.block, args.dag_fpathname)) api.remove_block(args.dag_fpathname, args.block) def main(main_args=None): if main_args is None: main_args = sys.argv module_name = 'dagpy' parser = argparse.ArgumentParser(prog='dagpy') parser.set_defaults(func=run_default) subparsers = parser.add_subparsers(title='DAGpy subcommands', description="This script provides you with the main DAGpy functionalities. \ To find out more about each, run '{0} subcommand -h'. To start and run a new project, run '{0} create my_dagpy_project -r'".format(module_name)) parser_create = subparsers.add_parser('create', help='Create new DAGpy project') parser_create.add_argument('name', help='project name') parser_create.add_argument('-r', '--run', dest='run', action='store_true', help='run the flow notebook of the newly created empty project',) parser_create.set_defaults(func=run_create) parser_view = subparsers.add_parser('view', help='Display the DAG') parser_view.add_argument('blocks', nargs='*', help='blocks for which to highlight the flow (optional)', metavar='BLOCKS') parser_view.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file (default: first .dagpy file in the current directory)', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_view.set_defaults(func=run_view) parser_exec = subparsers.add_parser('execute', help='Execute DAG blocks', aliases=['exe']) parser_exec.add_argument('blocks', nargs='*', help='blocks to execute', metavar='BLOCKS') parser_exec.add_argument('-a', '--all', dest='exec_all', action='store_true', help='execute all blocks',) parser_exec.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_exec.set_defaults(func=run_exec) parser_makeflow = subparsers.add_parser('makeflow', help='Make a new flow', aliases=['mf']) parser_makeflow.add_argument('blocks', nargs='+', help='blocks from which to create the flow', metavar='BLOCKS') parser_makeflow.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_makeflow.add_argument('-n', '--name', dest='flow_name', help="name of the flow (default 'dagpy_flow')", default='dagpy_flow', metavar='NAME') parser_makeflow.add_argument('-r', '--run', dest='run', action='store_true', help='run the flow notebook',) parser_makeflow.set_defaults(func=run_makeflow) parser_submitflow = subparsers.add_parser('submitflow', help='Submit the flow', aliases=['sf']) parser_submitflow.add_argument('flow_notebook', help='flow notebook from which to update the DAG', type=lambda x: is_valid_file(parser_exec, x)) parser_submitflow.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_submitflow.set_defaults(func=run_submitflow) parser_blockrm = subparsers.add_parser('remove', help='Remove block', aliases=['rm']) parser_blockrm.add_argument('block', help='block to remove') parser_blockrm.add_argument('-d', '--dag', dest='dag_fpathname', default='', help='DAG file', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_blockrm.add_argument('--removefile', dest='removefile', action='store_true', help='Remove the block file after removing the block from the DAG') parser_blockrm.set_defaults(func=run_blockrm) if len(sys.argv) == 1: main_args += ['-h'] parsed_args = parser.parse_args(main_args[1:]) if not hasattr(parsed_args, 'dag_fpathname') or not parsed_args.dag_fpathname: parsed_args.dag_fpathname = default_dagfile() if parsing_errors: sys.exit() elif hasattr(parsed_args, 'func'): parsed_args.func(parsed_args) if __name__ == '__main__': main()
dagpy/__main__.py
from . import api import argparse import os.path import sys parsing_errors = False def is_valid_file(parser, arg): """Check if the file exists and return its path. Otherwise raise error.""" if not arg: return arg if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg def default_dagfile(): """Get default DAG file path: the first *.dagpy file in the current folder.""" global parsing_errors for file in os.listdir('./'): if file.endswith('.dagpy'): return file print('No default dagpy file found. Please specify it with [-d] flag.') parsing_errors = True def run_default(args): """Running the script without any args.""" print('Run {} -h for help.'.format(module_name)) sys.exit() def run_create(args): """dagpy create""" print('Creating new project: {}'.format(args.name)) api.new_project(args.name, args.run) def run_view(args): """dagpy view""" print('Displaying DAG from {}. Please wait while the visualization framework is initialized.'.format(args.dag_fpathname)) api.display_dag(args.dag_fpathname, flow = args.blocks) def run_exec(args): """dagpy execute""" if args.exec_all: print('Executing all blocks.\n\n') elif args.blocks: print('Executing blocks: {} and all their dependencies.\n\n'.format(', '.join(args.blocks))) else: print('No blocks specified. To run all blocks use --all. To run selected, specify them.') return api.execute_blocks(args.dag_fpathname, args.blocks, exec_all=args.exec_all) def run_makeflow(args): """dagpy makeflow""" print('Making flow {} for blocks: {}'.format(args.flow_name, ', '.join(args.blocks))) api.create_flow(args.dag_fpathname, args.blocks, args.flow_name, run=args.run) def run_submitflow(args): """dagpy submitflow""" print('Commiting flow from {}'.format(args.flow_notebook)) api.update_from_flow(args.dag_fpathname, args.flow_notebook) def run_blockrm(args): """dagpy remove""" print('Removing block {} from {}'.format(args.block, args.dag_fpathname)) api.remove_block(args.dag_fpathname, args.block) def main(main_args=None): if main_args is None: main_args = sys.argv module_name = 'dagpy' parser = argparse.ArgumentParser(prog='dagpy') parser.set_defaults(func=run_default) subparsers = parser.add_subparsers(title='DAGpy subcommands', description="This script provides you with the main DAGpy functionalities. \ To find out more about each, run '{0} subcommand -h'. To start and run a new project, run '{0} create my_dagpy_project -r'".format(module_name)) parser_create = subparsers.add_parser('create', help='Create new DAGpy project') parser_create.add_argument('name', help='project name') parser_create.add_argument('-r', '--run', dest='run', action='store_true', help='run the flow notebook of the newly created empty project',) parser_create.set_defaults(func=run_create) parser_view = subparsers.add_parser('view', help='Display the DAG') parser_view.add_argument('blocks', nargs='*', help='blocks for which to highlight the flow (optional)', metavar='BLOCKS') parser_view.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file (default: first .dagpy file in the current directory)', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_view.set_defaults(func=run_view) parser_exec = subparsers.add_parser('execute', help='Execute DAG blocks', aliases=['exe']) parser_exec.add_argument('blocks', nargs='*', help='blocks to execute', metavar='BLOCKS') parser_exec.add_argument('-a', '--all', dest='exec_all', action='store_true', help='execute all blocks',) parser_exec.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_exec.set_defaults(func=run_exec) parser_makeflow = subparsers.add_parser('makeflow', help='Make a new flow', aliases=['mf']) parser_makeflow.add_argument('blocks', nargs='+', help='blocks from which to create the flow', metavar='BLOCKS') parser_makeflow.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_makeflow.add_argument('-n', '--name', dest='flow_name', help="name of the flow (default 'dagpy_flow')", default='dagpy_flow', metavar='NAME') parser_makeflow.add_argument('-r', '--run', dest='run', action='store_true', help='run the flow notebook',) parser_makeflow.set_defaults(func=run_makeflow) parser_submitflow = subparsers.add_parser('submitflow', help='Submit the flow', aliases=['sf']) parser_submitflow.add_argument('flow_notebook', help='flow notebook from which to update the DAG', type=lambda x: is_valid_file(parser_exec, x)) parser_submitflow.add_argument('-d', '--dag', dest='dag_fpathname', help='DAG file', default='', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_submitflow.set_defaults(func=run_submitflow) parser_blockrm = subparsers.add_parser('remove', help='Remove block', aliases=['rm']) parser_blockrm.add_argument('block', help='block to remove') parser_blockrm.add_argument('-d', '--dag', dest='dag_fpathname', default='', help='DAG file', metavar='FILE', type=lambda x: is_valid_file(parser_exec, x)) parser_blockrm.add_argument('--removefile', dest='removefile', action='store_true', help='Remove the block file after removing the block from the DAG') parser_blockrm.set_defaults(func=run_blockrm) if len(sys.argv) == 1: main_args += ['-h'] parsed_args = parser.parse_args(main_args[1:]) if not hasattr(parsed_args, 'dag_fpathname') or not parsed_args.dag_fpathname: parsed_args.dag_fpathname = default_dagfile() if parsing_errors: sys.exit() elif hasattr(parsed_args, 'func'): parsed_args.func(parsed_args) if __name__ == '__main__': main()
0.350866
0.15109
import random import pickle import os def print_board(slots, board_size): st = " " for i in range(board_size): st = st + " " + str(i + 1) print(st) for row in range(board_size): st = " " if row == 0: for col in range(board_size): st = st + "______" print(st) st = " " for col in range(board_size): st = st + "| " print(st + "|") st = " " + str(row + 1) + " " for col in range(board_size): st = st + "| " + str(slots[row][col]) + " " print(st + "|") st = " " for col in range(board_size): st = st + "|_____" print(st + '|') print() def set_mines(board, num_of_mines, board_size): count = 0 while count < num_of_mines: value = random.randint(0, board_size * board_size - 1) row = value // board_size col = value % board_size if board[row][col] != -1: count = count + 1 board[row][col] = -1 def set_values(board, board_size): # Function that counts value of cell for r in range(board_size): for col in range(board_size): # Skip, if it contains a mine if board[r][col] == -1: continue if r > 0 and board[r - 1][col] == -1: board[r][col] = board[r][col] + 1 # Check down if r < board_size - 1 and board[r + 1][col] == -1: board[r][col] = board[r][col] + 1 # Check left if col > 0 and board[r][col - 1] == -1: board[r][col] = board[r][col] + 1 # Check right if col < board_size - 1 and board[r][col + 1] == -1: board[r][col] = board[r][col] + 1 # Check top-left if r > 0 and col > 0 and board[r - 1][col - 1] == -1: board[r][col] = board[r][col] + 1 # Check top-right if r > 0 and col < board_size - 1 and board[r - 1][col + 1] == -1: board[r][col] = board[r][col] + 1 # Check below-left if r < board_size - 1 and col > 0 and board[r + 1][col - 1] == -1: board[r][col] = board[r][col] + 1 # Check below-right if r < board_size - 1 and col < board_size - 1 and board[r + 1][col + 1] == -1: board[r][col] = board[r][col] + 1 def neighbours(row, col, slots, board, board_size, opened): if [row, col] not in opened: opened.append([row, col]) if board[row][col] == 0: slots[row][col] = board[row][col] if row > 0: neighbours(row - 1, col, slots, board, board_size, opened) if row < board_size - 1: neighbours(row + 1, col, slots, board, board_size, opened) if col > 0: neighbours(row, col - 1, slots, board, board_size, opened) if col < board_size - 1: neighbours(row, col + 1, slots, board, board_size, opened) if row > 0 and col > 0: neighbours(row - 1, col - 1, slots, board, board_size, opened) if row > 0 and col < board_size - 1: neighbours(row - 1, col + 1, slots, board, board_size, opened) if row < board_size - 1 and col > 0: neighbours(row + 1, col - 1, slots, board, board_size, opened) if row < board_size - 1 and col < board_size - 1: neighbours(row + 1, col + 1, slots, board, board_size, opened) if board[row][col] != 0: slots[row][col] = board[row][col] def check_game_over(slots, board_size, num_of_mines): count = 0 # Loop for checking each cell in the grid for r in range(board_size): for col in range(board_size): if slots[r][col] != ' ' and slots[r][col] != 'F': count = count + 1 if count == board_size * board_size - num_of_mines: return True else: return False # Show all mines at the end of the game def show_mines(slots, board, board_size): for r in range(board_size): for col in range(board_size): if board[r][col] == -1: slots[r][col] = 'M' def show_instruction(): print("Instructions:") print("1. Enter column and row number to dig a cell, Example \"2 3\"") print("2. In order to put or remove a flag, enter F after column and row, Example \"2 3 f\"") print("3. If you decide to leave during the game, you can save your progress by writing \"s\"") print("4. Write \"q\" in order to quit") def generate_new_game(board_size, num_of_mines): board = [[0 for y in range(board_size)] for x in range(board_size)] slots = [[' ' for y in range(board_size)] for x in range(board_size)] set_mines(board, num_of_mines, board_size) set_values(board, board_size) return board, slots def play(board, slots, opened, flags, num_of_mines, board_size): show_instruction() game_over = False # Game loop while not game_over: print_board(slots, board_size) user_input = input("Enter column and row number: ").split() if (user_input[0]) == "q": quit() if user_input[0] == "s": file = open('save.p', 'wb') pickle.dump(board, file) pickle.dump(slots, file) pickle.dump(opened, file) pickle.dump(flags, file) pickle.dump(num_of_mines, file) file.close() print("Game saved\n") if len(user_input) == 2: try: value = list(map(int, user_input)) except ValueError: print("Wrong input!") show_instruction() continue elif len(user_input) == 3: if user_input[2] != 'F' and user_input[2] != 'f': print("Wrong Input!") show_instruction() continue try: value = list(map(int, user_input[:2])) except ValueError: print("Wrong input!") show_instruction() continue if value[0] > board_size or value[0] < 1 or value[1] > board_size or value[1] < 1: print("Wrong input!") show_instruction() continue col = value[0] - 1 row = value[1] - 1 if [row, col] in flags: print("Removing flag") flags.remove([row, col]) slots[row][col] = ' ' continue # Check the number of flags if len(flags) < num_of_mines: flags.append([row, col]) slots[row][col] = 'F' print("Flag set") continue else: print("All flags set") continue else: print("Wrong input!") show_instruction() continue # Check if the input fit size of board if value[0] > board_size or value[0] < 1 or value[1] > board_size or value[1] < 1: print("Wrong Input!") show_instruction() continue col = value[0] - 1 row = value[1] - 1 if board[row][col] == -1: slots[row][col] = 'M' show_mines(slots, board, board_size) print_board(slots, board_size) print("Step on a mine!") print( "\n" "┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼\n" "███▀▀▀██┼███▀▀▀███┼███▀█▄█▀███┼██▀▀▀\n" "██┼┼┼┼██┼██┼┼┼┼┼██┼██┼┼┼█┼┼┼██┼██┼┼┼\n" "██┼┼┼▄▄▄┼██▄▄▄▄▄██┼██┼┼┼▀┼┼┼██┼██▀▀▀\n" "██┼┼┼┼██┼██┼┼┼┼┼██┼██┼┼┼┼┼┼┼██┼██┼┼┼\n" "███▄▄▄██┼██┼┼┼┼┼██┼██┼┼┼┼┼┼┼██┼██▄▄▄\n" "┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼\n" "███▀▀▀███┼▀███┼┼██▀┼██▀▀▀┼██▀▀▀▀██▄┼\n" "██┼┼┼┼┼██┼┼┼██┼┼██┼┼██┼┼┼┼██┼┼┼┼┼██┼\n" "██┼┼┼┼┼██┼┼┼██┼┼██┼┼██▀▀▀┼██▄▄▄▄▄▀▀┼\n" "██┼┼┼┼┼██┼┼┼██┼┼█▀┼┼██┼┼┼┼██┼┼┼┼┼██┼\n" "███▄▄▄███┼┼┼─▀█▀┼┼─┼██▄▄▄┼██┼┼┼┼┼██▄\n" "┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼\n") game_over = True continue elif board[row][col] == 0: # opened = [] slots[row][col] = '0' neighbours(row, col, slots, board, board_size, opened) else: slots[row][col] = board[row][col] # Check if all cells are open if check_game_over(slots, board_size, num_of_mines): show_mines(slots, board, board_size) print_board(slots, board_size) print("Congratulations!!! YOU WIN") game_over = True continue def choose_game_mode(): while True: try: user_input = int(input("\nMINESWEEPER\nMAIN MENU\n1 - Standard game 5x5\n2 - Custom game\n3 - Load game\n" "4 - Quit\nSelect the game mode: ")) # Standard game 5x5 if user_input == 1: board_size = 5 num_of_mines = random.randint(2, 5) board, slots = generate_new_game(board_size, num_of_mines) flags = [] opened = [] play(board, slots, opened, flags, num_of_mines, board_size) # Custom game elif user_input == 2: board_size = int(input("Print size of board: ")) num_of_mines = int(input("Print number of mines: ")) board, slots = generate_new_game(board_size, num_of_mines) flags = [] opened = [] play(board, slots, opened, flags, num_of_mines, board_size) # Loaded game elif user_input == 3: if os.path.isfile('./save.p'): file = open('save.p', 'rb') board = pickle.load(file) slots = pickle.load(file) opened = pickle.load(file) flags = pickle.load(file) num_of_mines = pickle.load(file) board_size = len(board) play(board, slots, opened, flags, num_of_mines, board_size) else: print("There is no any savings") quit(1) elif user_input == 4: quit() except ValueError: print("\nProvide an integer value!") continue if __name__ == "__main__": choose_game_mode()
minesweeper.py
import random import pickle import os def print_board(slots, board_size): st = " " for i in range(board_size): st = st + " " + str(i + 1) print(st) for row in range(board_size): st = " " if row == 0: for col in range(board_size): st = st + "______" print(st) st = " " for col in range(board_size): st = st + "| " print(st + "|") st = " " + str(row + 1) + " " for col in range(board_size): st = st + "| " + str(slots[row][col]) + " " print(st + "|") st = " " for col in range(board_size): st = st + "|_____" print(st + '|') print() def set_mines(board, num_of_mines, board_size): count = 0 while count < num_of_mines: value = random.randint(0, board_size * board_size - 1) row = value // board_size col = value % board_size if board[row][col] != -1: count = count + 1 board[row][col] = -1 def set_values(board, board_size): # Function that counts value of cell for r in range(board_size): for col in range(board_size): # Skip, if it contains a mine if board[r][col] == -1: continue if r > 0 and board[r - 1][col] == -1: board[r][col] = board[r][col] + 1 # Check down if r < board_size - 1 and board[r + 1][col] == -1: board[r][col] = board[r][col] + 1 # Check left if col > 0 and board[r][col - 1] == -1: board[r][col] = board[r][col] + 1 # Check right if col < board_size - 1 and board[r][col + 1] == -1: board[r][col] = board[r][col] + 1 # Check top-left if r > 0 and col > 0 and board[r - 1][col - 1] == -1: board[r][col] = board[r][col] + 1 # Check top-right if r > 0 and col < board_size - 1 and board[r - 1][col + 1] == -1: board[r][col] = board[r][col] + 1 # Check below-left if r < board_size - 1 and col > 0 and board[r + 1][col - 1] == -1: board[r][col] = board[r][col] + 1 # Check below-right if r < board_size - 1 and col < board_size - 1 and board[r + 1][col + 1] == -1: board[r][col] = board[r][col] + 1 def neighbours(row, col, slots, board, board_size, opened): if [row, col] not in opened: opened.append([row, col]) if board[row][col] == 0: slots[row][col] = board[row][col] if row > 0: neighbours(row - 1, col, slots, board, board_size, opened) if row < board_size - 1: neighbours(row + 1, col, slots, board, board_size, opened) if col > 0: neighbours(row, col - 1, slots, board, board_size, opened) if col < board_size - 1: neighbours(row, col + 1, slots, board, board_size, opened) if row > 0 and col > 0: neighbours(row - 1, col - 1, slots, board, board_size, opened) if row > 0 and col < board_size - 1: neighbours(row - 1, col + 1, slots, board, board_size, opened) if row < board_size - 1 and col > 0: neighbours(row + 1, col - 1, slots, board, board_size, opened) if row < board_size - 1 and col < board_size - 1: neighbours(row + 1, col + 1, slots, board, board_size, opened) if board[row][col] != 0: slots[row][col] = board[row][col] def check_game_over(slots, board_size, num_of_mines): count = 0 # Loop for checking each cell in the grid for r in range(board_size): for col in range(board_size): if slots[r][col] != ' ' and slots[r][col] != 'F': count = count + 1 if count == board_size * board_size - num_of_mines: return True else: return False # Show all mines at the end of the game def show_mines(slots, board, board_size): for r in range(board_size): for col in range(board_size): if board[r][col] == -1: slots[r][col] = 'M' def show_instruction(): print("Instructions:") print("1. Enter column and row number to dig a cell, Example \"2 3\"") print("2. In order to put or remove a flag, enter F after column and row, Example \"2 3 f\"") print("3. If you decide to leave during the game, you can save your progress by writing \"s\"") print("4. Write \"q\" in order to quit") def generate_new_game(board_size, num_of_mines): board = [[0 for y in range(board_size)] for x in range(board_size)] slots = [[' ' for y in range(board_size)] for x in range(board_size)] set_mines(board, num_of_mines, board_size) set_values(board, board_size) return board, slots def play(board, slots, opened, flags, num_of_mines, board_size): show_instruction() game_over = False # Game loop while not game_over: print_board(slots, board_size) user_input = input("Enter column and row number: ").split() if (user_input[0]) == "q": quit() if user_input[0] == "s": file = open('save.p', 'wb') pickle.dump(board, file) pickle.dump(slots, file) pickle.dump(opened, file) pickle.dump(flags, file) pickle.dump(num_of_mines, file) file.close() print("Game saved\n") if len(user_input) == 2: try: value = list(map(int, user_input)) except ValueError: print("Wrong input!") show_instruction() continue elif len(user_input) == 3: if user_input[2] != 'F' and user_input[2] != 'f': print("Wrong Input!") show_instruction() continue try: value = list(map(int, user_input[:2])) except ValueError: print("Wrong input!") show_instruction() continue if value[0] > board_size or value[0] < 1 or value[1] > board_size or value[1] < 1: print("Wrong input!") show_instruction() continue col = value[0] - 1 row = value[1] - 1 if [row, col] in flags: print("Removing flag") flags.remove([row, col]) slots[row][col] = ' ' continue # Check the number of flags if len(flags) < num_of_mines: flags.append([row, col]) slots[row][col] = 'F' print("Flag set") continue else: print("All flags set") continue else: print("Wrong input!") show_instruction() continue # Check if the input fit size of board if value[0] > board_size or value[0] < 1 or value[1] > board_size or value[1] < 1: print("Wrong Input!") show_instruction() continue col = value[0] - 1 row = value[1] - 1 if board[row][col] == -1: slots[row][col] = 'M' show_mines(slots, board, board_size) print_board(slots, board_size) print("Step on a mine!") print( "\n" "┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼\n" "███▀▀▀██┼███▀▀▀███┼███▀█▄█▀███┼██▀▀▀\n" "██┼┼┼┼██┼██┼┼┼┼┼██┼██┼┼┼█┼┼┼██┼██┼┼┼\n" "██┼┼┼▄▄▄┼██▄▄▄▄▄██┼██┼┼┼▀┼┼┼██┼██▀▀▀\n" "██┼┼┼┼██┼██┼┼┼┼┼██┼██┼┼┼┼┼┼┼██┼██┼┼┼\n" "███▄▄▄██┼██┼┼┼┼┼██┼██┼┼┼┼┼┼┼██┼██▄▄▄\n" "┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼\n" "███▀▀▀███┼▀███┼┼██▀┼██▀▀▀┼██▀▀▀▀██▄┼\n" "██┼┼┼┼┼██┼┼┼██┼┼██┼┼██┼┼┼┼██┼┼┼┼┼██┼\n" "██┼┼┼┼┼██┼┼┼██┼┼██┼┼██▀▀▀┼██▄▄▄▄▄▀▀┼\n" "██┼┼┼┼┼██┼┼┼██┼┼█▀┼┼██┼┼┼┼██┼┼┼┼┼██┼\n" "███▄▄▄███┼┼┼─▀█▀┼┼─┼██▄▄▄┼██┼┼┼┼┼██▄\n" "┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼\n") game_over = True continue elif board[row][col] == 0: # opened = [] slots[row][col] = '0' neighbours(row, col, slots, board, board_size, opened) else: slots[row][col] = board[row][col] # Check if all cells are open if check_game_over(slots, board_size, num_of_mines): show_mines(slots, board, board_size) print_board(slots, board_size) print("Congratulations!!! YOU WIN") game_over = True continue def choose_game_mode(): while True: try: user_input = int(input("\nMINESWEEPER\nMAIN MENU\n1 - Standard game 5x5\n2 - Custom game\n3 - Load game\n" "4 - Quit\nSelect the game mode: ")) # Standard game 5x5 if user_input == 1: board_size = 5 num_of_mines = random.randint(2, 5) board, slots = generate_new_game(board_size, num_of_mines) flags = [] opened = [] play(board, slots, opened, flags, num_of_mines, board_size) # Custom game elif user_input == 2: board_size = int(input("Print size of board: ")) num_of_mines = int(input("Print number of mines: ")) board, slots = generate_new_game(board_size, num_of_mines) flags = [] opened = [] play(board, slots, opened, flags, num_of_mines, board_size) # Loaded game elif user_input == 3: if os.path.isfile('./save.p'): file = open('save.p', 'rb') board = pickle.load(file) slots = pickle.load(file) opened = pickle.load(file) flags = pickle.load(file) num_of_mines = pickle.load(file) board_size = len(board) play(board, slots, opened, flags, num_of_mines, board_size) else: print("There is no any savings") quit(1) elif user_input == 4: quit() except ValueError: print("\nProvide an integer value!") continue if __name__ == "__main__": choose_game_mode()
0.269999
0.318578
from unittest import TestCase from omnicanvas.graphics import ShapeGraphic, BoxGraphic class BoxGraphicCreationTests(TestCase): def test_can_create_box_graphic(self): box = BoxGraphic(10, 20, 100, 200) self.assertIsInstance(box, ShapeGraphic) self.assertEqual(box._x, 10) self.assertEqual(box._y, 20) self.assertEqual(box._width, 100) self.assertEqual(box._height, 200) self.assertEqual(box._fill_color, "#FFFFFF") self.assertEqual(box._opacity, 1) self.assertEqual(box._line_width, 1) self.assertEqual(box._line_style, "-") self.assertEqual(box._line_color, "#000000") self.assertEqual(box._rotation, (0, 0, 0)) self.assertEqual(box._data, {}) def test_box_location_must_be_numeric(self): with self.assertRaises(TypeError): BoxGraphic("10", 20, 100, 200) with self.assertRaises(TypeError): BoxGraphic(10, "20", 100, 200) BoxGraphic(10.5, 20, 100, 200) BoxGraphic(10, 20.5, 100, 200) def test_box_dimensions_must_be_numeric(self): with self.assertRaises(TypeError): BoxGraphic(10, 20, "100", 200) with self.assertRaises(TypeError): BoxGraphic(10, 20, 100, "200") BoxGraphic(10, 20, 100.5, 200) BoxGraphic(10, 20, 100, 200.5) class BoxGraphicPropertyTests(TestCase): def test_basic_properties(self): box = BoxGraphic(10, 20, 100, 200) self.assertIs(box.x(), box._x) self.assertIs(box.y(), box._y) self.assertIs(box.width(), box._width) self.assertIs(box.height(), box._height) def test_can_set_location(self): box = BoxGraphic(10, 20, 100, 200) box.x(200) self.assertEqual(box.x(), 200) box.y(-10) self.assertEqual(box.y(), -10) def test_set_box_location_must_be_numeric(self): box = BoxGraphic(10, 20, 100, 200) with self.assertRaises(TypeError): box.x("10") with self.assertRaises(TypeError): box.y("20") box.x(10.5) box.y(10.5) def test_can_set_box_size(self): box = BoxGraphic(10, 20, 100, 200) box.width(200) self.assertEqual(box.width(), 200) box.height(-10) self.assertEqual(box.height(), -10) def test_set_box_size_must_be_numeric(self): box = BoxGraphic(10, 20, 100, 200) with self.assertRaises(TypeError): box.width("10") with self.assertRaises(TypeError): box.height("20") box.width(10.5) box.height(10.5) def test_box_center(self): box = BoxGraphic(10, 20, 100, 200) self.assertEqual(box.center(), (60, 120))
tests/test_boxes.py
from unittest import TestCase from omnicanvas.graphics import ShapeGraphic, BoxGraphic class BoxGraphicCreationTests(TestCase): def test_can_create_box_graphic(self): box = BoxGraphic(10, 20, 100, 200) self.assertIsInstance(box, ShapeGraphic) self.assertEqual(box._x, 10) self.assertEqual(box._y, 20) self.assertEqual(box._width, 100) self.assertEqual(box._height, 200) self.assertEqual(box._fill_color, "#FFFFFF") self.assertEqual(box._opacity, 1) self.assertEqual(box._line_width, 1) self.assertEqual(box._line_style, "-") self.assertEqual(box._line_color, "#000000") self.assertEqual(box._rotation, (0, 0, 0)) self.assertEqual(box._data, {}) def test_box_location_must_be_numeric(self): with self.assertRaises(TypeError): BoxGraphic("10", 20, 100, 200) with self.assertRaises(TypeError): BoxGraphic(10, "20", 100, 200) BoxGraphic(10.5, 20, 100, 200) BoxGraphic(10, 20.5, 100, 200) def test_box_dimensions_must_be_numeric(self): with self.assertRaises(TypeError): BoxGraphic(10, 20, "100", 200) with self.assertRaises(TypeError): BoxGraphic(10, 20, 100, "200") BoxGraphic(10, 20, 100.5, 200) BoxGraphic(10, 20, 100, 200.5) class BoxGraphicPropertyTests(TestCase): def test_basic_properties(self): box = BoxGraphic(10, 20, 100, 200) self.assertIs(box.x(), box._x) self.assertIs(box.y(), box._y) self.assertIs(box.width(), box._width) self.assertIs(box.height(), box._height) def test_can_set_location(self): box = BoxGraphic(10, 20, 100, 200) box.x(200) self.assertEqual(box.x(), 200) box.y(-10) self.assertEqual(box.y(), -10) def test_set_box_location_must_be_numeric(self): box = BoxGraphic(10, 20, 100, 200) with self.assertRaises(TypeError): box.x("10") with self.assertRaises(TypeError): box.y("20") box.x(10.5) box.y(10.5) def test_can_set_box_size(self): box = BoxGraphic(10, 20, 100, 200) box.width(200) self.assertEqual(box.width(), 200) box.height(-10) self.assertEqual(box.height(), -10) def test_set_box_size_must_be_numeric(self): box = BoxGraphic(10, 20, 100, 200) with self.assertRaises(TypeError): box.width("10") with self.assertRaises(TypeError): box.height("20") box.width(10.5) box.height(10.5) def test_box_center(self): box = BoxGraphic(10, 20, 100, 200) self.assertEqual(box.center(), (60, 120))
0.585694
0.647004
from _TFL import TFL from _MOM import MOM from _MOM._Attr.Type import * from _MOM._Attr import Attr from _MOM._Pred import Pred import _MOM._Meta.M_Link import _MOM.Entity _Ancestor_Essence = MOM.Id_Entity class _MOM_Link_ \ (_Ancestor_Essence, metaclass = MOM.Meta.M_Link) : """Root class for link-types of MOM meta object model.""" _real_name = "Link" entity_kind = "link" is_partial = True is_synthetic = False class _Attributes (_Ancestor_Essence._Attributes) : class left (_A_Link_Role_Left_, A_Link_Role_EB) : """Left role of association. Override to define `role_type`, ...""" # end class left # end class _Attributes @property def roles (self) : """Link roles as tuple of cooked values (subset of :attr:`epk`).""" return self.epk [:self.number_of_roles] # end def roles def _finish__init__ (self) : self.__super._finish__init__ () for role_cacher in self.auto_cache_roles : role_cacher (self, no_value = False) # end def def _destroy (self) : for role_cacher in self.auto_cache_roles : role_cacher (self, no_value = True) self.__super._destroy () # end def _destroy def _rename (self, new_epk, pkas_raw, pkas_ckd) : result = self.__super._rename (new_epk, pkas_raw, pkas_ckd) for role_cacher in self.auto_cache_roles : role_cacher (self, no_value = False) return result # end def _rename Link = _MOM_Link_ # end class _Ancestor_Essence = Link class Link1 (_Ancestor_Essence, metaclass = MOM.Meta.M_Link1) : """Common base class for essential unary links of MOM""" is_partial = True _UI_Spec_Defaults = dict \ ( show_in_admin = True ) class _Attributes (_Ancestor_Essence._Attributes) : _Ancestor = _Ancestor_Essence._Attributes class left (_Ancestor.left) : Kind_Mixins = (Attr.Init_Only_Mixin, ) # end class left # end class _Attributes # end class Link1 _Ancestor_Essence = Link class _MOM_Link_n_ \ (_Ancestor_Essence, metaclass = MOM.Meta.M_Link_n) : """Root class for link-types of MOM meta object model with more than 1 role.""" is_partial = True _real_name = "_Link_n_" class _Attributes (_Ancestor_Essence._Attributes) : class right (_A_Link_Role_Right_, A_Link_Role_EB) : """Right role of association. Override to define `role_type`, ...""" # end class right # end class _Attributes _Link_n_ = _MOM_Link_n_ # end class _Ancestor_Essence = _Link_n_ class Link2 (_Ancestor_Essence, metaclass = MOM.Meta.M_Link2) : """Common base class for essential binary links of MOM.""" is_partial = True # end class Link2 _Ancestor_Essence = _Link_n_ class Link3 (_Ancestor_Essence, metaclass = MOM.Meta.M_Link3) : """Common base class for essential ternary links of MOM.""" is_partial = True class _Attributes (_Ancestor_Essence._Attributes) : class middle (_A_Link_Role_Middle_, A_Link_Role_EB) : """Middle role of association. Override to define `role_type`, ...""" # end class middle # end class _Attributes # end class Link3 @TFL.Add_To_Class ("_Destroyed_Mixin_", Link1) class _Link1_Destroyed_Mixin_ \ ( MOM._Id_Entity_Destroyed_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link1_Destroyed ) : """Mixin triggering an exception on any attribute access to a destroyed Link1. """ # end class _Link1_Destroyed_Mixin_ @TFL.Add_To_Class ("_Destroyed_Mixin_", Link2) class _Link2_Destroyed_Mixin_ \ ( MOM._Id_Entity_Destroyed_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link2_Destroyed ) : """Mixin triggering an exception on any attribute access to a destroyed Link2. """ # end class _Link2_Destroyed_Mixin_ @TFL.Add_To_Class ("_Destroyed_Mixin_", Link3) class _Link3_Destroyed_Mixin_ \ ( MOM._Id_Entity_Destroyed_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link3_Destroyed ) : """Mixin triggering an exception on any attribute access to a destroyed Link3. """ # end class _Link3_Destroyed_Mixin_ @TFL.Add_To_Class ("_Reload_Mixin_", Link1) class _Link1_Reload_Mixin_ \ ( MOM._Id_Entity_Reload_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link1_Reload ) : """Mixin triggering a reload from the database on any attribute access.""" # end class _Link1_Reload_Mixin_ @TFL.Add_To_Class ("_Reload_Mixin_", Link2) class _Link2_Reload_Mixin_ \ ( MOM._Id_Entity_Reload_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link2_Reload ) : """Mixin triggering a reload from the database on any attribute access.""" # end class _Link2_Reload_Mixin_ @TFL.Add_To_Class ("_Reload_Mixin_", Link3) class _Link3_Reload_Mixin_ \ ( MOM._Id_Entity_Reload_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link3_Reload ) : """Mixin triggering a reload from the database on any attribute access.""" # end class _Link3_Reload_Mixin_ ### «text» ### start of documentation Link.__doc_attr_head__ = """ `MOM.Link` provides the framework for defining essential associations. It is based on :class:`~_MOM.Entity.Id_Entity`. An association models the relationship between two or more objects or links of essential classes. An association manages the set of links between the entities of the associated classes. Conceptually, each link is an independent entity. The class `Link` simultaneously models two concepts: - The class `Link` itself models the association, i.e., the collection of all links. The behavior of the association is provided by the methods and properties of the link manager :class:`E_Type_Manager<_MOM.E_Type_Manager.Link>`. - Each instance of `Link` models one specific link of the association. Each essential association is characterized by: - `arity`_ - `roles`_ - `multiplicity`_ .. _`arity`: **Arity** Arity defines how many objects one link comprises. A unary link relates the (attributes of the) link to one object. A binary association relates pairs of objects to each other, a ternary association relates triples of objects to each other, and so on. For each arity, a separate subclass exists, e.g., :class:`Link2`, :class:`Link3`, etc. Each arity-specific subclass has its own arity-specific metaclass, e.g., :class:`M_Link3` defines the behavior of :class:`Link3`. An essential association is modelled by a class that inherits from the proper arity-specific descendent of :class:`Link_EB`. * :class:`Link1` * :class:`Link2` * :class:`Link3` .. _`roles`: **Roles** Each object participating in a link of an association plays a specific `role`. A role is characterized by: * Role type: the type of essential object expected. * Role name (default `role_type.type_base_name.lower ()`). - If an association links objects of the same types in different roles to each other, at least one, preferably all of these roles need a unique role name that's different from the default role name. * Generic role name (e.g., `left` or `right`). * Role abbreviation (e.g., `l` or `r`). * Multiplicity constraint, if any. * Non-essential properties: - `link_ref_attr_name` (see `link-ref-attr-name`_) - `auto_rev_ref` (see `auto-rev-ref`_) Each role of a specific association is defined by a link-role attribute named by the generic role name. For a specific association, the link-role attribute * Must define :attr:`role_type` (unless that's already inherited). * May define :attr:`role_name`, multiplicity constraints (:attr:`max_links`) or any non-essential property of the role. For instance:: class Person_works_for_Company (Link2) : class _Attributes (Link2._Attributes) : class left (Link2._Attributes.left) : role_type = Person role_name = "employee" auto_rev_ref = True max_links = 1 ### Danger, <NAME> # end class left class right (Link2._Attributes.right) : role_type = Company role_name = "employer" # end class right # end class _Attributes .. _`multiplicity`: **Multiplicity** Multiplicity restricts how many links can exist for a single object in a specific role. Constraints on multiplicity frequently change over the lifetime of a software application. Common multiplicities (of binary associations) are: - 1 <--> 1 - 1 <--> n - n <--> m Associations with at least one role with multiplicity 1 could be implemented by an attribute of the respective object instead of an association. Any change of requirements might invalidate that implementation, though. Simple multiplicity constraints are implemented by defining `max_links` for the appropriate role. In this case, the `Link` class will enforce the constraint. .. _`link-ref-attr-name`: **Link-ref-attr-name** For each link-role, the metaclass of the link automatically creates a query attribute of type `A_Link_Ref_List` for the role-type that returns the links in which the object is referred to by that link-role. By default, the name of `A_Link_Ref_List` attributes is: - for :class:`Link1`, the `type_base_name` in lower case - for :class:`Link2`, the `role_name` of the other link-role - for :class:`Link3`, the `role_name` of the other link-roles joined by "__" This default can be overriden by defining the property `link_ref_attr_name` for the link-role; setting `link_ref_attr_name` to `Undef()` inhibits the creation of the `A_Link_Ref_List` attribute. Unless `link_ref_suffix` is set to `None` for the link-role, the name of the `A_Link_Ref_List` is then pluralized, assuming English rules for pluralization. .. _`auto-rev-ref`: **Auto-Rev-Ref** By specifying `auto_rev_ref` for one of the `roles` of an entity-based association, an attribute referring to the objects linked via this association is automagically added to another role of the association. `auto_rev_ref` can be set to one of the values: - `True`. This only works for binary associations.As it is the simplest case, it should be preferred over the other possibilities, if possible. - A string specifying the name of the auto-rev-ref attribute. """ __doc__ = """ """ future_features = """ DFC-Synthesis ------------- Some object models allow recursive structures of the form: - A container-like class `C` inherits from class `X`. `C` thus is substitutable for `X` and can participate in all associations defined for `X`. - An association `X_in_C` that defines a container-like association with the multiplicity constraint that each instance of `X` is restricted to a single link to `C`. In many such models, the instances of `X` linked to a specific container `c` should reflect the links `c` itself participates in. To avoid numerous redundant links, the module :mod:`~_MOM.DFC_Link` provides classes that allow the automatic synthesis of links derived from a container association. DFC-synthesis is specified for the association that needs synthetic `DFC_Links` by defining the property `dfc_synthesizer` (which must be an instance of a subclass of :class:`~_MOM.DFC_Link.DFC_Synthesizer`) for the role related to `X`. For instance, given `C`, `X`, and `X_in_C` as described above, DFC-synthesis for an association `X_has_P` would be defined like:: class X_has_P (Link2) : class _Attributes (Link2._Attributes) : class left (Link2._Attributes.left) : role_type = X dfc_synthesizer = MOM.DFC_Synthesizer_LL (X_in_C) # end class left class right (Link2._Attributes.right) : role_type = P # end class right # end class _Attributes """ if __name__ != "__main__" : MOM._Export ("*", "_Link_n_") ### __END__ MOM.Link
_MOM/Link.py
from _TFL import TFL from _MOM import MOM from _MOM._Attr.Type import * from _MOM._Attr import Attr from _MOM._Pred import Pred import _MOM._Meta.M_Link import _MOM.Entity _Ancestor_Essence = MOM.Id_Entity class _MOM_Link_ \ (_Ancestor_Essence, metaclass = MOM.Meta.M_Link) : """Root class for link-types of MOM meta object model.""" _real_name = "Link" entity_kind = "link" is_partial = True is_synthetic = False class _Attributes (_Ancestor_Essence._Attributes) : class left (_A_Link_Role_Left_, A_Link_Role_EB) : """Left role of association. Override to define `role_type`, ...""" # end class left # end class _Attributes @property def roles (self) : """Link roles as tuple of cooked values (subset of :attr:`epk`).""" return self.epk [:self.number_of_roles] # end def roles def _finish__init__ (self) : self.__super._finish__init__ () for role_cacher in self.auto_cache_roles : role_cacher (self, no_value = False) # end def def _destroy (self) : for role_cacher in self.auto_cache_roles : role_cacher (self, no_value = True) self.__super._destroy () # end def _destroy def _rename (self, new_epk, pkas_raw, pkas_ckd) : result = self.__super._rename (new_epk, pkas_raw, pkas_ckd) for role_cacher in self.auto_cache_roles : role_cacher (self, no_value = False) return result # end def _rename Link = _MOM_Link_ # end class _Ancestor_Essence = Link class Link1 (_Ancestor_Essence, metaclass = MOM.Meta.M_Link1) : """Common base class for essential unary links of MOM""" is_partial = True _UI_Spec_Defaults = dict \ ( show_in_admin = True ) class _Attributes (_Ancestor_Essence._Attributes) : _Ancestor = _Ancestor_Essence._Attributes class left (_Ancestor.left) : Kind_Mixins = (Attr.Init_Only_Mixin, ) # end class left # end class _Attributes # end class Link1 _Ancestor_Essence = Link class _MOM_Link_n_ \ (_Ancestor_Essence, metaclass = MOM.Meta.M_Link_n) : """Root class for link-types of MOM meta object model with more than 1 role.""" is_partial = True _real_name = "_Link_n_" class _Attributes (_Ancestor_Essence._Attributes) : class right (_A_Link_Role_Right_, A_Link_Role_EB) : """Right role of association. Override to define `role_type`, ...""" # end class right # end class _Attributes _Link_n_ = _MOM_Link_n_ # end class _Ancestor_Essence = _Link_n_ class Link2 (_Ancestor_Essence, metaclass = MOM.Meta.M_Link2) : """Common base class for essential binary links of MOM.""" is_partial = True # end class Link2 _Ancestor_Essence = _Link_n_ class Link3 (_Ancestor_Essence, metaclass = MOM.Meta.M_Link3) : """Common base class for essential ternary links of MOM.""" is_partial = True class _Attributes (_Ancestor_Essence._Attributes) : class middle (_A_Link_Role_Middle_, A_Link_Role_EB) : """Middle role of association. Override to define `role_type`, ...""" # end class middle # end class _Attributes # end class Link3 @TFL.Add_To_Class ("_Destroyed_Mixin_", Link1) class _Link1_Destroyed_Mixin_ \ ( MOM._Id_Entity_Destroyed_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link1_Destroyed ) : """Mixin triggering an exception on any attribute access to a destroyed Link1. """ # end class _Link1_Destroyed_Mixin_ @TFL.Add_To_Class ("_Destroyed_Mixin_", Link2) class _Link2_Destroyed_Mixin_ \ ( MOM._Id_Entity_Destroyed_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link2_Destroyed ) : """Mixin triggering an exception on any attribute access to a destroyed Link2. """ # end class _Link2_Destroyed_Mixin_ @TFL.Add_To_Class ("_Destroyed_Mixin_", Link3) class _Link3_Destroyed_Mixin_ \ ( MOM._Id_Entity_Destroyed_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link3_Destroyed ) : """Mixin triggering an exception on any attribute access to a destroyed Link3. """ # end class _Link3_Destroyed_Mixin_ @TFL.Add_To_Class ("_Reload_Mixin_", Link1) class _Link1_Reload_Mixin_ \ ( MOM._Id_Entity_Reload_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link1_Reload ) : """Mixin triggering a reload from the database on any attribute access.""" # end class _Link1_Reload_Mixin_ @TFL.Add_To_Class ("_Reload_Mixin_", Link2) class _Link2_Reload_Mixin_ \ ( MOM._Id_Entity_Reload_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link2_Reload ) : """Mixin triggering a reload from the database on any attribute access.""" # end class _Link2_Reload_Mixin_ @TFL.Add_To_Class ("_Reload_Mixin_", Link3) class _Link3_Reload_Mixin_ \ ( MOM._Id_Entity_Reload_Mixin_ , metaclass = MOM.Meta.M_E_Type_Link3_Reload ) : """Mixin triggering a reload from the database on any attribute access.""" # end class _Link3_Reload_Mixin_ ### «text» ### start of documentation Link.__doc_attr_head__ = """ `MOM.Link` provides the framework for defining essential associations. It is based on :class:`~_MOM.Entity.Id_Entity`. An association models the relationship between two or more objects or links of essential classes. An association manages the set of links between the entities of the associated classes. Conceptually, each link is an independent entity. The class `Link` simultaneously models two concepts: - The class `Link` itself models the association, i.e., the collection of all links. The behavior of the association is provided by the methods and properties of the link manager :class:`E_Type_Manager<_MOM.E_Type_Manager.Link>`. - Each instance of `Link` models one specific link of the association. Each essential association is characterized by: - `arity`_ - `roles`_ - `multiplicity`_ .. _`arity`: **Arity** Arity defines how many objects one link comprises. A unary link relates the (attributes of the) link to one object. A binary association relates pairs of objects to each other, a ternary association relates triples of objects to each other, and so on. For each arity, a separate subclass exists, e.g., :class:`Link2`, :class:`Link3`, etc. Each arity-specific subclass has its own arity-specific metaclass, e.g., :class:`M_Link3` defines the behavior of :class:`Link3`. An essential association is modelled by a class that inherits from the proper arity-specific descendent of :class:`Link_EB`. * :class:`Link1` * :class:`Link2` * :class:`Link3` .. _`roles`: **Roles** Each object participating in a link of an association plays a specific `role`. A role is characterized by: * Role type: the type of essential object expected. * Role name (default `role_type.type_base_name.lower ()`). - If an association links objects of the same types in different roles to each other, at least one, preferably all of these roles need a unique role name that's different from the default role name. * Generic role name (e.g., `left` or `right`). * Role abbreviation (e.g., `l` or `r`). * Multiplicity constraint, if any. * Non-essential properties: - `link_ref_attr_name` (see `link-ref-attr-name`_) - `auto_rev_ref` (see `auto-rev-ref`_) Each role of a specific association is defined by a link-role attribute named by the generic role name. For a specific association, the link-role attribute * Must define :attr:`role_type` (unless that's already inherited). * May define :attr:`role_name`, multiplicity constraints (:attr:`max_links`) or any non-essential property of the role. For instance:: class Person_works_for_Company (Link2) : class _Attributes (Link2._Attributes) : class left (Link2._Attributes.left) : role_type = Person role_name = "employee" auto_rev_ref = True max_links = 1 ### Danger, <NAME> # end class left class right (Link2._Attributes.right) : role_type = Company role_name = "employer" # end class right # end class _Attributes .. _`multiplicity`: **Multiplicity** Multiplicity restricts how many links can exist for a single object in a specific role. Constraints on multiplicity frequently change over the lifetime of a software application. Common multiplicities (of binary associations) are: - 1 <--> 1 - 1 <--> n - n <--> m Associations with at least one role with multiplicity 1 could be implemented by an attribute of the respective object instead of an association. Any change of requirements might invalidate that implementation, though. Simple multiplicity constraints are implemented by defining `max_links` for the appropriate role. In this case, the `Link` class will enforce the constraint. .. _`link-ref-attr-name`: **Link-ref-attr-name** For each link-role, the metaclass of the link automatically creates a query attribute of type `A_Link_Ref_List` for the role-type that returns the links in which the object is referred to by that link-role. By default, the name of `A_Link_Ref_List` attributes is: - for :class:`Link1`, the `type_base_name` in lower case - for :class:`Link2`, the `role_name` of the other link-role - for :class:`Link3`, the `role_name` of the other link-roles joined by "__" This default can be overriden by defining the property `link_ref_attr_name` for the link-role; setting `link_ref_attr_name` to `Undef()` inhibits the creation of the `A_Link_Ref_List` attribute. Unless `link_ref_suffix` is set to `None` for the link-role, the name of the `A_Link_Ref_List` is then pluralized, assuming English rules for pluralization. .. _`auto-rev-ref`: **Auto-Rev-Ref** By specifying `auto_rev_ref` for one of the `roles` of an entity-based association, an attribute referring to the objects linked via this association is automagically added to another role of the association. `auto_rev_ref` can be set to one of the values: - `True`. This only works for binary associations.As it is the simplest case, it should be preferred over the other possibilities, if possible. - A string specifying the name of the auto-rev-ref attribute. """ __doc__ = """ """ future_features = """ DFC-Synthesis ------------- Some object models allow recursive structures of the form: - A container-like class `C` inherits from class `X`. `C` thus is substitutable for `X` and can participate in all associations defined for `X`. - An association `X_in_C` that defines a container-like association with the multiplicity constraint that each instance of `X` is restricted to a single link to `C`. In many such models, the instances of `X` linked to a specific container `c` should reflect the links `c` itself participates in. To avoid numerous redundant links, the module :mod:`~_MOM.DFC_Link` provides classes that allow the automatic synthesis of links derived from a container association. DFC-synthesis is specified for the association that needs synthetic `DFC_Links` by defining the property `dfc_synthesizer` (which must be an instance of a subclass of :class:`~_MOM.DFC_Link.DFC_Synthesizer`) for the role related to `X`. For instance, given `C`, `X`, and `X_in_C` as described above, DFC-synthesis for an association `X_has_P` would be defined like:: class X_has_P (Link2) : class _Attributes (Link2._Attributes) : class left (Link2._Attributes.left) : role_type = X dfc_synthesizer = MOM.DFC_Synthesizer_LL (X_in_C) # end class left class right (Link2._Attributes.right) : role_type = P # end class right # end class _Attributes """ if __name__ != "__main__" : MOM._Export ("*", "_Link_n_") ### __END__ MOM.Link
0.773559
0.171338
import os import time import cfg.glob import db.dml import pypandoc import utils # ----------------------------------------------------------------------------- # Global variables. # ----------------------------------------------------------------------------- PANDOC_PDF_ENGINE_LULATEX: str = "lulatex" PANDOC_PDF_ENGINE_XELATEX: str = "xelatex" # ----------------------------------------------------------------------------- # Convert non-pdf documents to pdf files (step: n_2_p). # ----------------------------------------------------------------------------- def convert_non_pdf_2_pdf() -> None: """Convert non-pdf documents to pdf files. TBD """ cfg.glob.logger.debug(cfg.glob.LOGGER_START) dbt = db.dml.dml_prepare(cfg.glob.DBT_DOCUMENT) utils.reset_statistics_total() with cfg.glob.db_orm_engine.connect() as conn: rows = db.dml.select_document(conn, dbt, cfg.glob.DOCUMENT_STEP_PANDOC) for row in rows: cfg.glob.start_time_document = time.perf_counter_ns() utils.start_document_processing( document=row, ) convert_non_pdf_2_pdf_file() # Document successfully converted to pdf format duration_ns = utils.finalize_file_processing() if cfg.glob.setup.is_verbose: utils.progress_msg( f"Duration: {round(duration_ns / 1000000000, 2):6.2f} s - " f"Document: {cfg.glob.document_id:6d} " f"[{db.dml.select_document_file_name_id(cfg.glob.document_id)}]" ) conn.close() utils.show_statistics_total() cfg.glob.logger.debug(cfg.glob.LOGGER_END) # ----------------------------------------------------------------------------- # Convert a non-pdf document to a pdf file (step: n_2_p). # ----------------------------------------------------------------------------- def convert_non_pdf_2_pdf_file() -> None: """Convert a non-pdf document to a pdf file.""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) source_file_name, target_file_name = utils.prepare_file_names(cfg.glob.DOCUMENT_FILE_TYPE_PDF) if os.path.exists(target_file_name): db.dml.update_document_error( document_id=cfg.glob.document_id, error_code=cfg.glob.DOCUMENT_ERROR_CODE_REJ_FILE_DUPL, error_msg=cfg.glob.ERROR_31_903.replace("{file_name}", target_file_name), ) return # Convert the document extra_args = [ f"--pdf-engine={PANDOC_PDF_ENGINE_XELATEX}", "-V", f"lang:{cfg.glob.languages_pandoc[cfg.glob.document_language_id]}", ] try: pypandoc.convert_file( source_file_name, cfg.glob.DOCUMENT_FILE_TYPE_PDF, extra_args=extra_args, outputfile=target_file_name, ) utils.prepare_document_4_next_step( next_file_type=cfg.glob.DOCUMENT_FILE_TYPE_PDF, next_step=cfg.glob.DOCUMENT_STEP_PDFLIB, ) cfg.glob.document_child_file_name = cfg.glob.document_stem_name + "." + cfg.glob.DOCUMENT_FILE_TYPE_PDF cfg.glob.document_child_stem_name = cfg.glob.document_stem_name db.dml.insert_document_child() utils.delete_auxiliary_file(source_file_name) except RuntimeError as err: db.dml.update_document_error( document_id=cfg.glob.document_id, error_code=cfg.glob.DOCUMENT_ERROR_CODE_REJ_PDF2IMAGE, error_msg=cfg.glob.ERROR_31_902.replace("{file_name}", source_file_name).replace( "{error_msg}", str(str(err).encode("utf-8")) ), ) cfg.glob.logger.debug(cfg.glob.LOGGER_END)
src/dcr/pp/pandoc_dcr.py
import os import time import cfg.glob import db.dml import pypandoc import utils # ----------------------------------------------------------------------------- # Global variables. # ----------------------------------------------------------------------------- PANDOC_PDF_ENGINE_LULATEX: str = "lulatex" PANDOC_PDF_ENGINE_XELATEX: str = "xelatex" # ----------------------------------------------------------------------------- # Convert non-pdf documents to pdf files (step: n_2_p). # ----------------------------------------------------------------------------- def convert_non_pdf_2_pdf() -> None: """Convert non-pdf documents to pdf files. TBD """ cfg.glob.logger.debug(cfg.glob.LOGGER_START) dbt = db.dml.dml_prepare(cfg.glob.DBT_DOCUMENT) utils.reset_statistics_total() with cfg.glob.db_orm_engine.connect() as conn: rows = db.dml.select_document(conn, dbt, cfg.glob.DOCUMENT_STEP_PANDOC) for row in rows: cfg.glob.start_time_document = time.perf_counter_ns() utils.start_document_processing( document=row, ) convert_non_pdf_2_pdf_file() # Document successfully converted to pdf format duration_ns = utils.finalize_file_processing() if cfg.glob.setup.is_verbose: utils.progress_msg( f"Duration: {round(duration_ns / 1000000000, 2):6.2f} s - " f"Document: {cfg.glob.document_id:6d} " f"[{db.dml.select_document_file_name_id(cfg.glob.document_id)}]" ) conn.close() utils.show_statistics_total() cfg.glob.logger.debug(cfg.glob.LOGGER_END) # ----------------------------------------------------------------------------- # Convert a non-pdf document to a pdf file (step: n_2_p). # ----------------------------------------------------------------------------- def convert_non_pdf_2_pdf_file() -> None: """Convert a non-pdf document to a pdf file.""" cfg.glob.logger.debug(cfg.glob.LOGGER_START) source_file_name, target_file_name = utils.prepare_file_names(cfg.glob.DOCUMENT_FILE_TYPE_PDF) if os.path.exists(target_file_name): db.dml.update_document_error( document_id=cfg.glob.document_id, error_code=cfg.glob.DOCUMENT_ERROR_CODE_REJ_FILE_DUPL, error_msg=cfg.glob.ERROR_31_903.replace("{file_name}", target_file_name), ) return # Convert the document extra_args = [ f"--pdf-engine={PANDOC_PDF_ENGINE_XELATEX}", "-V", f"lang:{cfg.glob.languages_pandoc[cfg.glob.document_language_id]}", ] try: pypandoc.convert_file( source_file_name, cfg.glob.DOCUMENT_FILE_TYPE_PDF, extra_args=extra_args, outputfile=target_file_name, ) utils.prepare_document_4_next_step( next_file_type=cfg.glob.DOCUMENT_FILE_TYPE_PDF, next_step=cfg.glob.DOCUMENT_STEP_PDFLIB, ) cfg.glob.document_child_file_name = cfg.glob.document_stem_name + "." + cfg.glob.DOCUMENT_FILE_TYPE_PDF cfg.glob.document_child_stem_name = cfg.glob.document_stem_name db.dml.insert_document_child() utils.delete_auxiliary_file(source_file_name) except RuntimeError as err: db.dml.update_document_error( document_id=cfg.glob.document_id, error_code=cfg.glob.DOCUMENT_ERROR_CODE_REJ_PDF2IMAGE, error_msg=cfg.glob.ERROR_31_902.replace("{file_name}", source_file_name).replace( "{error_msg}", str(str(err).encode("utf-8")) ), ) cfg.glob.logger.debug(cfg.glob.LOGGER_END)
0.394201
0.174833
from email.MIMEText import MIMEText import logging import os import re import smtplib import sys import urllib import pyauto_functional import pyauto sys.path.append(os.path.join(pyauto.PyUITest.DataDir(), 'pyauto_private', 'chromeos', 'network')) from gsm_sim_info import SIM, PROVIDER_TXT_SERVER class ChromeosTxtMsgSanity(pyauto.PyUITest): """Tests for ChromeOS text message handling""" def _SendText(self, mail_server, sender, phone_number, mobile_provider, msg): """Sends a text message to a specific phone Args: mail_server: An SMTP instance. sender: Sender's email address. phone_number: The phone number the txt message is directed to. mobile_provider: A cellular provider defined in gsm_sim_info.PROVIDER_TXT_SERVER msg: The message to be sent. """ recipient = ('%s@%s' % (phone_number, PROVIDER_TXT_SERVER[mobile_provider])) self._SendMail(mail_server, sender, recipient, None, msg) def _SendMail(self, mail_server, sender, recipients, msg_subject, msg_body): """Sends an email using the provided smtp connection Args: mail_server: An SMTP instace. sender: Senders email address. recipients: Recipients email address. msg_subject: The subject line of the email. msg_body: The body of the email. """ msg = MIMEText(msg_body) msg['To'] = recipients msg['From'] = sender if msg_subject: msg['Subject'] = msg_subject mail_server.sendmail(sender, recipients, msg.as_string()) def _GetGmailServerInstance(self, email, password): """Creates an SMTP connection with the gmail mail server Args: email: A gmail address. password: The password for the gmail address. Returns: An SMTP connection instance. """ mail_server = smtplib.SMTP('smtp.gmail.com', 587) mail_server.starttls() mail_server.ehlo() mail_server.login(email, password) return mail_server def _GetIMSI(self): """Obtains the IMSI by running modem status Returns: IMSI of device """ modem_status = os.popen('modem status').read() imsi = re.search('IMSI:\s(\d+)', modem_status) if not imsi: raise Exception('GSM Modem not detected in device') return imsi.groups()[0] def _GetSIMInfo(self): """Returns information necessary to send messages Returns: A dictionary with the following format { 'mdn' : <phone number>, 'carrier': <carrier name> } """ imsi = self._GetIMSI() sim_info = SIM.get(imsi, {}) if not sim_info: raise Exception('Phone number for sim with IMSI=%s is not ' 'recognized within config file' % imsi) return sim_info def setUp(self): # Connect to cellular service if not already connected. pyauto.PyUITest.setUp(self) connected_cellular = self.NetworkScan().get('connected_cellular') if not connected_cellular: self.ConnectToCellularNetwork() if not self.NetworkScan().get('connected_cellular'): raise Exception('Could not connect to cellular service.') else: logging.debug('Already connected to cellular service %s' % connected_cellular) # Obtain sender, recipient, and SMTP instance. self.credentials = self.GetPrivateInfo()['test_account_with_smtp'] self.sim = self._GetSIMInfo() self.mail_server = self._GetGmailServerInstance( self.credentials['username'], self.credentials['password']) def tearDown(self): self.DisconnectFromCellularNetwork() self.mail_server.close() for window in range(len(self.GetActiveNotifications())): self.CloseNotification(window) pyauto.PyUITest.tearDown(self) def testTxtMsgNotification(self): """Notifications are displayed for text messages""" msg = 'This is the text message' self._SendText(self.mail_server, self.credentials['username'], self.sim['mdn'], self.sim['carrier'], msg) self.WaitForNotificationCount(1) notification_result = self.GetActiveNotifications()[0]['content_url'] self.assertTrue(re.search(urllib.pathname2url(msg), notification_result), 'Invalid message was displayed. ' 'Expected "%s" but did not find it"' % msg) def testLongTxtMsgNotification(self): """Notifications are displayed for long (>160 char) text messages.""" long_msg = 'This is a really long message with spaces. Testing to '\ 'make sure that chromeos is able to catch it and '\ 'create a notifications for this message.' self._SendText(self.mail_server, self.credentials['username'], self.sim['mdn'], self.sim['carrier'], long_msg) self.WaitForNotificationCount(1) # GetActiveNotifications throws an exception if the text message never # arrives. txt_msg = self.GetActiveNotifications()[0] txt_msg = txt_windows[0]['content_url'] self.assertTrue(re.search(urllib.pathname2url(long_msg), txt_msg), 'Invalid message was displayed. ' 'Expected "%s" but did not find it"' % long_msg) if __name__ == '__main__': pyauto_functional.Main()
chrome/test/functional/chromeos_txt_msg_functional.py
from email.MIMEText import MIMEText import logging import os import re import smtplib import sys import urllib import pyauto_functional import pyauto sys.path.append(os.path.join(pyauto.PyUITest.DataDir(), 'pyauto_private', 'chromeos', 'network')) from gsm_sim_info import SIM, PROVIDER_TXT_SERVER class ChromeosTxtMsgSanity(pyauto.PyUITest): """Tests for ChromeOS text message handling""" def _SendText(self, mail_server, sender, phone_number, mobile_provider, msg): """Sends a text message to a specific phone Args: mail_server: An SMTP instance. sender: Sender's email address. phone_number: The phone number the txt message is directed to. mobile_provider: A cellular provider defined in gsm_sim_info.PROVIDER_TXT_SERVER msg: The message to be sent. """ recipient = ('%s@%s' % (phone_number, PROVIDER_TXT_SERVER[mobile_provider])) self._SendMail(mail_server, sender, recipient, None, msg) def _SendMail(self, mail_server, sender, recipients, msg_subject, msg_body): """Sends an email using the provided smtp connection Args: mail_server: An SMTP instace. sender: Senders email address. recipients: Recipients email address. msg_subject: The subject line of the email. msg_body: The body of the email. """ msg = MIMEText(msg_body) msg['To'] = recipients msg['From'] = sender if msg_subject: msg['Subject'] = msg_subject mail_server.sendmail(sender, recipients, msg.as_string()) def _GetGmailServerInstance(self, email, password): """Creates an SMTP connection with the gmail mail server Args: email: A gmail address. password: The password for the gmail address. Returns: An SMTP connection instance. """ mail_server = smtplib.SMTP('smtp.gmail.com', 587) mail_server.starttls() mail_server.ehlo() mail_server.login(email, password) return mail_server def _GetIMSI(self): """Obtains the IMSI by running modem status Returns: IMSI of device """ modem_status = os.popen('modem status').read() imsi = re.search('IMSI:\s(\d+)', modem_status) if not imsi: raise Exception('GSM Modem not detected in device') return imsi.groups()[0] def _GetSIMInfo(self): """Returns information necessary to send messages Returns: A dictionary with the following format { 'mdn' : <phone number>, 'carrier': <carrier name> } """ imsi = self._GetIMSI() sim_info = SIM.get(imsi, {}) if not sim_info: raise Exception('Phone number for sim with IMSI=%s is not ' 'recognized within config file' % imsi) return sim_info def setUp(self): # Connect to cellular service if not already connected. pyauto.PyUITest.setUp(self) connected_cellular = self.NetworkScan().get('connected_cellular') if not connected_cellular: self.ConnectToCellularNetwork() if not self.NetworkScan().get('connected_cellular'): raise Exception('Could not connect to cellular service.') else: logging.debug('Already connected to cellular service %s' % connected_cellular) # Obtain sender, recipient, and SMTP instance. self.credentials = self.GetPrivateInfo()['test_account_with_smtp'] self.sim = self._GetSIMInfo() self.mail_server = self._GetGmailServerInstance( self.credentials['username'], self.credentials['password']) def tearDown(self): self.DisconnectFromCellularNetwork() self.mail_server.close() for window in range(len(self.GetActiveNotifications())): self.CloseNotification(window) pyauto.PyUITest.tearDown(self) def testTxtMsgNotification(self): """Notifications are displayed for text messages""" msg = 'This is the text message' self._SendText(self.mail_server, self.credentials['username'], self.sim['mdn'], self.sim['carrier'], msg) self.WaitForNotificationCount(1) notification_result = self.GetActiveNotifications()[0]['content_url'] self.assertTrue(re.search(urllib.pathname2url(msg), notification_result), 'Invalid message was displayed. ' 'Expected "%s" but did not find it"' % msg) def testLongTxtMsgNotification(self): """Notifications are displayed for long (>160 char) text messages.""" long_msg = 'This is a really long message with spaces. Testing to '\ 'make sure that chromeos is able to catch it and '\ 'create a notifications for this message.' self._SendText(self.mail_server, self.credentials['username'], self.sim['mdn'], self.sim['carrier'], long_msg) self.WaitForNotificationCount(1) # GetActiveNotifications throws an exception if the text message never # arrives. txt_msg = self.GetActiveNotifications()[0] txt_msg = txt_windows[0]['content_url'] self.assertTrue(re.search(urllib.pathname2url(long_msg), txt_msg), 'Invalid message was displayed. ' 'Expected "%s" but did not find it"' % long_msg) if __name__ == '__main__': pyauto_functional.Main()
0.511717
0.105625