content
stringlengths
5
1.05M
import random def add_or_subtract(number): if (((number + 1) % 3) == 0): print(int(number), ' 1') number += 1 elif (((number - 1) % 3) == 0): print(int(number), ' -1') number -= 1 return number def play(number): if (number == 1): print(int(number)) elif ((number % 3) == 0): print(int(number), ' 0') play(number / 3) else: play(add_or_subtract(number)) def represents_int(s): try: int(s) return True except ValueError: return False def init(): while True: print('Input a number to start the game!') print('> ', end="") number = input() if (represents_int(number)): number = int(number) break play(number) init()
#! /usr/bin/env python import nmrglue as ng # read in the Agilent data dic, data = ng.varian.read("agilent_2d") # Set the spectral parameters udic = ng.varian.guess_udic(dic, data) # Direct dimension # Indirect dimension udic[1]['size'] = 1500 ; udic[0]['size'] = 332 udic[1]['complex'] = True ; udic[0]['complex'] = True udic[1]['encoding'] = 'direct' ; udic[0]['encoding'] = 'states' udic[1]['sw'] = 50000.0 ; udic[0]['sw'] = 5555.556 udic[1]['obs'] = 125.691 ; udic[0]['obs'] = 50.648 udic[1]['car'] = 55.0 * 125.691; udic[0]['car'] = 120.0 * 50.648 udic[1]['label'] = '13C' ; udic[0]['label'] = '15N' # create the converter object and initialize with Agilent data C = ng.convert.converter() C.from_varian(dic, data, udic) # create NMRPipe data and then write it out ng.pipe.write("2d_pipe.fid", *C.to_pipe(), overwrite=True)
import click import transaction import zope.sqlalchemy import os from models.sql import User from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, configure_mappers from sqlalchemy.pool import NullPool DBSession = scoped_session(sessionmaker()) def get_dbsession(transaction_manager): zope.sqlalchemy.register(DBSession, transaction_manager=transaction_manager) return DBSession engine = create_engine( os.getenv("DATABASE_URL"), poolclass=NullPool, ) DBSession.configure(bind=engine) configure_mappers() @click.command() @click.option("--user-id", "-id", type=int, help="user id") def get_user(user_id=None): with transaction.manager: session = get_dbsession(transaction.manager) if user_id: user = session.query(User).get(user_id) click.echo(user) return click.echo([str(u) for u in session.query(User)]) if __name__ == "__main__": get_user()
from CC3501Utils import * import math as m class Player(Figura): #inicializador def __init__(self,pos: Vector,rgb=(1.0,1.0,51.0/255),vida=True,numero=1): self.vida=vida#true si esta vivo self.centro=Vector(pos.x+(53.0/2),pos.y+(46.0/2)) self.numero=numero if self.numero==1: self.color_camisa=(1.0,1.0,1.0) if self.numero==2: self.color_camisa=(43.0/255,185/255,0.0) super().__init__(pos,rgb) def figura(self): """ Dibuja al modelo en pantalla :return: None """ (r,g,b)=self.color (cr,cg,cb)=self.color_camisa #discretizacion ################# ###Homero (P1)### ################# if self.numero==1: dx = 53.0 / 16 dy = 46.0 / 20 ###################### ####contorno negro#### ###################### glColor3f(0.0, 0.0, 0.0) # torso glBegin(GL_POLYGON) glVertex2f(8 * dx, 8 * dy) glVertex2f(8 * dx, 19 * dy) glVertex2f(11 * dx, 19 * dy) glVertex2f(11 * dx, 18 * dy) glVertex2f(12 * dx, 18 * dy) glVertex2f(12 * dx, 16 * dy) glVertex2f(13 * dx, 16 * dy) glVertex2f(13 * dx, 12 * dy) glVertex2f(14 * dx, 12 * dy) glVertex2f(14 * dx, 11 * dy) glVertex2f(15 * dx, 11 * dy) glVertex2f(15 * dx, 8 * dy) glEnd() glBegin(GL_POLYGON) glVertex2f(8 * dx, 8 * dy) glVertex2f(8 * dx, 19 * dy) glVertex2f(5 * dx, 19 * dy) glVertex2f(5 * dx, 18 * dy) glVertex2f(4 * dx, 18 * dy) glVertex2f(4 * dx, 16 * dy) glVertex2f(3 * dx, 16 * dy) glVertex2f(3 * dx, 12 * dy) glVertex2f(2 * dx, 12 * dy) glVertex2f(2 * dx, 11 * dy) glVertex2f(dx, 11 * dy) glVertex2f(dx, 8 * dy) glEnd() # ---piernas--- glBegin(GL_QUADS) glVertex2f(8 * dx, 8 * dy) glVertex2f(12 * dx, 8 * dy) glVertex2f(12 * dx, 2 * dy) glVertex2f(8 * dx, 2 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(8 * dx, 8 * dy) glVertex2f(4 * dx, 8 * dy) glVertex2f(4 * dx, 2 * dy) glVertex2f(8 * dx, 2 * dy) glEnd() # los que faltan (detalles) glBegin(GL_QUADS) glVertex2f(5 * dx, dy) glVertex2f(5 * dx, 2 * dy) glVertex2f(7 * dx, 2 * dy) glVertex2f(7 * dx, dy) glEnd() glBegin(GL_QUADS) glVertex2f(9 * dx, dy) glVertex2f(9 * dx, 2 * dy) glVertex2f(11 * dx, 2 * dy) glVertex2f(11 * dx, dy) glEnd() glBegin(GL_QUADS) glVertex2f(2 * dx, 7 * dy) glVertex2f(2 * dx, 8 * dy) glVertex2f(4 * dx, 8 * dy) glVertex2f(4 * dx, 7 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(12 * dx, 7 * dy) glVertex2f(12 * dx, 8 * dy) glVertex2f(14 * dx, 8 * dy) glVertex2f(14 * dx, 7 * dy) glEnd() glColor3f(138.0 / 255, 138.0 / 255, 138.0 / 255) glBegin(GL_QUADS) glVertex2f(3 * dx, 13 * dy) glVertex2f(3 * dx, 14 * dy) glVertex2f(4 * dx, 14 * dy) glVertex2f(4 * dx, 13 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(12 * dx, 13 * dy) glVertex2f(12 * dx, 14 * dy) glVertex2f(13 * dx, 14 * dy) glVertex2f(13 * dx, 13 * dy) glEnd() # -------------------- ####figura#### # zapatos glColor3f(0.2, 0.2, 0.2) glBegin(GL_QUADS) glVertex2f(5 * dx, 2 * dy) glVertex2f(5 * dx, 3 * dy) glVertex2f(7 * dx, 3 * dy) glVertex2f(7 * dx, 2 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(9 * dx, 2 * dy) glVertex2f(9 * dx, 3 * dy) glVertex2f(11 * dx, 3 * dy) glVertex2f(11 * dx, 2 * dy) glEnd() # pantalones glColor3f(75.0 / 255, 146.0 / 255, 226.0 / 255) glBegin(GL_QUADS) glVertex2f(5 * dx, 3 * dy) glVertex2f(5 * dx, 6 * dy) glVertex2f(7 * dx, 6 * dy) glVertex2f(7 * dx, 3 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(9 * dx, 3 * dy) glVertex2f(9 * dx, 6 * dy) glVertex2f(11 * dx, 6 * dy) glVertex2f(11 * dx, 3 * dy) glEnd() ###camisa### glColor3f(cr,cg,cb) glBegin(GL_QUADS) glVertex2f(5 * dx, 6 * dy) glVertex2f(5 * dx, 10 * dy) glVertex2f(11 * dx, 10 * dy) glVertex2f(11 * dx, 6 * dy) glEnd() # ---hombro derecho--- glBegin(GL_QUADS) glVertex2f(2 * dx, 10 * dy) glVertex2f(2 * dx, 11 * dy) glVertex2f(3 * dx, 11 * dy) glVertex2f(3 * dx, 10 * dy) glEnd() glBegin(GL_POLYGON) glVertex2f(3 * dx, 10 * dy) glVertex2f(3 * dx, 12 * dy) glVertex2f(5 * dx, 12 * dy) glVertex2f(5 * dx, 11 * dy) glVertex2f(6 * dx, 11 * dy) glVertex2f(6 * dx, 10 * dy) glEnd() # ---izquierdo--- glBegin(GL_QUADS) glVertex2f(10 * dx, 10 * dy) glVertex2f(10 * dx, 11 * dy) glVertex2f(11 * dx, 11 * dy) glVertex2f(11 * dx, 10 * dy) glEnd() glBegin(GL_POLYGON) glVertex2f(11 * dx, 10 * dy) glVertex2f(11 * dx, 12 * dy) glVertex2f(13 * dx, 12 * dy) glVertex2f(13 * dx, 11 * dy) glVertex2f(14 * dx, 11 * dy) glVertex2f(14 * dx, 10 * dy) glEnd() # piel glColor3f(r, g, b) # ---Manos--- glBegin(GL_QUADS) glVertex2f(2 * dx, 8 * dy) glVertex2f(2 * dx, 10 * dy) glVertex2f(4 * dx, 10 * dy) glVertex2f(4 * dx, 8 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(12 * dx, 8 * dy) glVertex2f(12 * dx, 10 * dy) glVertex2f(14 * dx, 10 * dy) glVertex2f(14 * dx, 8 * dy) glEnd() #---cabeza--- #nariz glBegin(GL_QUADS) glVertex2f(7*dx,13*dy) glVertex2f(7*dx,14*dy) glVertex2f(9*dx,14*dy) glVertex2f(9*dx,13*dy) glEnd() #laterales glBegin(GL_QUADS) glVertex2f(5*dx,12*dy) glVertex2f(5*dx,14*dy) glVertex2f(6*dx,14*dy) glVertex2f(6*dx,12*dy) glEnd() glBegin(GL_QUADS) glVertex2f(10 * dx, 12 * dy) glVertex2f(10 * dx, 14 * dy) glVertex2f(11 * dx, 14 * dy) glVertex2f(11 * dx, 12 * dy) glEnd() #frente glBegin(GL_QUADS) glVertex2f(5*dx,14*dy) glVertex2f(5*dx,18*dy) glVertex2f(11*dx,18*dy) glVertex2f(11*dx,14*dy) glEnd() #orejas glBegin(GL_QUADS) glVertex2f(4*dx,14*dy) glVertex2f(4*dx,15*dy) glVertex2f(5*dx,15*dy) glVertex2f(5*dx,14*dy) glEnd() glBegin(GL_QUADS) glVertex2f(11 * dx, 14 * dy) glVertex2f(11 * dx, 15 * dy) glVertex2f(12 * dx, 15 * dy) glVertex2f(12 * dx, 14 * dy) glEnd() # ---barba--- glColor3f(171.0/255,82.0/255,4.0/255) glBegin(GL_QUADS) glVertex2f(5*dx,11*dy) glVertex2f(5*dx,12*dy) glVertex2f(10*dx,12*dy) glVertex2f(10*dx,11*dy) glEnd() glBegin(GL_QUADS) glVertex2f(7*dx,12*dy) glVertex2f(7*dx,13*dy) glVertex2f(9*dx,13*dy) glVertex2f(9*dx,12*dy) glEnd() ################ ###Marge (P2)### ################ if self.numero==2: dx=53.0/16 dy=46.0/24 ############## ###contorno### ############## glColor3f(0.0, 0.0, 0.0) # torso glBegin(GL_POLYGON) glVertex2f(8 * dx, 8 * dy) glVertex2f(8 * dx, 23 * dy) glVertex2f(11 * dx, 23 * dy) glVertex2f(11 * dx, 22 * dy) glVertex2f(12 * dx, 22 * dy) glVertex2f(12 * dx, 21 * dy) glVertex2f(13 * dx, 21 * dy) glVertex2f(13 * dx, 12 * dy) glVertex2f(14 * dx, 12 * dy) glVertex2f(14 * dx, 11 * dy) glVertex2f(15 * dx, 11 * dy) glVertex2f(15 * dx, 8 * dy) glEnd() glBegin(GL_POLYGON) glVertex2f(8 * dx, 8 * dy) glVertex2f(8 * dx, 23 * dy) glVertex2f(5 * dx, 23 * dy) glVertex2f(5 * dx, 22 * dy) glVertex2f(4 * dx, 22 * dy) glVertex2f(4 * dx, 21 * dy) glVertex2f(3 * dx, 21 * dy) glVertex2f(3 * dx, 12 * dy) glVertex2f(2 * dx, 12 * dy) glVertex2f(2 * dx, 11 * dy) glVertex2f(dx, 11 * dy) glVertex2f(dx, 8 * dy) glEnd() # ---piernas--- glBegin(GL_QUADS) glVertex2f(8 * dx, 8 * dy) glVertex2f(12 * dx, 8 * dy) glVertex2f(12 * dx, 2 * dy) glVertex2f(8 * dx, 2 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(8 * dx, 8 * dy) glVertex2f(4 * dx, 8 * dy) glVertex2f(4 * dx, 2 * dy) glVertex2f(8 * dx, 2 * dy) glEnd() # los que faltan (detalles) glBegin(GL_QUADS) glVertex2f(5 * dx, dy) glVertex2f(5 * dx, 2 * dy) glVertex2f(7 * dx, 2 * dy) glVertex2f(7 * dx, dy) glEnd() glBegin(GL_QUADS) glVertex2f(9 * dx, dy) glVertex2f(9 * dx, 2 * dy) glVertex2f(11 * dx, 2 * dy) glVertex2f(11 * dx, dy) glEnd() glBegin(GL_QUADS) glVertex2f(2 * dx, 7 * dy) glVertex2f(2 * dx, 8 * dy) glVertex2f(4 * dx, 8 * dy) glVertex2f(4 * dx, 7 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(12 * dx, 7 * dy) glVertex2f(12 * dx, 8 * dy) glVertex2f(14 * dx, 8 * dy) glVertex2f(14 * dx, 7 * dy) glEnd() glColor3f(138.0 / 255, 138.0 / 255, 138.0 / 255) glBegin(GL_QUADS) glVertex2f(3 * dx, 13 * dy) glVertex2f(3 * dx, 14 * dy) glVertex2f(4 * dx, 14 * dy) glVertex2f(4 * dx, 13 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(12 * dx, 13 * dy) glVertex2f(12 * dx, 14 * dy) glVertex2f(13 * dx, 14 * dy) glVertex2f(13 * dx, 13 * dy) glEnd() ############ ###figura### ############ #---zapatos---# glColor3f(235.0/255, 0.0, 0.0) glBegin(GL_QUADS) glVertex2f(5 * dx, 2 * dy) glVertex2f(5 * dx, 3 * dy) glVertex2f(7 * dx, 3 * dy) glVertex2f(7 * dx, 2 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(9 * dx, 2 * dy) glVertex2f(9 * dx, 3 * dy) glVertex2f(11 * dx, 3 * dy) glVertex2f(11 * dx, 2 * dy) glEnd() #---vestido---# glColor3f(cr,cg,cb) glBegin(GL_QUADS) glVertex2f(5*dx,3*dy) glVertex2f(5*dx,10*dy) glVertex2f(11*dx,10*dy) glVertex2f(11*dx,3*dy) glEnd() # ---hombro derecho--- # piel glColor3f(r, g, b) glBegin(GL_QUADS) glVertex2f(2 * dx, 10 * dy) glVertex2f(2 * dx, 11 * dy) glVertex2f(3 * dx, 11 * dy) glVertex2f(3 * dx, 10 * dy) glEnd() glBegin(GL_POLYGON) glVertex2f(3 * dx, 10 * dy) glVertex2f(3 * dx, 12 * dy) glVertex2f(5 * dx, 12 * dy) glVertex2f(5 * dx, 11 * dy) glVertex2f(6 * dx, 11 * dy) glVertex2f(6 * dx, 10 * dy) glEnd() # ---izquierdo--- glBegin(GL_QUADS) glVertex2f(10 * dx, 10 * dy) glVertex2f(10 * dx, 11 * dy) glVertex2f(11 * dx, 11 * dy) glVertex2f(11 * dx, 10 * dy) glEnd() glBegin(GL_POLYGON) glVertex2f(11 * dx, 10 * dy) glVertex2f(11 * dx, 12 * dy) glVertex2f(13 * dx, 12 * dy) glVertex2f(13 * dx, 11 * dy) glVertex2f(14 * dx, 11 * dy) glVertex2f(14 * dx, 10 * dy) glEnd() # ---Manos--- glBegin(GL_QUADS) glVertex2f(2 * dx, 8 * dy) glVertex2f(2 * dx, 10 * dy) glVertex2f(4 * dx, 10 * dy) glVertex2f(4 * dx, 8 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(12 * dx, 8 * dy) glVertex2f(12 * dx, 10 * dy) glVertex2f(14 * dx, 10 * dy) glVertex2f(14 * dx, 8 * dy) glEnd() #---cabeza---# #boca glBegin(GL_QUADS) glVertex2f(6*dx,11*dy) glVertex2f(6*dx,12*dy) glVertex2f(10*dx,12*dy) glVertex2f(10*dx,11*dy) glEnd() # nariz glBegin(GL_QUADS) glVertex2f(7 * dx, 12 * dy) glVertex2f(7 * dx, 14 * dy) glVertex2f(9 * dx, 14 * dy) glVertex2f(9 * dx, 12 * dy) glEnd() # laterales glBegin(GL_QUADS) glVertex2f(5 * dx, 12 * dy) glVertex2f(5 * dx, 14 * dy) glVertex2f(6 * dx, 14 * dy) glVertex2f(6 * dx, 12 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(10 * dx, 12 * dy) glVertex2f(10 * dx, 14 * dy) glVertex2f(11 * dx, 14 * dy) glVertex2f(11 * dx, 12 * dy) glEnd() # frente + orejas glBegin(GL_QUADS) glVertex2f(4 * dx, 14 * dy) glVertex2f(4 * dx, 16 * dy) glVertex2f(12 * dx, 16 * dy) glVertex2f(12 * dx, 14 * dy) glEnd() #---pelo---# glColor3f(0.0,12.0/255,175.0/255) glBegin(GL_QUADS) glVertex2f(4*dx,15*dy) glVertex2f(4*dx,16*dy) glVertex2f(5*dx,16*dy) glVertex2f(5*dx,15*dy) glEnd() glBegin(GL_QUADS) glVertex2f(11 * dx, 15 * dy) glVertex2f(11 * dx, 16 * dy) glVertex2f(12 * dx, 16 * dy) glVertex2f(12 * dx, 15 * dy) glEnd() glBegin(GL_QUADS) glVertex2f(4*dx,16*dy) glVertex2f(4*dx,21*dy) glVertex2f(12*dx,21*dy) glVertex2f(12*dx,16*dy) glEnd() glBegin(GL_QUADS) glVertex2f(5*dx,21*dy) glVertex2f(5*dx,22*dy) glVertex2f(11*dx,22*dy) glVertex2f(11*dx,21*dy) glEnd() def updatecenter(self): """ Actualiza el centro del jugador al moverse :return: None """ self.centro=Vector(self.pos.x+53.0/2,self.pos.y+46.0/2) #moverse: se mueve segun la discretizacion, direccion es -1 o 1 segun si le resto a sumo def moverx(self,direccion: int): self.pos=sumar(self.pos,Vector(direccion*53.0,0.0)) self.dibujar() self.updatecenter() def movery(self,direccion:int): self.pos=sumar(self.pos,Vector(0.0,direccion*46.0)) self.updatecenter() def getpos(self): """ Da la posicion como tupla x,y :return: tuple """ return self.pos.cartesianas() def getcenter(self): """ Da el centro como tupla x,y :return: tuple """ return self.centro.cartesianas() def getlife(self): """ True si esta vivo :return: boolean """ return self.vida def setlife(self,v): """ Pone el valor de la vida como v :param v: boolean :return: None """ self.vida=v def normalizar_camisa(self): """ Al terminar un power up, deja el valor de la camisa como normal :return: None """ if self.numero==1: self.color_camisa=(1.0,1.0,1.0) if self.numero==2: self.color_camisa=(43.0/255,185/255,0.0) def setcoloracion(self,rgb: tuple): """ Cambia el color de la camisa :param rgb: tuple :return: None """ self.color_camisa=rgb
# Executed prior to every build in platformio.ini # Copies Nexus Library (nexus/src, nexus/oc, nexus/include, and nexus/utils) # into the built-in PlatformIO 'lib' folder for this project. import glob import os from shutil import copytree, ignore_patterns, rmtree from filecmp import dircmp # from platformio Import("env") PROJECT_DIR = env["PROJECT_DIR"] # "Library name", folder to create within `lib/` BASE_LIBRARY_FOLDER_NAME = "nexus" # Folders to copy into BASE_LIBRARY_FOLDER_NAME NEXUS_LIBRARY_FOLDERS = ["../../src", "../../include", "../../oc", "../../utils"] # Create folder if its not already there nexus_pio_lib_path = os.path.join(PROJECT_DIR, "lib", BASE_LIBRARY_FOLDER_NAME) if not os.path.exists(nexus_pio_lib_path): print("Creating directory {}".format(nexus_pio_lib_path)) os.mkdir(nexus_pio_lib_path) # Overwrite all files in the Nexus folder if changed for lib_src_folder in NEXUS_LIBRARY_FOLDERS: # src, include, oc, utils basename = os.path.basename(lib_src_folder) copied_folder = os.path.join(nexus_pio_lib_path, basename) should_copy = True # Delete all '*.o' files before copying, if any exist for file_in_dir in os.listdir(lib_src_folder): if file_in_dir.endswith(".o"): os.remove(os.path.join(lib_src_folder, file_in_dir)) if os.path.exists(copied_folder): dir_cmp_result = dircmp(lib_src_folder, copied_folder) # If the folder already exists and there aren't differences, don't copy if ( len(dir_cmp_result.diff_files) == 0 and len(dir_cmp_result.right_only) == 0 and len(dir_cmp_result.left_only) == 0 and len(dir_cmp_result.funny_files) == 0 ): should_copy = False if should_copy: # PIO `lib` subfolder may exist, but has differences - delete it if os.path.exists(copied_folder): rmtree(copied_folder) # Copy all files from the library source folder into the PIO lib folder # Should raise/fail if there is a problem copying print("Copying {} into {}".format(lib_src_folder, copied_folder)) copytree(lib_src_folder, copied_folder)
# -*- coding: utf-8 -*- import pandas as pd MASTER_FILE_PATH = './data/shop_master.csv' GOOGLEMAP_FILE_PATH = './data/googlemap.csv' dir_path = "./rawdata/shops/" file_name = "shop.csv" TARGET_FILE_PATH = dir_path + file_name master = pd.read_csv(MASTER_FILE_PATH, index_col='id') df = pd.read_csv(TARGET_FILE_PATH, index_col="id") data = pd.concat([master, df], sort=False).drop_duplicates(subset="url", keep="last") # master data.to_csv(MASTER_FILE_PATH, index=True, mode="w") # googlemap googlemap = pd.DataFrame() googlemap["店名"] = data["name"] googlemap["住所"] = data["address"] googlemap["緯度"] = data["latitude"] googlemap["経度"] = data["longitude"] # googlemap["開始"] = data["open_hour"] # googlemap["終了"] = data["close_hour"] googlemap["点数"] = data["point"] googlemap["レビュー数"] = data["reviews"] googlemap["URL"] = data["url"] googlemap.to_csv(GOOGLEMAP_FILE_PATH, index=False, mode="w")
# Copyright 2016 A Family For Every Child # # 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. """Helper/Misc functions and the like to make life easier for everyone.""" from twisted.logger import Logger log = Logger() def return_type(t): """ A decorator method to do runtime type verification for method returns. @type t: any @param t: The class of a type f should return """ def wrap(f): def wrapped_f(*args, **kwargs): # Run the decorated method/function and get the returned object result = f(*args, **kwargs) # If not a list, do a regular type check if not isinstance(result, t): raise TypeError( "%s returned a result with type %s and not %s." % ( f.__name__, type(result), t ) ) return result return wrapped_f return wrap
"""Self managed apicast deployed from apicast template""" import logging import os import importlib_resources as resources from testsuite.openshift.objects import SecretTypes from testsuite.openshift.client import OpenShiftClient from . import OpenshiftApicast LOGGER = logging.getLogger(__name__) class TemplateApicast(OpenshiftApicast): """Template-based APIcast Gateway.""" # pylint: disable=too-many-arguments def __init__(self, staging: bool, openshift: OpenShiftClient, template, name, image, portal_endpoint, generate_name=False, path_routing=False): super().__init__(staging, openshift, name, generate_name, path_routing) self._image = image self._portal_endpoint = portal_endpoint if template.endswith(".yml") and template == os.path.basename(template): template = resources.files("testsuite.resources").joinpath(template) self._template = template self.template_parameters = { "APICAST_NAME": self.deployment.name, "AMP_APICAST_IMAGE": self._image, "CONFIGURATION_URL_SECRET": f"{self.deployment.name}-secret"} if self.staging: self.template_parameters.update({ "CONFIGURATION_LOADER": "lazy", "DEPLOYMENT_ENVIRONMENT": "staging", "CONFIGURATION_CACHE": 0}) @staticmethod def fits(openshift: OpenShiftClient): # pylint: disable=unused-argument return True def _create_configuration_url_secret(self): self.openshift.secrets.create( name=self.template_parameters["CONFIGURATION_URL_SECRET"], string_data={ "password": self._portal_endpoint }, secret_type=SecretTypes.BASIC_AUTH ) def create(self): LOGGER.debug('Deploying new template-based apicast "%s". Template params: "%s"', self.deployment, self.template_parameters) self._create_configuration_url_secret() self.openshift.new_app(self._template, self.template_parameters) # pylint: disable=protected-access self.deployment.wait_for() super().create() def destroy(self): super().destroy() LOGGER.debug('Destroying template-based apicast "%s"...', self.deployment) LOGGER.debug('Deleting service "%s"', self.deployment) self.openshift.delete("service", self.deployment.name) LOGGER.debug('Deleting deploymentconfig "%s"', self.deployment) self.deployment.delete() LOGGER.debug('Deleting secret "%s"', self.template_parameters["CONFIGURATION_URL_SECRET"]) self.openshift.delete("secret", self.template_parameters["CONFIGURATION_URL_SECRET"]) def setup_tls(self, secret_name, https_port): mount_path = "/var/apicast/secrets" LOGGER.debug('Adding tls volume bound to secret "%s" to deployment "%s"...', secret_name, self.deployment) self.deployment.add_volume("tls-secret", mount_path, secret_name) LOGGER.debug('Patching https port into service "%s"...', self.deployment) self.openshift.patch("service", self.deployment.name, [{ "op": "add", "path": "/spec/ports/-", "value": { "name": "httpsproxy", "port": https_port, "protocol": "TCP" } }], patch_type="json") LOGGER.debug('Adding envs to deployment "%s"...', self.deployment) self.environ.set_many({ "APICAST_HTTPS_PORT": https_port, "APICAST_HTTPS_CERTIFICATE": f"{mount_path}/tls.crt", "APICAST_HTTPS_CERTIFICATE_KEY": f"{mount_path}/tls.key", }) def connect_jaeger(self, jaeger): """ Modifies the APIcast to send information to jaeger. Creates configmap and a volume, mounts the configmap into the volume Updates the required env vars :param jaeger instance of the Jaeger class carrying the information about the apicast_configuration :returns Name of the jaeger service """ config_map_name = f"{self.name}-jaeger" self.openshift.config_maps.add(config_map_name, jaeger.apicast_config(config_map_name, self.name)) self._to_delete.append(("configmap", config_map_name)) self.deployment.add_volume("jaeger-config-vol", "/tmp/jaeger/", configmap_name=config_map_name) self.environ.set_many({"OPENTRACING_TRACER": "jaeger", "OPENTRACING_CONFIG": f"/tmp/jaeger/{config_map_name}"}) return self.name
import logging from argparse import ArgumentParser, FileType, Namespace from itertools import chain from typing import Callable, Dict, Iterable, List, Optional from progress.bar import Bar # type: ignore import bankroll.analysis as analysis from bankroll.broker import AccountAggregator from bankroll.broker.configuration import ( Configuration, Settings, addSettingsToArgumentGroup, ) from bankroll.marketdata import MarketConnectedAccountData, MarketDataProvider from bankroll.model import Activity, Cash, converter, Instrument, Position, Stock, Trade from .brokers import * from .configuration import loadConfig, marketDataProvider parser = ArgumentParser( prog="bankroll", add_help=False, description="Ingests portfolio and other data from multiple brokerages, and analyzes it.", epilog="For more information, or to report issues, please visit: https://github.com/bankroll-py/bankroll", ) # Add our own help option for consistent formatting. parser.add_argument( "-h", "--help", help="Show this help message and exit.", action="help" ) parser.add_argument( "--lenient", help="Attempt to ignore invalid data instead of erroring out. May not be supported for all data sources.", default=False, action="store_true", ) parser.add_argument( "--no-lenient", dest="lenient", help="Opposite of --lenient.", action="store_false" ) parser.add_argument( "-v", "--verbose", help="Turns on more logging, for debugging purposes.", dest="verbose", default=False, action="store_true", ) parser.add_argument( "--config", help="Path to an INI file specifying configuration options, taking precedence over the default search paths. Can be specified multiple times, with the latest file's settings taking precedence over those previous.", action="append", ) if ibkr: ibGroup = parser.add_argument_group( "IB", "Options for importing data from Interactive Brokers." ) readIBSettings = addSettingsToArgumentGroup(ibkr.Settings, ibGroup) if fidelity: fidelityGroup = parser.add_argument_group( "Fidelity", "Options for importing data from local files in Fidelity's CSV export format.", ) readFidelitySettings = addSettingsToArgumentGroup(fidelity.Settings, fidelityGroup) if schwab: schwabGroup = parser.add_argument_group( "Schwab", "Options for importing data from local files in Charles Schwab's CSV export format.", ) readSchwabSettings = addSettingsToArgumentGroup(schwab.Settings, schwabGroup) if vanguard: vanguardGroup = parser.add_argument_group( "Vanguard", "Options for importing data from local files in Vanguard's CSV export format.", ) readVanguardSettings = addSettingsToArgumentGroup(vanguard.Settings, vanguardGroup) def printPositions(accounts: AccountAggregator, args: Namespace) -> None: values: Dict[Position, Cash] = {} if args.live_value: dataProvider = marketDataProvider(accounts) if dataProvider: values = analysis.liveValuesForPositions( accounts.positions(), dataProvider=dataProvider, progressBar=Bar("Loading market data for positions"), ) else: logging.error("Live data connection required to fetch market values") for p in sorted(accounts.positions(), key=lambda p: p.instrument): print(p) if p in values: print(f"\tMarket value: {values[p]}") elif args.live_value: logging.warning(f"Could not fetch market value for {p.instrument}") print(f"\tCost basis: {p.costBasis}") if args.realized_basis and isinstance(p.instrument, Stock): realizedBasis = analysis.realizedBasisForSymbol( p.instrument.symbol, activity=accounts.activity() ) print(f"\tRealized basis: {realizedBasis}") def printActivity(accounts: AccountAggregator, args: Namespace) -> None: if args.output_csv: df = converter.dataframeForModelObjects(list(accounts.activity())).sort_values( by=["Date"] ) df.to_csv(args.output_csv, index=False) print(f"Activity saved to: {args.output_csv}") else: for t in sorted(accounts.activity(), key=lambda t: t.date, reverse=True): print(t) def printBalances(accounts: AccountAggregator, args: Namespace) -> None: print(accounts.balance()) def symbolTimeline(accounts: AccountAggregator, args: Namespace) -> None: for entry in reversed( list(analysis.timelineForSymbol(args.symbol, accounts.activity())) ): print(entry) commands: Dict[str, Callable[[AccountAggregator, Namespace], None]] = { "positions": printPositions, "activity": printActivity, "balances": printBalances, "timeline": symbolTimeline, } subparsers = parser.add_subparsers(dest="command", help="What to inspect") positionsParser = subparsers.add_parser( "positions", help="Operations upon the imported list of portfolio positions" ) positionsParser.add_argument( "--realized-basis", help="Calculate realized basis for stock positions", default=False, action="store_true", ) positionsParser.add_argument( "--live-value", help="Fetch live, mark-to-market value of positions", default=False, action="store_true", ) activityParser = subparsers.add_parser( "activity", help="Operations upon imported portfolio activity" ) activityParser.add_argument( "-o", "--output-csv", metavar="out-file", help="Path to output results as csv file" ) balancesParser = subparsers.add_parser( "balances", help="Operations upon imported portfolio cash balances" ) timelineParser = subparsers.add_parser( "timeline", help="Traces a position and P/L for a symbol over time" ) timelineParser.add_argument( "symbol", help="The symbol to look up (multi-part symbols like BRK.B will be normalized so they can be tracked across brokers)", ) def main() -> None: args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) config = loadConfig( chain(Configuration.defaultSearchPaths, args.config if args.config else []) ) if not args.command: parser.print_usage() quit(1) mergedSettings: Dict[Settings, str] = dict( chain( readFidelitySettings(config, args).items() if fidelity else [], readSchwabSettings(config, args).items() if schwab else [], readVanguardSettings(config, args).items() if vanguard else [], readIBSettings(config, args).items() if ibkr else [], ) ) accounts = AccountAggregator.fromSettings(mergedSettings, lenient=args.lenient) commands[args.command](accounts, args) if __name__ == "__main__": main()
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Functions for operating on tests run in swarming.""" import json import logging import time from google.appengine.ext import ndb from common.findit_http_client import FinditHttpClient from dto import swarming_task_error from dto.swarming_task_error import SwarmingTaskError from dto.test_location import TestLocation from infra_api_clients.swarming import swarming_util from libs.test_results import test_results_util from services import isolate from services import constants from services import swarming from waterfall import waterfall_config _FINDIT_HTTP_CLIENT = FinditHttpClient() def GetOutputJsonByOutputsRef(outputs_ref, http_client): """Downloads failure log from isolated server.""" isolated_data = swarming_util.GenerateIsolatedData(outputs_ref) file_content, error = isolate.DownloadFileFromIsolatedServer( isolated_data, http_client, 'output.json') return json.loads(file_content) if file_content else None, error def GetSwarmingTaskDataAndResult(task_id, http_client=_FINDIT_HTTP_CLIENT): """Gets information about a swarming task. Returns: (str, dict, dict): The state, test result and error for a swarming task. """ data, error = swarming_util.GetSwarmingTaskResultById(swarming.SwarmingHost(), task_id, http_client) error = SwarmingTaskError.FromSerializable(error) if not data: return None, None, error task_state = data['state'] output_json = None if task_state not in constants.STATE_NOT_STOP: if task_state == constants.STATE_COMPLETED: outputs_ref = data.get('outputs_ref') # If swarming task aborted because of errors in request arguments, # it's possible that there is no outputs_ref. if not outputs_ref: error = error or SwarmingTaskError.GenerateError( swarming_task_error.NO_TASK_OUTPUTS) else: output_json, error = GetOutputJsonByOutputsRef(outputs_ref, http_client) if not output_json: error = error or SwarmingTaskError.GenerateError( swarming_task_error.NO_OUTPUT_JSON) else: # The swarming task did not complete successfully. logging.error('Swarming task %s stopped with status: %s', task_id, task_state) error = SwarmingTaskError.GenerateError( swarming_task_error.STATES_NOT_RUNNING_TO_ERROR_CODES[task_state]) return data, output_json, error def GetTestResultForSwarmingTask(task_id, http_client=_FINDIT_HTTP_CLIENT): """Get isolated output for a swarming task based on it's id.""" _data, test_result_log, _error = GetSwarmingTaskDataAndResult( task_id, http_client) return test_result_log def GetTestLocation(task_id, test_name): """Gets the filepath and line number of a test from swarming. Args: task_id (str): The swarming task id to query. test_name (str): The name of the test whose location to return. Returns: (TestLocation): The file path and line number of the test, or None if the test location was not be retrieved. """ test_results_log = GetTestResultForSwarmingTask(task_id, _FINDIT_HTTP_CLIENT) test_results = test_results_util.GetTestResultObject(test_results_log) test_location, error = test_results.GetTestLocation( test_name) if test_results else (None, constants.WRONG_FORMAT_LOG) if error: logging.info('Failed to get test location for task %s: %s', task_id, error) return None return TestLocation.FromSerializable(test_location or {}) def IsTestEnabled(test_name, tasks): """Returns True if the test is enabled, False otherwise.""" # Get the isolated outputs from the tests that were just run. for task in tasks: test_results_log = GetTestResultForSwarmingTask(task.task_id, _FINDIT_HTTP_CLIENT) test_result_object = test_results_util.GetTestResultObject( test_results_log, partial_result=True) if test_result_object.DoesTestExist(test_name): return test_result_object.IsTestEnabled(test_name) elif test_result_object.contains_all_tests: # Has checked all tests and the test doesn't exist. return False return False def RetrieveShardedTestResultsFromIsolatedServer(list_isolated_data, http_client): """Gets test results from isolated server and merge the results.""" shard_results = [] for isolated_data in list_isolated_data: test_result_log, _ = isolate.DownloadFileFromIsolatedServer( isolated_data, http_client, 'output.json') if not test_result_log: return None shard_results.append(json.loads(test_result_log)) if not shard_results: return [] test_results = test_results_util.GetTestResultObject(shard_results[0]) return test_results.GetMergedTestResults( shard_results) if test_results else None def GetTaskIdFromSwarmingTaskEntity(urlsafe_task_key): """Gets swarming task id from SwarmingTask. Waits and polls if needed.""" swarming_settings = waterfall_config.GetSwarmingSettings() wait_seconds = swarming_settings.get('get_swarming_task_id_wait_seconds') timeout_seconds = swarming_settings.get( 'get_swarming_task_id_timeout_seconds') deadline = time.time() + timeout_seconds while time.time() < deadline: swarming_task = ndb.Key(urlsafe=urlsafe_task_key).get() if not swarming_task: raise Exception('Swarming task was deleted unexpectedly!') if swarming_task.task_id: return swarming_task.task_id # Wait for the existing pipeline to start the Swarming task. time.sleep(wait_seconds) raise Exception('Timed out waiting for task_id.')
#!/usr/bin/env python3 import numpy as np import multiprocessing import copy import time from datetime import timedelta from functools import partial from scipy import integrate from scipy import optimize from amespahdbpythonsuite.amespahdb import AmesPAHdb from amespahdbpythonsuite.data import Data message = AmesPAHdb.message class Transitions(Data): """ AmesPAHdbPythonSuite transitions class. Contains methods to create and apply an emission model. """ def __init__(self, d=None, **keywords): """ Initialize transitions class. """ self.__shift = 0.0 self.set(d, **keywords) def set(self, d=None, **keywords): """ Calls class: :class:`amespahdbpythonsuite.data.Data.set to parse keywords. Checks type of database object (e.g., theoretical, experimental) """ super().set(d, **keywords) if d: if d.get('type', '') == self.__class__.__name__: if not keywords.get('shift'): self.__shift = d['shift'] d['type'] = 'Transitions' if keywords.get('shift'): self.shift = keywords.get('shift') def get(self): """ Calls class: :class:`amespahdbpythonsuite.data.Data.get to get keywords. """ d = super().get() d['type'] = self.__class__.__name__ d['shift'] = self.__shift return copy.deepcopy(d) def shift(self, shift): """ Shifts transitions frequency by provided value. """ self.__shift += shift for key in self.data: for d in self.data[key]: d['frequency'] += shift message(f'TOTAL SHIFT: {self.__shift} /cm') def fixedtemperature(self, t): """ Applies the Fixed Temperature emission model. Parameters ---------- t : float Excitation temperature in Kelvin. """ if self.model: if self.model['type'] != 'zerokelvin_m': message(f'AN EMISSION MODEL HAS ALREADY BEEN APPLIED: {self.model["type"]}') return message('APPLYING FIXED TEMPERATURE EMISSION MODEL') for uid in self.uids: f = np.array([d['frequency'] for d in self.data[uid]]) intensity = 2.4853427121856266e-23 * f ** 3 / (np.exp(1.4387751297850830401 * f / t) - 1.0) for (d, i) in zip(self.data[uid], intensity): d['intensity'] *= i def calculatedtemperature(self, e, **keywords): """ Applies the Calculated Temperature emission model. Parameters ---------- e : float Excitation energy in erg. """ if self.type != 'theoretical': message('THEORETICAL DATABASE REQUIRED FOR EMISSION MODEL') return if self.model: if self.model['type'] != 'zerokelvin_m': message(f'AN EMISSION MODEL HAS ALREADY BEEN APPLIED: {self.model["type"]}') return message('APPLYING CALCULATED TEMPERATURE EMISSION MODEL') global energy energy = e self.model = {'type': 'calculatedtemperature_m', 'energy': e, 'temperatures': [], 'description': ''} self.units['ordinate'] = {'unit': 2, 'str': 'integrated spectral radiance [erg/s/PAH]'} print(57 * '=') i = 0 nuids = len(self.uids) for uid in self.uids: # Start timer. tstart = time.perf_counter() print('SPECIES : %d/%d' % (i + 1, nuids)) print('UID : %d' % uid) print('MEAN ABSORBED ENERGY : %f +/- %f eV' % (e / 1.6021765e-12, 0.0)) global frequencies frequencies = np.array([d['frequency'] for d in self.data[uid]]) Tmax = optimize.brentq(self.attainedtemperature, 2.73, 5000.0) print('MAXIMUM ATTAINED TEMPERATURE : %f Kelvin' % Tmax) self.model['temperatures'].append({'uid': uid, 'temperature': Tmax}) for d in self.data[uid]: if d['intensity'] > 0: d['intensity'] *= 2.4853427121856266e-23 * \ d['frequency'] ** 3 / (np.exp(1.4387751297850830401 * d['frequency'] / Tmax) - 1.0) # Stop timer and calculate elapsed time. elapsed = timedelta(seconds=(time.perf_counter() - tstart)) print(f'Elapsed time: {elapsed}') i += 1 print(57 * '=') def _cascade_em_model(self, e, uid): """ A partial method of :meth:`amespahdbpythonsuite.transitions.cascade` used when multiprocessing is required. Parameters ---------- uid : int single UID value. Returns ------- temp : dict Dictionary of Tmax. ud : dict Dictionary of calculated intensities for the given UID. """ global energy energy = e global frequencies frequencies = np.array([d['frequency'] for d in self.data[uid]]) global intensities intensities = np.array([d['intensity'] for d in self.data[uid]]) Tmax = optimize.brentq(self.attainedtemperature, 2.73, 5000.0) for d in self.data[uid]: if d['intensity'] > 0: global frequency frequency = d['frequency'] d['intensity'] *= d['frequency'] ** 3 * integrate.quad(self.featurestrength, 2.73, Tmax)[0] temp = {'uid': uid, 'temperature': Tmax} ud = {uid: self.data[uid]} return ud, temp def cascade(self, e, **keywords): """ Applies the Cascade emission model. Parameters ---------- e : float Excitation energy in erg. """ if self.type != 'theoretical': message('THEORETICAL DATABASE REQUIRED FOR EMISSION MODEL') return if self.model: if self.model['type'] != 'zerokelvin_m': message(f'AN EMISSION MODEL HAS ALREADY BEEN APPLIED: {self.model["type"]}') return message('APPLYING CASCADE EMISSION MODEL') tstart = time.perf_counter() global energy energy = e self.model = {'type': 'cascade_m', 'energy': e, 'temperatures': [], 'description': ''} self.units['ordinate'] = {'unit': 3, 'str': 'integrated radiant energy [erg]'} print(57 * '=') if keywords.get('multiprocessing'): cascade_em_model = partial(self._cascade_em_model, e) if keywords.get('ncores'): ncores = keywords.get('ncores') print(f'Using multiprocessing module with {ncores} cores') pool = multiprocessing.Pool(processes=ncores) data, temp = zip(*pool.map(cascade_em_model, self.uids)) else: print('Using multiprocessing module with 2 cores') pool = multiprocessing.Pool(processes=2) data, temp = zip(*pool.map(cascade_em_model, self.uids)) pool.close() pool.join() # Re-assign self.data. self.data = {} for d in list(data): for k, v in d.items(): self.data[k] = v self.model['temperatures'] = temp else: i = 0 nuids = len(self.uids) for uid in self.uids: print('SPECIES : %d/%d' % (i + 1, nuids)) print('UID : %d' % uid) print('MEAN ABSORBED ENERGY : %f +/- %f eV' % (e / 1.6021765e-12, 0.0)) global frequencies frequencies = np.array([d['frequency'] for d in self.data[uid]]) global intensities intensities = np.array([d['intensity'] for d in self.data[uid]]) Tmax = optimize.brentq(self.attainedtemperature, 2.73, 5000.0) print('MAXIMUM ATTAINED TEMPERATURE : %f Kelvin' % Tmax) self.model['temperatures'].append({'uid': uid, 'temperature': Tmax}) for d in self.data[uid]: if d['intensity'] > 0: global frequency frequency = d['frequency'] d['intensity'] *= d['frequency'] ** 3 * integrate.quad(self.featurestrength, 2.73, Tmax)[0] i += 1 print(57 * '=') elapsed = timedelta(seconds=(time.perf_counter() - tstart)) print(f'Elapsed time: {elapsed}\n') def _get_intensities(self, npoints, xmin, xmax, clip, width, x, gaussian, drude, uid): """ A partial method of :meth:`amespahdbpythonsuite.transitions.convolve` used when multiprocessing is required. Parameters ---------- npoints : int Number of grid points. xmin : float Minimum value of grid. xmax : float Maximum value of grid. clip : float Value to clip and define the frequency range of the profile calculation. width : float Width of the line profile. x : array Grid array. gaussian : str String to indicate Gaussian profile drude : str String to indicate Drude profile uid : int Single UID value Returns ------- ud : dict Dictionary of convolutged intensities for the given UID. """ s = np.zeros(npoints) f = [v for v in self.data[uid] if v['frequency'] >= xmin - clip * width and v['frequency'] <= xmax + clip * width] for t in f: if t['intensity'] > 0: s += t['intensity'] * \ self.__lineprofile(x, t['frequency'], width, gaussian=gaussian, drude=drude) ud = {uid: s} return ud def convolve(self, **keywords): """ Convolve transitions with a line profile. Calls class: :class:`amespahdbpythonsuite.spectrum.Spectrum` to retrieve the respective object. """ fwhm = keywords.get('fwhm', 15.0) if keywords.get('gaussian'): width = 0.5 * fwhm / np.sqrt(2.0 * np.log(2.0)) clip = 3.0 profile = 'Gaussian' message('USING GAUSSIAN LINE PROFILES') elif keywords.get('drude'): width = 1.0 / fwhm clip = 11.0 profile = 'Drude' message('USING DRUDE LINE PROFILES') else: width = 0.5 * fwhm clip = 22.0 profile = 'Lorentzian' message('USING LORENTZIAN LINE PROFILES') x = keywords.get('grid', []) if not len(x): r = keywords.get('xrange', []) if len(r): xmin = min(r) xmax = max(r) else: xmin = 1.0 xmax = 4000.0 npoints = keywords.get('npoints', False) if not npoints: npoints = 400 x = np.arange(xmin, xmax, (xmax - xmin) / npoints) else: x = np.asarray(x) xmin = min(x) xmax = max(x) npoints = len(x) message(f'GRID: (XMIN,XMAX)=({xmin:.3f}, {xmax:.3f}); {npoints} POINTS') message(f'FWHM: {fwhm} /cm') print('Convolving') # Start timer. tstart = time.perf_counter() gaussian = keywords.get('gaussian', False) drude = keywords.get('drude', False) d = {} if keywords.get('multiprocessing'): get_intensities = partial(self._get_intensities, npoints, xmin, xmax, clip, width, x, gaussian, drude) if keywords.get('ncores'): ncores = keywords.get('ncores') print(f'Using multiprocessing module with {ncores} cores') pool = multiprocessing.Pool(processes=ncores) data = pool.map(get_intensities, self.uids) else: print('Using multiprocessing module with 2 cores') pool = multiprocessing.Pool(processes=2) data = pool.map(get_intensities, self.uids) pool.close() pool.join() # Re-assign self.data. for ud in list(data): for k, v in ud.items(): d[k] = v else: for uid in self.uids: s = np.zeros(npoints) f = [v for v in self.data[uid] if (v['frequency'] >= xmin - clip * width) and (v['frequency'] <= xmax + clip * width)] for t in f: if t['intensity'] > 0: s += t['intensity'] * self.__lineprofile(x, t['frequency'], width, gaussian=keywords.get('gaussian', False), drude=keywords.get('drude', False)) d[uid] = s elapsed = timedelta(seconds=(time.perf_counter() - tstart)) print(f'Elapsed time: {elapsed}') from amespahdbpythonsuite.spectrum import Spectrum if self.model['type'] == 'zerokelvin_m': self.units['ordinate'] = {'unit': 2, 'str': 'cross-section [x10$^{5}$ cm$^{2}$/mol]'} elif self.model['type'] == 'cascade_m': self.units['ordinate'] = {'unit': 3, 'str': 'radiant energy [x10$^{5}$ erg/cm$^{-1}$/mol]'} return Spectrum(type=self.type, version=self.version, data=d, pahdb=self.pahdb, uids=self.uids, model=self.model, units={'abscissa': self.units['abscissa'], 'ordinate': self.units['ordinate']}, shift=self.__shift, grid=x, profile=profile, fwhm=fwhm) def __lineprofile(self, x, x0, width, **keywords): """ Calculate Gaussian, Drude, or Lorentzian line profiles. Parameters ---------- x : array Grid array. x0 : float Central frequency width : float Width of the line profile. """ if keywords.get('gaussian', False): return (1.0 / (width * np.sqrt(2.0 * np.pi))) * \ np.exp(-(x - x0) ** 2 / (2.0 * width ** 2)) elif keywords.get('drude', False): return (2.0 / (np.pi * x0 * width)) * \ width ** 2 / ((x / x0 - x0 / x) ** 2 + width ** 2) elif keywords.get('lorentzian', True): return (width / np.pi) / ((x - x0) ** 2 + width ** 2) def plot(self, **keywords): """ Plot the transitions absorption spectrum. """ import matplotlib.pyplot as plt import matplotlib.cm as cm _, ax = plt.subplots() ax.minorticks_on() ax.tick_params(which='major', right='on', top='on', direction='in', length=5) ax.tick_params(which='minor', right='on', top='on', direction='in', length=3) colors = cm.rainbow(np.linspace(0, 1, len(self.uids))) for uid, col in zip(self.uids, colors): f = [v for v in self.data[uid]] x = [d['frequency'] for d in f] y = [d['intensity'] for d in f] ax.bar(x, y, 20, color=col, alpha=0.5) ax.tick_params(axis='both', labelsize=14) plt.gca().invert_xaxis() plt.xlabel(self.units['abscissa']['str'], fontsize=14) plt.ylabel(self.units['ordinate']['str'], fontsize=14) if keywords.get('show'): plt.show() elif keywords.get('outfile'): outfile = keywords.get('outfile') plt.savefig(f'{outfile}.pdf', bbox_inches='tight') @staticmethod def featurestrength(T): """ Calculate a feature's strength covolved with a blackbody. Parameters ---------- T : float Excitation temperature in Kelvin. """ global frequency global frequencies global intensities val1 = 1.4387751297850830401 * frequency / T val2 = 1.4387751297850830401 * frequencies / T # TODO: replace np.exp with np.expm1, and avoid overflow. return (Transitions.heatcapacity(T) / (np.exp(val1) - 1)) * \ (1 / np.sum(intensities * (frequencies) ** 3 / (np.exp(val2) - 1))) @staticmethod def attainedtemperature(T): """ Calculate a PAH's temperature after absorbing a given amount of energy. Parameters ---------- T : float Excitation temperature in Kelvin. """ global energy return integrate.quad(Transitions.heatcapacity, 2.73, T)[0] - energy def heatcapacity(T): """ Calculate heat capacity. Parameters ---------- T : float Excitation temperature in Kelvin. """ global frequencies val = 1.4387751297850830401 * frequencies / T return 1.3806505e-16 * np.sum(np.exp(-val) * (val / (1.0 - np.exp(-val))) ** 2)
PCS_VERSION_STRING = "Version v1.8" PCS_VERSION = 18 PCS_UPDATE_DEFAULT_ENDPOINT = "https://raw.githubusercontent.com/smclt30p/pcs_update/master/update.json" SETT_PATH = "path" SETT_ARGS_MAIN = "argsMain" SETT_ARGS_SUB = "argsTitle" SETT_DEFAULT = "" SETTINGS_FILE_NAME = "settings.ini" SETT_UNSUP = "unsupported" ARGS_VLC_DEF = "%URL%" ARGS_SUB_VLC_DEF = "--sub-file=%SUB%" ARGS_WMP_DEF = "%URL" ARGS_SUB_WPM_DEF = "" RES_PROGRAM_ICON = "ui/res/icon.png" RES_SETTINGS_ICON = "ui/res/play.png" RES_PREF_IC = "ui/res/play.png" STRING_PROGRAM_NAME = "PCS" RES_PREF_TITLE = "PCS - Preferences" REF_ARGS_TITLE = "PCS - Player Settings" CONST_URL_PARAM = "%URL%" CONST_SUB_PARAM = "%SUB%" TAG_IFRAME = "iframe" SUBTITLES_DISABLED = 0 SUBTITLES_CUSTOM = 1 ARR_ARGS = "arguments" ARR_ARGS_DEF = ["%URL%", "--sub-file=%SUB%"]
#Caesar cipher encryptor string = "xyza" def encryptor(string, key): newString = "" for i in range(len(string)): newString+= (chr((ord(string[i])-ord("a")+key)%26+ord("a"))) return newString print(encryptor(string,3))
####################################### # CONVERSION ENCODING BYTES CHR FUNCS # ####################################### # %% ####################################### def decode_base64(obj: object): """Decodes the string / bytes string using BASE64. Example: >>> encode_base64('hello')\n b'aGVsbG8=\\n' >>> encode_base64('hello', no_newline=True)\n b'aGVsbG8=' >>> encode_base64('hello', True)\n b'aGVsbG8=' >>> >>> decode_base64(b'aGVsbG8=\\n')\n b'hello' >>> decode_base64(b'aGVsbG8=')\n b'hello' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj return codecs.decode(temp_obj, "base64") # %% ####################################### def get_preferred_encoding(): """Shows the preferred encoding of the local machine (often it is "UTF-8"). Examples: >>> get_preferred_encoding()\n 'UTF-8' References: https://realpython.com/python-encodings-guide/ """ import locale return locale.getpreferredencoding() # %% ####################################### def encode_punycode(string: str): """Encodes the string using Punycode. Example: >>> encode_punycode('hello')\n b'hello-' >>> decode_punycode(b'hello-')\n 'hello' """ import codecs if isinstance(string, str): temp_obj = string result = codecs.encode(temp_obj, "punycode") return result # %% ####################################### def display_binary_4bit(num: int): """Displays the binary string representation for a given integer. If the number is within 4 bits, the output will be 4 binary digits; if the number is 8 bits then 8 binary digits will be the output. Examples: >>> display_binary_4bit(151)\n '10010111' >>> display_binary_4bit(11)\n '1011' """ return format(num, "04b") # %% ####################################### def decode_rot13(string: str): """Decodes the string using ROT-13. Examples: >>> encode_rot13('hello')\n 'uryyb' >>> decode_rot13('uryyb')\n 'hello' """ import codecs return codecs.decode(string, "rot13") # %% ####################################### def encode_gzip(obj: object): """Encodes the string / bytes string using GZIP / zlib. Example: >>> encode_gzip('hello')\n b'x\x9c\xcbH\xcd\xc9\xc9\x07\x00\x06,\x02\x15' >>> encode_gzip(b'hello')\n b'x\x9c\xcbH\xcd\xc9\xc9\x07\x00\x06,\x02\x15' >>> decode_gzip(b'x\x9c\xcbH\xcd\xc9\xc9\x07\x00\x06,\x02\x15')\n b'hello' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj result = codecs.encode(temp_obj, "zlib") return result encode_zip = encode_gzip # %% ####################################### def decode_bz2(obj: object): """Decodes the string / bytes string using BZ2. Example: >>> encode_bz2('hello')\n b'BZh91AY&SY\x191e=\x00\x00\x00\x81\x00\x02D\xa0\x00!\x9ah3M\x073\x8b\xb9"\x9c(H\x0c\x98\xb2\x9e\x80' >>> encode_bz2(b'hello')\n b'BZh91AY&SY\x191e=\x00\x00\x00\x81\x00\x02D\xa0\x00!\x9ah3M\x073\x8b\xb9"\x9c(H\x0c\x98\xb2\x9e\x80' >>> decode_bz2(b'BZh91AY&SY\x191e=\x00\x00\x00\x81\x00\x02D\xa0\x00!\x9ah3M\x073\x8b\xb9"\x9c(H\x0c\x98\xb2\x9e\x80')\n b'hello' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj return codecs.decode(temp_obj, "bz2") # %% ####################################### def display_chr_value(num: int): """Displays the glyph representation of a given integer. Examples: >>> display_chr_value(128013) '🐍' >>> display_chr_value(77) 'M' display_chr_value(700) 'ʼ' """ return chr(num) # %% ####################################### def xor_strings(string: str, xor_string="zen"): """Returns an XOR'ed string given a string object. By default the string object will be XOR'ed using a truncated version of the "Zen of Python". You can change this default by specifying your own "xor_string" value. Examples: >>> mystring = "Complex is better than complicated." >>> xor_strings(mystring)\n '\x17\x07\x08P6\x00\x16\x00\x06\x15\x002\x1c\x00\x1c\n\x1c\x0cT\n\x18Nt\n\x02M \t\x1d\x06\x13\x07onl' >>> xor_strings( ... "\x17\x07\x08P6\x00\x16\x00\x06\x15\x002\x1c\x00\x1c\n\x1c\x0cT\n\x18Nt\n\x02M \t\x1d\x06\x13\x07onl" ... )\n 'Complex is better than complicated.' >>> xor_strings('here is some blah blah', 'and here is a super secret string we use for xor')\n '\t\x0b\x16EH\x0c\x01ES\x06\x1eEAB\x1f\x14\x18E\x10L\x12\r' >>> xor_strings( ... '\t\x0b\x16EH\x0c\x01ES\x06\x1eEAB\x1f\x14\x18E\x10L\x12\r', 'and here is a super secret string we use for xor' ... )\n 'here is some blah blah' Args: string (str): The string object you want to XOR xor_string (str, optional): The xor_string used to XOR against the given string object. Defaults to "zen". Returns: str: Returns an XOR'ed string. """ import codecs # import this from this import s as this_s # We initialize an empty string variable which we will += each xor'ed character to for the final string result_string = "" # We want to know the length of the given string, so we can have an equivalent number of characters from the "Zen of Python" len_of_string = len(string) if xor_string == "zen": # this.s is the zen of python rot13 encoded, so here we are decoding it zen = codecs.decode(this_s, "rot13") # Then we take the zen of python, and truncate it to match the length of the string we want to XOR match_len_for_xor_enum = zen[:len_of_string] for index_num, val in enumerate(string): result_string += chr(ord(val) ^ ord(match_len_for_xor_enum[index_num])) return result_string else: if len(string) == len(xor_string): match_len_for_xor_enum = xor_string elif len(string) > len(xor_string): makebig = xor_string * len(string) match_len_for_xor_enum = makebig[: len(string)] elif len(string) < len(xor_string): match_len_for_xor_enum = xor_string[: len(string)] for index_num, val in enumerate(string): result_string += chr(ord(val) ^ ord(match_len_for_xor_enum[index_num])) return result_string # %% ####################################### def decode_hex(obj: object): """Decodes the string / bytes string using Hexadecimal. Example: >>> encode_hex('hello')\n b'68656c6c6f' >>> encode_hex(b'hello')\n b'68656c6c6f' >>> decode_hex(b'68656c6c6f')\n b'hello' >>> decode_hex('68656c6c6f')\n b'hello' >>> [hex(ord(s)) for s in 'hello']\n ['0x68', '0x65', '0x6c', '0x6c', '0x6f'] >>> ''.join([hex(ord(s)) for s in 'hello'])\n '0x680x650x6c0x6c0x6f' >>> ''.join([hex(ord(s)) for s in 'hello']).replace('0x','')\n '68656c6c6f' ####################################### >>> data = ['6e', '75', '64', '67', '65', '20', '6e', '75', '64', '67', '65', '20', '77', '69', '6e', '6b', '20', '77', '69', '6e', '6b']\n >>> [decode_hex(hexa) for hexa in data]\n [b'n', b'u', b'd', b'g', b'e', b' ', b'n', b'u', b'd', b'g', b'e', b' ', b'w', b'i', b'n', b'k', b' ', b'w', b'i', b'n', b'k'] >>> [decode_hex(hexa).decode() for hexa in data]\n ['n', 'u', 'd', 'g', 'e', ' ', 'n', 'u', 'd', 'g', 'e', ' ', 'w', 'i', 'n', 'k', ' ', 'w', 'i', 'n', 'k'] >>> ''.join([decode_hex(hexa).decode() for hexa in data])\n 'nudge nudge wink wink' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj return codecs.decode(temp_obj, "hex") # %% ####################################### def encode_base64(obj: object, no_newline=False): """Encodes the string / bytes string using BASE64. Example: >>> encode_base64('hello')\n b'aGVsbG8=\\n' >>> encode_base64('hello', no_newline=True)\n b'aGVsbG8=' >>> encode_base64('hello', True)\n b'aGVsbG8=' >>> >>> decode_base64(b'aGVsbG8=\\n')\n b'hello' >>> decode_base64(b'aGVsbG8=')\n b'hello' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj if no_newline: result = codecs.encode(temp_obj, "base64") result = result.decode().rstrip("\n") result = result.encode() else: result = codecs.encode(temp_obj, "base64") return result # %% ####################################### def get_size_in_bytes(string: str): """Takes a given string and return the number of bytes used for all of the glyphs in the string. Examples: >>> shrug = r'¯\_(ツ)_/¯'\n >>> get_size_in_bytes(shrug)\n 13 >>> shrug.encode()\n b'\xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf' >>> shrug.encode('utf-8')\n b'\xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf' >>> shrug.encode('utf8')\n b'\xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf' >>> shrug.encode('utf-16')\n b'\xff\xfe\xaf\x00\\\x00_\x00(\x00\xc40)\x00_\x00/\x00\xaf\x00' >>> >>> len(shrug.encode())\n 13 """ return len(string.encode()) # %% ####################################### def bitwise_compliment_comparison(num: int): """Prints a comparison table of the number, its complement (the num * -1), and the Args: num (int): [description] Returns: [type]: [description] """ from pprint import pprint dict1 = {} dict1["num_orig"] = (num, format(num, "08b")) dict1["num_neg"] = (num * -1, format(num * -1, "08b")) dict1["bitcomp"] = (~num, format(~num, "08b")) pprint(list(dict1.items())) # %% ####################################### def encode_rot13(string: str): """Encodes the string using ROT-13. Example: >>> encode_rot13('hello')\n 'uryyb' >>> decode_rot13('uryyb')\n 'hello' """ import codecs return codecs.encode(string, "rot13") # %% ####################################### def encode_bz2(obj: object): """Encodes the string / bytes string using BZ2. Example: >>> encode_bz2('hello')\n b'BZh91AY&SY\x191e=\x00\x00\x00\x81\x00\x02D\xa0\x00!\x9ah3M\x073\x8b\xb9"\x9c(H\x0c\x98\xb2\x9e\x80' >>> encode_bz2(b'hello')\n b'BZh91AY&SY\x191e=\x00\x00\x00\x81\x00\x02D\xa0\x00!\x9ah3M\x073\x8b\xb9"\x9c(H\x0c\x98\xb2\x9e\x80' >>> decode_bz2(b'BZh91AY&SY\x191e=\x00\x00\x00\x81\x00\x02D\xa0\x00!\x9ah3M\x073\x8b\xb9"\x9c(H\x0c\x98\xb2\x9e\x80')\n b'hello' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj result = codecs.encode(temp_obj, "bz2") return result # %% ####################################### def bit_shifter(num: int, shiftright: int): """Shifts the bits of the given number (int) by the designated number (int) given to the "shiftright" parameter. Examples: >>> bit_shifter(151, 4)\n 9 >>> bin(151)\n '0b10010111' >>> bin(151 >> 1)\n '0b1001011' >>> bin(151 >> 2)\n '0b100101' >>> bin(151 >> 3)\n '0b10010' >>> bin(151 >> 4)\n '0b1001' >>> int('0b1001', 2)\n 9 >>> format(151, '08b')\n '10010111' >>> format(151 >> 4, '04b')\n '1001' >>> int('1001', 2)\n 9 """ return num >> shiftright # %% ####################################### def convert_bytes2string(thebytes: bytes): """Converts a "bytes" type object into a "str" type object Examples: >>> convert_bytes2string(b'nice string')\n 'nice string' """ return thebytes.decode() # %% ####################################### def display_binary_8bit(num: int): """Displays the binary string representation for a given integer. If the number is within 4 bits, the output will be 8 binary digits (left padded with four 0s); if the number is 8 bits then 8 binary digits will be the output. Examples: >>> display_binary_8bit(151)\n '10010111' >>> bin(151)\n '0b10010111' >>> display_binary_8bit(11)\n '00001011' """ return format(num, "08b") # %% ####################################### def get_emojis(): """Retrieves hundreds of emoji glyphs derived from the UTF-8 character table. Examples: >>> moji = get_emojis()\n >>> moji[1540:1547]\n '🤠 🤡 🤢 🤣' """ emoji_list_1 = [chr(i) for i in range(127744, 127994)] emoji_list_2 = [chr(e) for e in range(128000, 128501)] remove_list_for_list_3 = [ 129394, 129399, 129400, 129401, 129443, 129444, 129451, 129452, 129453, 129483, 129484, ] emoji_list_3 = [ chr(e) for e in range(129293, 129536) if e not in remove_list_for_list_3 ] agg_list = emoji_list_1 + emoji_list_2 + emoji_list_3 one_space_sep_string = " ".join(agg_list) return one_space_sep_string # %% ####################################### def encode_hex(obj: object): """Encodes the string / bytes string using Hexadecimal. Example: >>> encode_hex('hello')\n b'68656c6c6f' >>> encode_hex(b'hello')\n b'68656c6c6f' >>> decode_hex(b'68656c6c6f')\n b'hello' >>> decode_hex('68656c6c6f')\n b'hello' >>> [hex(ord(s)) for s in 'hello']\n ['0x68', '0x65', '0x6c', '0x6c', '0x6f'] >>> ''.join([hex(ord(s)) for s in 'hello'])\n '0x680x650x6c0x6c0x6f' >>> ''.join([hex(ord(s)) for s in 'hello']).replace('0x','')\n '68656c6c6f' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj result = codecs.encode(temp_obj, "hex") return result # %% ####################################### def decode_gzip(obj: object): """Decodes the string / bytes string using GZIP / zlib. Example: >>> encode_gzip('hello')\n b'x\x9c\xcbH\xcd\xc9\xc9\x07\x00\x06,\x02\x15' >>> encode_gzip(b'hello')\n b'x\x9c\xcbH\xcd\xc9\xc9\x07\x00\x06,\x02\x15' >>> decode_gzip(b'x\x9c\xcbH\xcd\xc9\xc9\x07\x00\x06,\x02\x15')\n b'hello' """ import codecs if isinstance(obj, str): temp_obj = obj.encode() elif isinstance(obj, bytes): temp_obj = obj return codecs.decode(temp_obj, "zlib") decode_zip = decode_gzip # %% ####################################### def xor_string(string: str, xor_int_value=42): """Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42 Examples: >>> string2encode = 'Now is better than never.'\n >>> xor_string(string2encode)\n 'dE]\nCY\nHO^^OX\n^BKD\nDO\\OX\x04' >>> xor_string('dE]\nCY\nHO^^OX\n^BKD\nDO\\OX\x04')\n 'Now is better than never.' >>> chr(97)\n 'a' >>> ord('a')\n 97 >>> hex(97)\n '0x61' >>> int('0x61', 16)\n 97 >>> xor_string(string2encode, xor_int_value = 97)\n '/\x0e\x16A\x08\x12A\x03\x04\x15\x15\x04\x13A\x15\t\x00\x0fA\x0f\x04\x17\x04\x13O' >>> >>> xor_string('/\x0e\x16A\x08\x12A\x03\x04\x15\x15\x04\x13A\x15\t\x00\x0fA\x0f\x04\x17\x04\x13O', 97)\n 'Now is better than never.' Args: string (str): The string you want to XOR (each character will be XORed by the xor_int_value) xor_int_value (int, optional): The integer value that is used for the XOR operation. Defaults to 42. Returns: str: Returns an XORed string """ xored_result = "".join([chr(ord(c) ^ xor_int_value) for c in string]) return xored_result # %% ####################################### def decode_punycode(thebytes: bytes): """Decodes the bytes string using Punycode. Example: >>> encode_punycode('hello')\n b'hello-' >>> decode_punycode(b'hello-')\n 'hello' """ import codecs if isinstance(thebytes, bytes): temp_obj = thebytes return codecs.decode(temp_obj, "punycode") # %% ####################################### def display_ordinal_value(glyph: str): """Displays the integer value of the given glyph Examples: >>> display_ordinal_value('🐍')\n 128013 >>> display_ordinal_value('G')\n 71 >>> display_ordinal_value('g')\n 103 """ return ord(glyph) # %% ####################################### def convert_string2bytes(string: str): """Converts a "str" type object into a "bytes" type object Examples: >>> convert_string2bytes('nice string')\n b'nice string' """ return string.encode()
# =============================================================================== # Copyright 2015 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= # ============= standard library imports ======================== # ============= local library imports ========================== from __future__ import absolute_import from pychron.canvas.canvas2D.scene.extraction_line_scene import ExtractionLineScene from pychron.canvas.canvas2D.scene.primitives.dumper_primitives import Gate, Funnel from pychron.canvas.canvas2D.scene.primitives.rounded import RoundedRectangle KLASS_MAP = {'gate': Gate, 'funnel': Funnel} class DumperScene(ExtractionLineScene): def load(self, pathname, configpath, valvepath, canvas): self.overlays = [] self.reset_layers() cp = self._get_canvas_parser(pathname) origin, color_dict = self._load_config(configpath, canvas) self._load_switchables(cp, origin, valvepath) self._load_rects(cp, origin, color_dict) self._load_stateables(cp, origin, color_dict) self._load_markup(cp, origin, color_dict) def _load_stateables(self, cp, origin, color_dict): for key in ('gate', 'funnel'): for b in cp.get_elements(key): if key in color_dict: c = color_dict[key] else: c = (204, 204, 204) klass = KLASS_MAP.get(key, RoundedRectangle) rect = self._new_rectangle(cp, b, c, bw=5, origin=origin, klass=klass, type_tag=key) self._load_states(rect, b) def _load_states(self, item, elem): closed_state = {'translation': (item.x, item.y), 'dimension': (item.width, item.height)} states = {'closed': closed_state} for state in elem.findall('state'): try: trans = self._get_floats(state, 'translation') except: trans = item.x, item.y try: dim = self._get_floats(state, 'dimension') except: dim = item.width, item.height d = {'translation': trans, 'dimension': dim} states[state.text.strip()] = d item.states = states # ============= EOF =============================================
from __future__ import absolute_import from ._snappy_cffi import ffi, lib try: unicode # Python 2 except NameError: unicode = str # Python 3 class UncompressError(Exception): pass class SnappyBufferSmallError(Exception): pass def prepare(data): _out_data = None _out_size = None _out_data = ffi.new('char[]', data) _out_size = ffi.cast('size_t', len(data)) return (_out_data, _out_size) def compress(data): if isinstance(data, unicode): data = data.encode('utf-8') _input_data, _input_size = prepare(data) max_compressed = lib.snappy_max_compressed_length(_input_size) _out_data = ffi.new('char[]', max_compressed) _out_size = ffi.new('size_t*', max_compressed) rc = lib.snappy_compress(_input_data, _input_size, _out_data, _out_size) if rc != lib.SNAPPY_OK: raise SnappyBufferSmallError() value = ffi.buffer(ffi.cast('char*', _out_data), _out_size[0]) return value[:] def uncompress(data): _out_data, _out_size = prepare(data) result = ffi.new('size_t*', 0) rc = lib.snappy_validate_compressed_buffer(_out_data, _out_size) if not rc == lib.SNAPPY_OK: raise UncompressError() rc = lib.snappy_uncompressed_length(_out_data, _out_size, result) if not rc == lib.SNAPPY_OK: raise UncompressError() _uncompressed_data = ffi.new('char[]', result[0]) rc = lib.snappy_uncompress(_out_data, _out_size, _uncompressed_data, result) if rc != lib.SNAPPY_OK: raise UncompressError() buf = ffi.buffer(ffi.cast('char*', _uncompressed_data), result[0]) return buf[:] def isValidCompressed(data): if isinstance(data, unicode): data = data.encode('utf-8') _out_data, _out_size= prepare(data) rc = lib.snappy_validate_compressed_buffer(_out_data, _out_size) return rc == lib.SNAPPY_OK decompress = uncompress def _crc32c(data): c_data = ffi.new('char[]', data) size = ffi.cast('int', len(data)) return int(lib._crc32c(c_data, size))
# !/usr/bin/env python3 # -*- Coding: UTF-8 -*- # # -*- System: Linux -*- # # -*- Usage: *.py -*- # # Owner: Cloud-Technology LLC. # Source: gitlab.cloud-technology.io # License: BSD 3-Clause License """ ... """ # ============================================================================= # Local Imports # ============================================================================= from . import * # ============================================================================= # Class (Schema) Initialization # ============================================================================= __module__ = __name__ class User(Scheme): """ ... """ ID: String Email: String Username: String Token: String = Field(alias = "HTML-Token") class Config(Scheme.Config): title = ".".join([__package__, "Base"]) class Base(Scheme): """ ... """ Content: List[Optional[Dictionary]] = Field( alias = "Content" ) class Config(Scheme.Config): title = ".".join([__package__, "Base"]) @property def ID(self) -> String: return String(self._id) class Style(Scheme): display: String margin: String marginBottom: String fontSize: String color: String background: String borderStyle: String borderWidth: String borderRadius: String borderColor: String class Map(Scheme): Styles: Style class Properties(Scheme): """ ... """ Name: String = Field(default = "[Label-Name]", alias = "Name") Redirect: String = Field(default ="[Redirect-URL]", alias = "Redirect") Button: String = Field(default = "[Button-HTML]", alias = "Button") Mapping: Map = Field(default = "[Mapping-CSS]", alias = "Mapping") Atlas: String = Field(default = "[Atlas-CSS]", alias = "Atlas") class Config(Scheme.Config): title = ".".join([__package__, "Properties"]) class Instantiation(Base): """ ... """ Identifier: Union[Object, String, Bytes] = Field(alias = "ID") class Config(Scheme.Config): title = ".".join([__package__, "Instantiation"]) class Input(Scheme): """ ... """ Identifier: Union[Object, String, Bytes] = Field(alias = "ID") Key: String = Field(default = "[Key-ID]", alias = "Key-ID") Name: String = Field(default = "[Name]", alias = "Name") Value: Properties = Field(...) class Config(Scheme.Config): title = ".".join([__package__, "Content"]) class Schema(Base): """ ... """ Identifier: Union[Object, String, Bytes] = Field(alias = "ID") Account: User = Field(alias = "User") class Config(Scheme.Config): title = ".".join([__package__, "Schema"]) class Response(Scheme): Content: List[Optional[Input]] = Field(alias = "Content") Profile: User = Field(alias = "User") # ============================================================================= # Exports & Schema Type Associations # ============================================================================= ...
# # This file is part of the PyMeasure package. # # Copyright (c) 2013-2021 PyMeasure Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import re import time import numpy as np from enum import IntFlag from pymeasure.instruments import Instrument, discreteTruncate from pymeasure.instruments.validators import strict_discrete_set, \ truncated_discrete_set, truncated_range class LIAStatus(IntFlag): """ IntFlag type that is returned by the lia_status property. """ NO_ERROR = 0 INPUT_OVERLOAD = 1 FILTER_OVERLOAD = 2 OUTPUT_OVERLOAD = 4 REF_UNLOCK = 8 FREQ_RANGE_CHANGE = 16 TC_CHANGE = 32 TRIGGER = 64 UNUSED = 128 class ERRStatus(IntFlag): """ IntFlag type that is returned by the err_status property. """ NO_ERROR = 0 BACKUP_ERR = 2 RAM_ERR = 4 ROM_ERR = 16 GPIB_ERR = 32 DSP_ERR = 64 MATH_ERR = 128 class SR830(Instrument): SAMPLE_FREQUENCIES = [ 62.5e-3, 125e-3, 250e-3, 500e-3, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 ] SENSITIVITIES = [ 2e-9, 5e-9, 10e-9, 20e-9, 50e-9, 100e-9, 200e-9, 500e-9, 1e-6, 2e-6, 5e-6, 10e-6, 20e-6, 50e-6, 100e-6, 200e-6, 500e-6, 1e-3, 2e-3, 5e-3, 10e-3, 20e-3, 50e-3, 100e-3, 200e-3, 500e-3, 1 ] TIME_CONSTANTS = [ 10e-6, 30e-6, 100e-6, 300e-6, 1e-3, 3e-3, 10e-3, 30e-3, 100e-3, 300e-3, 1, 3, 10, 30, 100, 300, 1e3, 3e3, 10e3, 30e3 ] FILTER_SLOPES = [6, 12, 18, 24] EXPANSION_VALUES = [1, 10, 100] RESERVE_VALUES = ['High Reserve', 'Normal', 'Low Noise'] CHANNELS = ['X', 'Y', 'R'] INPUT_CONFIGS = ['A', 'A - B', 'I (1 MOhm)', 'I (100 MOhm)'] INPUT_GROUNDINGS = ['Float', 'Ground'] INPUT_COUPLINGS = ['AC', 'DC'] INPUT_NOTCH_CONFIGS = ['None', 'Line', '2 x Line', 'Both'] REFERENCE_SOURCES = ['External', 'Internal'] SNAP_ENUMERATION = {"x": 1, "y": 2, "r": 3, "theta": 4, "aux in 1": 5, "aux in 2": 6, "aux in 3": 7, "aux in 4": 8, "frequency": 9, "ch1": 10, "ch2": 11} sine_voltage = Instrument.control( "SLVL?", "SLVL%0.3f", """ A floating point property that represents the reference sine-wave voltage in Volts. This property can be set. """, validator=truncated_range, values=[0.004, 5.0] ) frequency = Instrument.control( "FREQ?", "FREQ%0.5e", """ A floating point property that represents the lock-in frequency in Hz. This property can be set. """, validator=truncated_range, values=[0.001, 102000] ) phase = Instrument.control( "PHAS?", "PHAS%0.2f", """ A floating point property that represents the lock-in phase in degrees. This property can be set. """, validator=truncated_range, values=[-360, 729.99] ) x = Instrument.measurement("OUTP?1", """ Reads the X value in Volts. """ ) y = Instrument.measurement("OUTP?2", """ Reads the Y value in Volts. """ ) lia_status = Instrument.measurement("LIAS?", """ Reads the value of the lockin amplifier (LIA) status byte. Returns a binary string with positions within the string corresponding to different status flags: bit 0: Input/Amplifier overload bit 1: Time constant filter overload bit 2: Output overload bit 3: Reference unlock bit 4: Detection frequency range switched bit 5: Time constant changed indirectly bit 6: Data storage triggered bit 7: unused """, get_process=lambda s: LIAStatus(int(s)), ) err_status = Instrument.measurement("ERRS?", """Reads the value of the lockin error (ERR) status byte. Returns an IntFlag type with positions within the string corresponding to different error flags: bit 0: unused bit 1: backup error bit 2: RAM error bit 3: unused bit 4: ROM error bit 5: GPIB error bit 6: DSP error bit 7: Math error """, get_process=lambda s: ERRStatus(int(s)), ) @property def xy(self): """ Reads the X and Y values in Volts. """ return self.snap() magnitude = Instrument.measurement("OUTP?3", """ Reads the magnitude in Volts. """ ) theta = Instrument.measurement("OUTP?4", """ Reads the theta value in degrees. """ ) channel1 = Instrument.control( "DDEF?1;", "DDEF1,%d,0", """ A string property that represents the type of Channel 1, taking the values X, R, X Noise, Aux In 1, or Aux In 2. This property can be set.""", validator=strict_discrete_set, values=['X', 'R', 'X Noise', 'Aux In 1', 'Aux In 2'], map_values=True ) channel2 = Instrument.control( "DDEF?2;", "DDEF2,%d,0", """ A string property that represents the type of Channel 2, taking the values Y, Theta, Y Noise, Aux In 3, or Aux In 4. This property can be set.""", validator=strict_discrete_set, values=['Y', 'Theta', 'Y Noise', 'Aux In 3', 'Aux In 4'], map_values=True ) sensitivity = Instrument.control( "SENS?", "SENS%d", """ A floating point property that controls the sensitivity in Volts, which can take discrete values from 2 nV to 1 V. Values are truncated to the next highest level if they are not exact. """, validator=truncated_discrete_set, values=SENSITIVITIES, map_values=True ) time_constant = Instrument.control( "OFLT?", "OFLT%d", """ A floating point property that controls the time constant in seconds, which can take discrete values from 10 microseconds to 30,000 seconds. Values are truncated to the next highest level if they are not exact. """, validator=truncated_discrete_set, values=TIME_CONSTANTS, map_values=True ) filter_slope = Instrument.control( "OFSL?", "OFSL%d", """ An integer property that controls the filter slope, which can take on the values 6, 12, 18, and 24 dB/octave. Values are truncated to the next highest level if they are not exact. """, validator=truncated_discrete_set, values=FILTER_SLOPES, map_values=True ) harmonic = Instrument.control( "HARM?", "HARM%d", """ An integer property that controls the harmonic that is measured. Allowed values are 1 to 19999. Can be set. """, validator=strict_discrete_set, values=range(1, 19999), ) input_config = Instrument.control( "ISRC?", "ISRC %d", """ An string property that controls the input configuration. Allowed values are: {}""".format(INPUT_CONFIGS), validator=strict_discrete_set, values=INPUT_CONFIGS, map_values=True ) input_grounding = Instrument.control( "IGND?", "IGND %d", """ An string property that controls the input shield grounding. Allowed values are: {}""".format(INPUT_GROUNDINGS), validator=strict_discrete_set, values=INPUT_GROUNDINGS, map_values=True ) input_coupling = Instrument.control( "ICPL?", "ICPL %d", """ An string property that controls the input coupling. Allowed values are: {}""".format(INPUT_COUPLINGS), validator=strict_discrete_set, values=INPUT_COUPLINGS, map_values=True ) input_notch_config = Instrument.control( "ILIN?", "ILIN %d", """ An string property that controls the input line notch filter status. Allowed values are: {}""".format(INPUT_NOTCH_CONFIGS), validator=strict_discrete_set, values=INPUT_NOTCH_CONFIGS, map_values=True ) reference_source = Instrument.control( "FMOD?", "FMOD %d", """ An string property that controls the reference source. Allowed values are: {}""".format(REFERENCE_SOURCES), validator=strict_discrete_set, values=REFERENCE_SOURCES, map_values=True ) aux_out_1 = Instrument.control( "AUXV?1;", "AUXV1,%f;", """ A floating point property that controls the output of Aux output 1 in Volts, taking values between -10.5 V and +10.5 V. This property can be set.""", validator=truncated_range, values=[-10.5, 10.5] ) # For consistency with other lock-in instrument classes dac1 = aux_out_1 aux_out_2 = Instrument.control( "AUXV?2;", "AUXV2,%f;", """ A floating point property that controls the output of Aux output 2 in Volts, taking values between -10.5 V and +10.5 V. This property can be set.""", validator=truncated_range, values=[-10.5, 10.5] ) # For consistency with other lock-in instrument classes dac2 = aux_out_2 aux_out_3 = Instrument.control( "AUXV?3;", "AUXV3,%f;", """ A floating point property that controls the output of Aux output 3 in Volts, taking values between -10.5 V and +10.5 V. This property can be set.""", validator=truncated_range, values=[-10.5, 10.5] ) # For consistency with other lock-in instrument classes dac3 = aux_out_3 aux_out_4 = Instrument.control( "AUXV?4;", "AUXV4,%f;", """ A floating point property that controls the output of Aux output 4 in Volts, taking values between -10.5 V and +10.5 V. This property can be set.""", validator=truncated_range, values=[-10.5, 10.5] ) # For consistency with other lock-in instrument classes dac4 = aux_out_4 aux_in_1 = Instrument.measurement( "OAUX?1;", """ Reads the Aux input 1 value in Volts with 1/3 mV resolution. """ ) # For consistency with other lock-in instrument classes adc1 = aux_in_1 aux_in_2 = Instrument.measurement( "OAUX?2;", """ Reads the Aux input 2 value in Volts with 1/3 mV resolution. """ ) # For consistency with other lock-in instrument classes adc2 = aux_in_2 aux_in_3 = Instrument.measurement( "OAUX?3;", """ Reads the Aux input 3 value in Volts with 1/3 mV resolution. """ ) # For consistency with other lock-in instrument classes adc3 = aux_in_3 aux_in_4 = Instrument.measurement( "OAUX?4;", """ Reads the Aux input 4 value in Volts with 1/3 mV resolution. """ ) # For consistency with other lock-in instrument classes adc4 = aux_in_4 def __init__(self, resourceName, **kwargs): super(SR830, self).__init__( resourceName, "Stanford Research Systems SR830 Lock-in amplifier", **kwargs ) def auto_gain(self): self.write("AGAN") def auto_reserve(self): self.write("ARSV") def auto_phase(self): self.write("APHS") def auto_offset(self, channel): """ Offsets the channel (X, Y, or R) to zero """ if channel not in self.CHANNELS: raise ValueError('SR830 channel is invalid') channel = self.CHANNELS.index(channel) + 1 self.write("AOFF %d" % channel) def get_scaling(self, channel): """ Returns the offset precent and the exapnsion term that are used to scale the channel in question """ if channel not in self.CHANNELS: raise ValueError('SR830 channel is invalid') channel = self.CHANNELS.index(channel) + 1 offset, expand = self.ask("OEXP? %d" % channel).split(',') return float(offset), self.EXPANSION_VALUES[int(expand)] def set_scaling(self, channel, precent, expand=0): """ Sets the offset of a channel (X=1, Y=2, R=3) to a certain precent (-105% to 105%) of the signal, with an optional expansion term (0, 10=1, 100=2) """ if channel not in self.CHANNELS: raise ValueError('SR830 channel is invalid') channel = self.CHANNELS.index(channel) + 1 expand = discreteTruncate(expand, self.EXPANSION_VALUES) self.write("OEXP %i,%.2f,%i" % (channel, precent, expand)) def output_conversion(self, channel): """ Returns a function that can be used to determine the signal from the channel output (X, Y, or R) """ offset, expand = self.get_scaling(channel) sensitivity = self.sensitivity return lambda x: (x/(10.*expand) + offset) * sensitivity @property def sample_frequency(self): """ Gets the sample frequency in Hz """ index = int(self.ask("SRAT?")) if index == 14: return None # Trigger else: return SR830.SAMPLE_FREQUENCIES[index] @sample_frequency.setter def sample_frequency(self, frequency): """Sets the sample frequency in Hz (None is Trigger)""" assert type(frequency) in [float, int, type(None)] if frequency is None: index = 14 # Trigger else: frequency = discreteTruncate(frequency, SR830.SAMPLE_FREQUENCIES) index = SR830.SAMPLE_FREQUENCIES.index(frequency) self.write("SRAT%f" % index) def aquireOnTrigger(self, enable=True): self.write("TSTR%d" % enable) @property def reserve(self): return SR830.RESERVE_VALUES[int(self.ask("RMOD?"))] @reserve.setter def reserve(self, reserve): if reserve not in SR830.RESERVE_VALUES: index = 1 else: index = SR830.RESERVE_VALUES.index(reserve) self.write("RMOD%d" % index) def is_out_of_range(self): """ Returns True if the magnitude is out of range """ return int(self.ask("LIAS?2")) == 1 def quick_range(self): """ While the magnitude is out of range, increase the sensitivity by one setting """ self.write('LIAE 2,1') while self.is_out_of_range(): self.write("SENS%d" % (int(self.ask("SENS?"))+1)) time.sleep(5.0*self.time_constant) self.write("*CLS") # Set the range as low as possible newsensitivity = 1.15*abs(self.magnitude) if self.input_config in('I (1 MOhm)','I (100 MOhm)'): newsensitivity = newsensitivity*1e6 self.sensitivity = newsensitivity @property def buffer_count(self): query = self.ask("SPTS?") if query.count("\n") > 1: return int(re.match(r"\d+\n$", query, re.MULTILINE).group(0)) else: return int(query) def fill_buffer(self, count, has_aborted=lambda: False, delay=0.001): ch1 = np.empty(count, np.float32) ch2 = np.empty(count, np.float32) currentCount = self.buffer_count index = 0 while currentCount < count: if currentCount > index: ch1[index:currentCount] = self.buffer_data(1, index, currentCount) ch2[index:currentCount] = self.buffer_data(2, index, currentCount) index = currentCount time.sleep(delay) currentCount = self.buffer_count if has_aborted(): self.pause_buffer() return ch1, ch2 self.pauseBuffer() ch1[index:count+1] = self.buffer_data(1, index, count) ch2[index:count+1] = self.buffer_data(2, index, count) return ch1, ch2 def buffer_measure(self, count, stopRequest=None, delay=1e-3): self.write("FAST0;STRD") ch1 = np.empty(count, np.float64) ch2 = np.empty(count, np.float64) currentCount = self.buffer_count index = 0 while currentCount < count: if currentCount > index: ch1[index:currentCount] = self.buffer_data(1, index, currentCount) ch2[index:currentCount] = self.buffer_data(2, index, currentCount) index = currentCount time.sleep(delay) currentCount = self.buffer_count if stopRequest is not None and stopRequest.isSet(): self.pauseBuffer() return (0, 0, 0, 0) self.pauseBuffer() ch1[index:count] = self.buffer_data(1, index, count) ch2[index:count] = self.buffer_data(2, index, count) return (ch1.mean(), ch1.std(), ch2.mean(), ch2.std()) def pause_buffer(self): self.write("PAUS") def start_buffer(self, fast=False): if fast: self.write("FAST2;STRD") else: self.write("FAST0;STRD") def wait_for_buffer(self, count, has_aborted=lambda: False, timeout=60, timestep=0.01): """ Wait for the buffer to fill a certain count """ i = 0 while not self.buffer_count >= count and i < (timeout / timestep): time.sleep(timestep) i += 1 if has_aborted(): return False self.pauseBuffer() def get_buffer(self, channel=1, start=0, end=None): """ Aquires the 32 bit floating point data through binary transfer """ if end is None: end = self.buffer_count return self.binary_values("TRCB?%d,%d,%d" % ( channel, start, end-start)) def reset_buffer(self): self.write("REST") def trigger(self): self.write("TRIG") def snap(self, val1="X", val2="Y", *vals): """ Method that records and retrieves 2 to 6 parameters at a single instant. The parameters can be one of: X, Y, R, Theta, Aux In 1, Aux In 2, Aux In 3, Aux In 4, Frequency, CH1, CH2. Default is "X" and "Y". :param val1: first parameter to retrieve :param val2: second parameter to retrieve :param vals: other parameters to retrieve (optional) """ if len(vals) > 4: raise ValueError("No more that 6 values (in total) can be captured" "simultaneously.") # check if additional parameters are given as a list if len(vals) == 1 and isinstance(vals[0], (list, tuple)): vals = vals[0] # make a list of all vals vals = [val1, val2] + list(vals) vals_idx = [str(self.SNAP_ENUMERATION[val.lower()]) for val in vals] command = "SNAP? " + ",".join(vals_idx) return self.values(command)
from madqn import MADQN import pickle import rlUtilities as rl import matplotlib.pyplot as plt if __name__ == '__main__': # train and save a network algorithm = MADQN(mode='train') algorithm.train(num_episodes=2) # test a network or the heuristic # load_filename = # test_method = 'network' # algorithm = MADQN(mode='test', filename=load_filename) # results = algorithm.test(num_episodes=1, method=test_method) test_method = 'network' algorithm = MADQN(mode='test', filename=None) results = algorithm.test(num_episodes=1, method=test_method) #print(list(results)) #print(results) forest_states = results.get(0) forest_state = list(forest_states.get('sim_states'))[-1] #print(forest_state) image = rl.latticeforest_image(forest_state, (25,25), (50,50)) plt.imshow(image) plt.show() # save the results to file # WARNING: the resulting output file may be very large, ~1.5 GB # save_filename = 'results_' + test_method + '.pkl' # output = open(save_filename, 'wb') # pickle.dump(results, output) # output.close()
# Generated by Django 2.1.7 on 2019-02-18 01:41 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Record', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('category', models.CharField(max_length=100)), ('action', models.CharField(max_length=200)), ('start_time', models.DateTimeField()), ('end_time', models.DateTimeField()), ('duration', models.PositiveIntegerField(default=0)), ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-end_time', 'created'), }, ), ]
# -*- coding: utf-8 -*- # Copyright (c) 2019 Minoru Osuka # # 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. from copy import deepcopy from whoosh.fields import Schema from cockatrice.util.loader import get_instance class IndexConfig: def __init__(self, config_dict): self.__index_config_dict = config_dict self.__schema = Schema() try: for field_name in self.__index_config_dict['schema'].keys(): field_type = self.__get_field_type(self.__index_config_dict['schema'][field_name]['field_type']) for arg in self.__index_config_dict['schema'][field_name]['args'].keys(): setattr(field_type, arg, self.__index_config_dict['schema'][field_name]['args'][arg]) self.__schema.add(field_name, field_type, glob=False) if not self.__validate(): raise ValueError('invalid schema') except Exception as ex: raise ex def __get_filter(self, name): class_name = self.__index_config_dict['filters'][name]['class'] class_args = {} if 'args' in self.__index_config_dict['filters'][name]: class_args = deepcopy(self.__index_config_dict['filters'][name]['args']) instance = get_instance(class_name, **class_args) return instance def __get_tokenizer(self, name): class_name = self.__index_config_dict['tokenizers'][name]['class'] class_args = {} if 'args' in self.__index_config_dict['tokenizers'][name]: class_args = deepcopy(self.__index_config_dict['tokenizers'][name]['args']) instance = get_instance(class_name, **class_args) return instance def __get_analyzer(self, name): instance = None if 'class' in self.__index_config_dict['analyzers'][name]: class_name = self.__index_config_dict['analyzers'][name]['class'] class_args = {} if 'args' in self.__index_config_dict['analyzers'][name]: class_args = deepcopy(self.__index_config_dict['analyzers'][name]['args']) instance = get_instance(class_name, **class_args) elif 'tokenizer' in self.__index_config_dict['analyzers'][name]: instance = self.__get_tokenizer(self.__index_config_dict['analyzers'][name]['tokenizer']) if 'filters' in self.__index_config_dict['analyzers'][name]: for filter_name in self.__index_config_dict['analyzers'][name]['filters']: instance = instance | self.__get_filter(filter_name) return instance def __get_field_type(self, name): class_name = self.__index_config_dict['field_types'][name]['class'] class_args = {} if 'args' in self.__index_config_dict['field_types'][name]: class_args = deepcopy(self.__index_config_dict['field_types'][name]['args']) if 'analyzer' in class_args: class_args['analyzer'] = self.__get_analyzer(class_args['analyzer']) if class_args['analyzer'] else None if 'tokenizer' in class_args: class_args['tokenizer'] = self.__get_tokenizer(class_args['tokenizer']) if class_args[ 'tokenizer'] else None instance = get_instance(class_name, **class_args) return instance def __get_unique_fields(self): return [name for name, field in self.__schema.items() if field.unique] def __validate(self): valid = False if len(self.__get_unique_fields()) == 1: valid = True return valid def get_schema(self): return self.__schema def get_doc_id_field(self): return self.__get_unique_fields()[0] def get_storage_type(self): try: storage_type = self.__index_config_dict['storage']['type'] except KeyError: storage_type = 'file' return storage_type def get_writer_processors(self): try: procs = self.__index_config_dict['writer']['processors'] except KeyError: procs = 1 return procs def get_writer_batch_size(self): try: batch_size = self.__index_config_dict['writer']['batch_size'] except KeyError: batch_size = 100 return batch_size def get_writer_multi_segment(self): try: multi_segment = self.__index_config_dict['writer']['multi_segment'] except KeyError: multi_segment = False return multi_segment def get_writer_auto_commit_period(self): try: period = self.__index_config_dict['writer']['auto_commit']['period'] except KeyError: period = 0 return period def get_writer_auto_commit_limit(self): try: limit = self.__index_config_dict['writer']['auto_commit']['limit'] except KeyError: limit = 10 return limit
import ctypes import numpy from ..utils.c import load_library double1d = ctypes.POINTER(ctypes.c_double) class GloballyCoupledMap(ctypes.Structure): _fields_ = [ ("dim", ctypes.c_int), ("steps", ctypes.c_int), ("r", ctypes.c_double), ("epsilon", ctypes.c_double), ("x", double1d), ] class Simulator: _lib = load_library('libcomparatist_gcm') def __init__(self, x0, r, epsilon, dim, steps, map='logistic'): self.x = numpy.ones((steps, dim), dtype=float) self.x[0] = x0 self._run = getattr(self._lib, 'GloballyCoupledMap_' + map) self._run.argtypes = [ctypes.POINTER(GloballyCoupledMap)] self.struct = GloballyCoupledMap() self.struct.steps = steps self.struct.dim = dim self.struct.r = r self.struct.epsilon = epsilon self.struct.x = self.x.ctypes.data_as(double1d) def run(self): self._run(ctypes.pointer(self.struct)) def prepare(name): from ._helper import init, params kwds = init(**params[name]) steps, dim = kwds["x"].shape sim = Simulator(x0=kwds["x"][0], dim=dim, steps=steps, r=kwds['r'], epsilon=kwds['epsilon']) kwds["x"] = sim.x def run(): sim.run() return kwds return run
__author__ = "John Doe" def even_or_odd(number): """ 1. Given a number, return string 'even' if it is even or 'odd' if it is odd. """ pass def sum_them_all(number): """ 2. Given a number, return the sum of all digits from zero to the number (inclusive). """ pass def how_many_days(days): """ 3. Given a certain amount of days, return a string in the format: 'x year(s) y month(s) and z day(s). For the purposes of this exercise, assume a year has 360 days and a month has 30 days. """ pass def whats_the_price(diameter, price): """ 4. Given the diameter and price of a pizza, return the cost per square inch of it. """ pass def how_much_on_taxes(price, total): """ 5. Given the price of a product and the total on the receipt, return the exact percentage paid in taxes, with two decimals. """ pass def calories_per_day(current, goal, max_per_day): """ 6. Given current weith (kg), goal weight (kg), and the maximum intake of calories per day (g). Find the amount of days this person will need to reach their goal. Hint: check if goal < current and vice versa. """ pass
### Copyright 2015 The Pennsylvania State University. Office of the Vice Provost for Educational Equity. All Rights Reserved. ### from django.conf import settings from django.contrib import messages from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import permission_required from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from django.contrib.auth.models import User from django.contrib.auth.views import ( login as auth_login, logout as auth_logout, password_change as auth_password_change, password_change_done as auth_password_change_done ) from django.contrib.humanize.templatetags.humanize import naturaltime from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse, ) from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from smtplib import SMTPException from .decorators import login_required, never_cache, prevent_url_guessing from .models import ( Comment, Locker, Submission, ) from .utils.notifications import get_from_address from .utils.users import get_public_user_dict, UserColors import logging logger = logging.getLogger(__name__) @login_required @never_cache @prevent_url_guessing @require_http_methods(['POST']) def comment_add(request, locker_id, submission_id): """Adds a comment or reply to the specified submission""" submission = get_object_or_404(Submission, id=submission_id) comment_text = request.POST.get('comment', '').strip() parent_id = request.POST.get('parent', None) try: parent = Comment.objects.get(pk=parent_id) except Comment.DoesNotExist: parent = None if comment_text: comment = Comment( submission=submission, comment=comment_text, user=request.user, parent=parent ) comment.save() if request.is_ajax(): color_helper = UserColors(request) comment_dict = comment.to_dict() comment_dict['user']['color'] = color_helper.get(comment.user.username) # NOQA return JsonResponse(comment_dict) else: messages.success(request, u'<strong>Success!</strong> ' u'Your comment was added to the discussion.') else: error_msg = u'<strong>Oops!</strong> Your comment was blank.' if request.is_ajax(): return HttpResponseBadRequest(error_msg) else: messages.error(request, error_msg) return HttpResponseRedirect(reverse( 'datalocker:submission_view', kwargs={'locker_id': locker_id, 'submission_id': submission_id} )) @login_required @never_cache @prevent_url_guessing @require_http_methods(['POST']) def comment_modify(request, locker_id, submission_id): """Modifies the existing comment if it is still editable""" comment = get_object_or_404(Comment, id=request.POST.get('id', '')) if comment.is_editable and comment.user == request.user: comment_text = request.POST.get('comment', '').strip() comment.comment = comment_text comment.save() if request.is_ajax(): return JsonResponse({ 'comment': comment_text, 'id': comment.id, }) else: messages.success(request, u'<strong>Success!</strong> ' u'Your comment was added to the discussion.') else: error_msg = u"<strong>D'oh!</strong> This comment is no longer editable." # NOQA if request.is_ajax(): return HttpResponseBadRequest(error_msg) else: messages.warning(request, error_msg) return HttpResponseRedirect(reverse( 'datalocker:submission_view', kwargs={ 'locker_id': comment.submission.locker.id, 'submission_id': comment.submission.id, } )) @login_required @never_cache @prevent_url_guessing @require_http_methods(['GET', 'HEAD']) def comments_list(request, locker_id, submission_id): """Returns a list of comments for the specified submission""" submission = get_object_or_404(Submission, pk=submission_id) if submission.locker.discussion_enabled(): is_owner = submission.locker.is_owner(request.user) is_user = submission.locker.is_user(request.user) discussion_users = submission.locker.discussion_users_have_access() if is_owner or (is_user and discussion_users) or request.user.is_superuser: # NOQA if request.is_ajax(): color_helper = UserColors(request) comments = [] comment_objs = submission.comments.order_by('parent', '-timestamp') # NOQA for comment in comment_objs: comment_dict = comment.to_dict() comment_dict['user']['color'] = color_helper.get(comment.user.username) # NOQA if comment.user != request.user: comment_dict['editable'] = False comments.append(comment_dict) return JsonResponse({ 'discussion': comments, 'editing_time_value': settings.COMMENT_EDIT_MAX, 'editing_time_units': 'minutes', }) if request.is_ajax(): error_msg = u'The user does not have permission to view the discussion.' # NOQA return HttpResponseBadRequest(error_msg) else: return HttpResponseRedirect(reverse( 'datalocker:submission_view', kwargs={'locker_id': locker_id, 'submission_id': submission_id} )) @csrf_exempt @never_cache def form_submission_view(request, **kwargs): """Handles submissions from outside forms to be saved in lockers""" # redirect non-form submissions to the main page if request.method != 'POST': return HttpResponseRedirect(reverse('datalocker:index')) safe_values = { 'identifier': request.POST.get('form-id', '').strip(), 'name': request.POST.get('name', 'New Locker').strip(), 'url': request.POST.get('url', '').strip(), 'owner_name': request.POST.get('owner', '').strip(), 'data': request.POST.get('data', '').strip(), } try: safe_values['owner'] = User.objects.get(username=safe_values['owner_name']) # NOQA except User.DoesNotExist: safe_values['owner'] = None Locker.objects.add_submission(safe_values, request=request) return HttpResponse(status=201) @login_required @never_cache @prevent_url_guessing @require_http_methods(['POST']) def locker_archive(request, locker_id): """Archive a locker so it receives no new submissions""" locker = get_object_or_404(Locker, id=locker_id) locker.archive_timestamp = timezone.now() locker.save() if request.is_ajax(): return JsonResponse({'locker_id': locker_id}) else: return HttpResponseRedirect(reverse('datalocker:index')) @login_required() @never_cache @require_http_methods(['GET', 'HEAD']) def locker_list_view(request): """Return list of lockers for the current user The list includes lockers for which the current user is an owner and lockers for which the current user is included in the list of shared users. """ context = {} context['owned'] = (Locker.objects .active() .has_access(request.user) .include_latest() .filter(owner=request.user)) context['shared'] = (Locker.objects .active() .has_access(request.user) .include_latest() .exclude(owner=request.user)) if request.user.is_superuser: context['all'] = (Locker.objects.include_latest()) context['orphaned'] = (Locker.objects .filter(owner=None) .include_latest()) return render(request, 'datalocker/index.html', context) @login_required @never_cache @prevent_url_guessing @require_http_methods(['POST']) def locker_unarchive(request, locker_id): """Unarchives a locker so it can receive new submissions""" locker = get_object_or_404(Locker, id=locker_id) locker.archive_timestamp = None locker.save() if request.is_ajax(): return JsonResponse({'locker_id': locker_id}) else: return HttpResponseRedirect(reverse('datalocker:index')) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['POST']) def locker_user_add(request, locker_id): """Adds the specified user to the locker's list of shared users""" if request.is_ajax(): locker = get_object_or_404(Locker, id=locker_id) user = get_object_or_404(User, email=request.POST.get('email', '')) if user not in locker.users.all(): locker.users.add(user) from_addr = get_from_address('locker access granted') if from_addr: subject = u'Access to Locker: {}'.format(locker.name) to_addr = user.email url = request.build_absolute_uri(reverse( 'datalocker:submissions_list', kwargs={'locker_id': locker.id} )) message = (u'The following Data Locker of form submissions ' u'has been shared with you.\n\n' u'Locker: {}\n\n' u'You can view the submissions at:\n{}\n' u''.format(locker.name, url)) try: send_mail(subject, message, from_addr, [to_addr]) except SMTPException: logger.exception(u'Locker shared with you email failed to send') # NOQA return JsonResponse({'user': get_public_user_dict(user)}) else: return HttpResponseRedirect(reverse('datalocker:index')) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['POST']) def locker_user_delete(request, locker_id): """Removes the specified user from the locker's list of users""" if request.is_ajax(): locker = get_object_or_404(Locker, id=locker_id) try: user = get_object_or_404(User, id=request.POST.get('id', '')) except ValueError: error_msg = u'An invalid user was requested to be deleted.' return HttpResponseBadRequest(error_msg) else: if user in locker.users.all(): locker.users.remove(user) return JsonResponse({'user_id': user.id}) if error_msg: error_msg = u'<strong>Oops</strong> {}'.format(error_msg) messages.error(request, error_msg) return HttpResponseRedirect(reverse('datalocker:index')) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['GET', 'HEAD']) def locker_users(request, locker_id): if request.is_ajax(): locker = get_object_or_404(Locker, pk=locker_id) users = [ get_public_user_dict(user) for user in locker.users.all() ] return JsonResponse({'users': users}) else: return HttpResponseRedirect(reverse('datalocker:index')) @never_cache def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): return auth_login( request, template_name, redirect_field_name, authentication_form, current_app, extra_context ) @never_cache def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): return auth_logout( request, next_page, template_name, redirect_field_name, current_app, extra_context ) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['POST']) def modify_locker(request, **kwargs): """Modifies locker name, ownership, and settings""" locker = get_object_or_404(Locker, id=kwargs['locker_id']) previous_owner = locker.owner if not locker.owner: previous_owner = request.user new_locker_name = request.POST.get('locker-name', '') new_owner_email = request.POST.get('locker-owner', '') if new_locker_name != '': locker.name = new_locker_name if new_owner_email != '': try: new_owner = User.objects.get(email=new_owner_email) except User.DoesNotExist: logger.error(u'Attempted to reassign locker ({}) ' u'to non-existent user ({})' u''.format(locker.name, new_owner_email)) messages.error(request, u'<strong>Oops!</strong> The user ({}) you tried ' u'to make the owner of the <strong>{}</strong> ' u'locker does not exist. ' u'<strong>You still own the locker.</strong>' u''.format(new_owner_email, locker.name)) else: locker.owner = new_owner from_addr = get_from_address(u'change locker owner') if from_addr: subject = u'Ownership of Locker: {}'.format(locker.name) to_addr = new_owner_email previous_name = u'{} {}'.format(previous_owner.first_name, previous_owner.last_name) url = request.build_absolute_uri(reverse( 'datalocker:submissions_list', kwargs={'locker_id': locker.id} )) message = (u'{} has changed the ownership of the following ' u'locker of form submissions to you.\n\n' u'Locker: {}\n\n' u'You can view the submissions at:\n{}\n' u''.format(previous_name, locker.name, url)) try: send_mail(subject, message, from_addr, [to_addr]) except SMTPException: logger.exception(u'Locker ownership changed to you email failed to send') # NOQA locker.save() # update the locker settings locker.shared_users_notification( bool(request.POST.get('shared-users', False)) ) locker.workflow_enabled( bool(request.POST.get('workflow-enable', False)) ) locker.workflow_users_can_edit( bool(request.POST.get('workflow-users-can-edit', False)) ) locker.workflow_states(request.POST.get('workflow-states', '')) locker.discussion_enabled( bool(request.POST.get('discussion-enable', False)) ) locker.discussion_users_have_access( bool(request.POST.get('discussion-users-have-access', False)) ) return HttpResponseRedirect(reverse('datalocker:index')) @never_cache def password_change(request, template_name='registration/password_change_form.html', post_change_redirect=None, password_change_form=PasswordChangeForm, current_app=None, extra_context=None): return auth_password_change( request, template_name, post_change_redirect, password_change_form, current_app, extra_context ) @never_cache def password_change_done(request, template_name='registration/password_change_done.html', # NOQA current_app=None, extra_context=None): return auth_password_change_done( request, template_name, current_app, extra_context ) @permission_required('datalocker.add_manual_submission') @login_required() @require_http_methods(['POST']) @never_cache def submission_add(request, locker_id): """Manually add a submission to a locker Arguments: request {obj} -- Django HTTP Request object instance locker_id {int} -- Unique identifier for the Locker to add the submission to """ locker = get_object_or_404(Locker, id=locker_id) json_data = request.POST.get('json', '').strip() json_data = json_data.replace('\r', '') json_data = json_data.replace('\n', '') json_data = json_data.replace('<div>', '') json_data = json_data.replace('</div>', '') json_data = json_data.replace('<br />', '\\r\\n') json_data = json_data.replace('<br>', '\\r\\n') if json_data[-3:] == '",}': json_data = json_data[:-3] + '"}' Locker.objects.add_submission( {'data': json_data}, request=request, locker=locker ) return HttpResponseRedirect(reverse( 'datalocker:submissions_list', kwargs={'locker_id': locker_id} )) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['POST']) def submission_delete(request, locker_id, submission_id): """Marks a submission as deleted""" submission = get_object_or_404(Submission, id=submission_id) submission.deleted = timezone.now() submission.save() if request.is_ajax(): return JsonResponse({ 'id': submission.id, 'timestamp': submission.timestamp, 'deleted': submission.deleted, 'purge_timestamp': submission.purge_date, }) else: return HttpResponseRedirect(reverse( 'datalocker:submissions_list', kwargs={'locker_id': locker_id} )) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['POST']) def submission_undelete(request, locker_id, submission_id): """Removes the deleted timestamp from a submission""" submission = get_object_or_404(Submission, id=submission_id) submission.deleted = None submission.save() if request.is_ajax(): return JsonResponse({ 'id': submission.id, 'timestamp': submission.timestamp, }) else: return HttpResponseRedirect(reverse( 'datalocker:submissions_list', kwargs={'locker_id': locker_id} )) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['GET', 'HEAD']) def submission_view(request, locker_id, submission_id): """Displays an individual submission""" submission = get_object_or_404(Submission, pk=submission_id) newer = submission.newer() newest = Submission.objects.newest(submission.locker) if not newest: newest = submission oldest = Submission.objects.oldest(submission.locker) if not oldest: oldest = submission older = submission.older() discussion_enabled = submission.locker.discussion_enabled() is_owner = submission.locker.owner == request.user users_discussion = submission.locker.discussion_users_have_access() users_workflow = submission.locker.workflow_users_can_edit() workflow_enabled = submission.locker.workflow_enabled() # generate a message to the user if the submission is deleted if submission.deleted: messages.warning(request, u'<strong>Heads up!</strong> This submission has ' u'been deleted and <strong>will be permanently ' u'removed</strong> from the locker ' u'<strong>{}</strong>.' u''.format(naturaltime(submission.purge_date))) return render(request, 'datalocker/submission_view.html', { 'data': submission.data_dict(with_types=True), 'discussion_enabled': discussion_enabled, 'discussion_users_have_access': users_discussion or is_owner, 'newer': newer, 'newer_disabled': True if submission.id == newer.id else False, 'newest': newest, 'newest_disabled': True if submission.id == newest.id else False, 'older': older, 'older_disabled': True if submission.id == older.id else False, 'oldest': oldest, 'oldest_disabled': True if submission.id == oldest.id else False, 'sidebar_enabled': workflow_enabled or discussion_enabled, 'submission': submission, 'workflow_enabled': workflow_enabled, 'workflow_states': submission.locker.workflow_states(), 'workflow_state': submission.workflow_state, 'workflow_users_can_edit': users_workflow or is_owner, }) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['GET', 'HEAD', 'POST']) def submissions_list_view(request, locker_id): """Returns a list of submissions for the specified locker""" locker = get_object_or_404(Locker, pk=locker_id) if request.method == 'POST': # Save the selected fields to include in the submissions list locker.fields_selected(request.POST) return HttpResponseRedirect(reverse( 'datalocker:submissions_list', kwargs={'locker_id': locker_id} )) is_owner = locker.owner == request.user selected_fields = locker.fields_selected() context = { 'allow_maintenance_mode': is_owner or request.user.is_superuser, 'column_headings': ['Submitted date', ] + selected_fields, 'data': [], 'fields_list': locker.fields_all(), 'linkable_indices': [], 'locker': locker, 'purge_days': settings.SUBMISSION_PURGE_DAYS, 'selected_fields': selected_fields, } ## # Build the data that is made available to the template # # context['data'] contains all the data and metadata for displaying # the table of submissions. # # Format: # [ # [<list of table cell data>], # submission id, # deleted (True/False), # purged date # ] ## for submission in locker.submissions.order_by('-timestamp'): entry_data = [submission.timestamp, ] submission_data = submission.data_dict() for field in selected_fields: try: entry_data.append(submission_data[field]) except KeyError: if field == 'Workflow state': entry_data.append(submission.workflow_state) context['data'].append([ entry_data, submission.id, True if submission.deleted else False, submission.purge_date, ]) # determine which indices in the cell data list will be linked try: context['linkable_indices'].append( context['column_headings'].index('Submitted date') ) except ValueError: pass if not context['linkable_indices']: context['linkable_indices'] = [0, ] return render(request, 'datalocker/submissions_list.html', context) @never_cache @require_http_methods(['GET', 'HEAD']) def testing_bad_request_view(request): """Displays a custom bad request (400) page""" return render(request, '400.html', {}) @never_cache @require_http_methods(['GET', 'HEAD']) def testing_forbidden_view(request): """Displays a custom forbidden (403) page""" return render(request, '403.html', {}) @never_cache @require_http_methods(['GET', 'HEAD']) def testing_not_found_view(request): """Displays a custom not found (404) page""" return render(request, '404.html', {}) @never_cache @require_http_methods(['GET', 'HEAD']) def testing_server_error_view(request): """Displays a custom internal server error (500) page""" return render(request, '500.html', {}) @login_required() @never_cache @require_http_methods(['GET', 'HEAD']) def users_list(request, **kwargs): """Returns a list of all the user email addresses in the system This is used to power the owner and shared user auto-complete which is driven by TypeAhead.js. """ users_list = [] for user in User.objects.all(): users_list.append({ 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name, }) return JsonResponse({'users': users_list}) @login_required() @never_cache @prevent_url_guessing @require_http_methods(['POST']) def workflow_modify(request, locker_id, submission_id): submission = get_object_or_404(Submission, pk=submission_id) new_state = request.POST.get('workflow-state', '') if new_state in submission.locker.workflow_states(): submission.workflow_state = new_state submission.save() if request.is_ajax(): return JsonResponse({'state': new_state}) else: error_msg = u'<strong>Oops!</strong> Unknown workflow state specified.' if request.is_ajax(): return HttpResponseBadRequest(error_msg, content_type='text/plain') else: messages.error(request, error_msg) return HttpResponseRedirect(reverse( 'datalocker:submission_view', kwargs={ 'locker_id': submission.locker.id, 'submission_id': submission.id, } ))
# SecretStorage module for Python # Access passwords using the SecretService DBus API # Author: Dmitry Shachnev, 2013-2018 # License: 3-clause BSD, see LICENSE file """SecretStorage item contains a *secret*, some *attributes* and a *label* visible to user. Editing all these properties and reading the secret is possible only when the :doc:`collection <collection>` storing the item is unlocked. The collection can be unlocked using collection's :meth:`~secretstorage.collection.Collection.unlock` method.""" from typing import Dict, Optional from jeepney.integrate.blocking import DBusConnection from secretstorage.defines import SS_PREFIX from secretstorage.dhcrypto import Session from secretstorage.exceptions import LockedException, PromptDismissedException from secretstorage.util import DBusAddressWrapper, \ exec_prompt, open_session, format_secret, unlock_objects from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend ITEM_IFACE = SS_PREFIX + 'Item' class Item(object): """Represents a secret item.""" def __init__(self, connection: DBusConnection, item_path: str, session: Optional[Session] = None) -> None: self.item_path = item_path self._item = DBusAddressWrapper(item_path, ITEM_IFACE, connection) self._item.get_property('Label') self.session = session self.connection = connection def __eq__(self, other: "DBusConnection") -> bool: assert isinstance(other.item_path, str) return self.item_path == other.item_path def is_locked(self) -> bool: """Returns :const:`True` if item is locked, otherwise :const:`False`.""" return bool(self._item.get_property('Locked')) def ensure_not_locked(self) -> None: """If collection is locked, raises :exc:`~secretstorage.exceptions.LockedException`.""" if self.is_locked(): raise LockedException('Item is locked!') def unlock(self) -> bool: """Requests unlocking the item. Usually, this means that the whole collection containing this item will be unlocked. Returns a boolean representing whether the prompt has been dismissed; that means :const:`False` on successful unlocking and :const:`True` if it has been dismissed. .. versionadded:: 2.1.2 .. versionchanged:: 3.0 No longer accepts the ``callback`` argument. """ return unlock_objects(self.connection, [self.item_path]) def get_attributes(self) -> Dict[str, str]: """Returns item attributes (dictionary).""" attrs = self._item.get_property('Attributes') return dict(attrs) def set_attributes(self, attributes: Dict[str, str]) -> None: """Sets item attributes to `attributes` (dictionary).""" self._item.set_property('Attributes', 'a{ss}', attributes) def get_label(self) -> str: """Returns item label (unicode string).""" label = self._item.get_property('Label') assert isinstance(label, str) return label def set_label(self, label: str) -> None: """Sets item label to `label`.""" self.ensure_not_locked() self._item.set_property('Label', 's', label) def delete(self) -> None: """Deletes the item.""" self.ensure_not_locked() prompt, = self._item.call('Delete', '') if prompt != "/": dismissed, _result = exec_prompt(self.connection, prompt) if dismissed: raise PromptDismissedException('Prompt dismissed.') def get_secret(self) -> bytes: """Returns item secret (bytestring).""" self.ensure_not_locked() if not self.session: self.session = open_session(self.connection) secret, = self._item.call('GetSecret', 'o', self.session.object_path) if not self.session.encrypted: return bytes(secret[2]) aes = algorithms.AES(self.session.aes_key) aes_iv = bytes(secret[1]) decryptor = Cipher(aes, modes.CBC(aes_iv), default_backend()).decryptor() encrypted_secret = secret[2] padded_secret = decryptor.update(encrypted_secret) + decryptor.finalize() assert isinstance(padded_secret, bytes) return padded_secret[:-padded_secret[-1]] def get_secret_content_type(self) -> str: """Returns content type of item secret (string).""" self.ensure_not_locked() if not self.session: self.session = open_session(self.connection) secret, = self._item.call('GetSecret', 'o', self.session.object_path) return str(secret[3]) def set_secret(self, secret: bytes, content_type: str = 'text/plain') -> None: """Sets item secret to `secret`. If `content_type` is given, also sets the content type of the secret (``text/plain`` by default).""" self.ensure_not_locked() if not self.session: self.session = open_session(self.connection) _secret = format_secret(self.session, secret, content_type) self._item.call('SetSecret', '(oayays)', _secret) def get_created(self) -> int: """Returns UNIX timestamp (integer) representing the time when the item was created. .. versionadded:: 1.1""" created = self._item.get_property('Created') assert isinstance(created, int) return created def get_modified(self) -> int: """Returns UNIX timestamp (integer) representing the time when the item was last modified.""" modified = self._item.get_property('Modified') assert isinstance(modified, int) return modified
from django.core.exceptions import ValidationError from django.test import TestCase import ipaddress import pytest from django_inet.models import ( URLField, ASNField, IPAddressField, IPPrefixField, MacAddressField, ) from models import FullModel def assert_ip_validator(obj): """ assert the validator is set correctly and referring to the correct object """ assert 0 == len(obj.default_validators) assert 1 == len(obj.validators) assert obj == obj.validators[0].field assert obj.version == obj.validators[0].field.version class ModelTests(TestCase): """ test model functionality """ def test_init(self): model = FullModel() new0 = URLField() new1 = URLField() assert 1 == len(new0.default_validators) assert 1 == len(new1.default_validators) new0 = ASNField() new1 = ASNField() assert 0 == len(new0.default_validators) assert 0 == len(new1.default_validators) new0 = IPAddressField() new1 = IPAddressField() assert_ip_validator(new0) assert_ip_validator(new1) new0 = IPPrefixField() new1 = IPPrefixField() assert_ip_validator(new0) assert_ip_validator(new1) new0 = MacAddressField() new1 = MacAddressField() assert 1 == len(new0.default_validators) assert 1 == len(new1.default_validators) def test_blank(self): model = FullModel() model.full_clean() def test_asn(self): model = FullModel() model.asn = 42 assert 42 == model.asn model.full_clean() with pytest.raises(ValidationError): model.asn = 'invalid' model.full_clean() def test_ipaddress(self): model = FullModel() model.ip_address = '10.0.0.0' assert ipaddress.ip_address(u'10.0.0.0') == model.ip_address with pytest.raises(ValidationError): model.ip_address = 'invalid' def test_ipv4(self): model = FullModel() model.ipv4 = '10.0.0.0' assert ipaddress.ip_address(u'10.0.0.0') == model.ipv4 with pytest.raises(ValidationError): model.ipv4 = '1::1' def test_ipv6(self): model = FullModel() model.ipv6 = '10::' assert ipaddress.ip_address(u'10::') == model.ipv6 with pytest.raises(ValidationError): model.ipv6 = '10.0.0.0' def test_ipprefix(self): model = FullModel() model.prefix = '10.0.0.0/8' with pytest.raises(ValidationError): model.prefix = 'invalid' def test_mac(self): model = FullModel() model.mac = 'Ff:00:00:12:34:56' model.full_clean() assert 'Ff:00:00:12:34:56' == model.mac with pytest.raises(ValidationError): model.mac = 'invalid' model.full_clean()
#generates a series using a function which takes first and last values, # generates four terms = equidistant # e.g., if two numbers passed are 1 and 7 then function returns 1 3 5 7. #a**n = a + (n-1)d #a = 1, n = 4 terms, a**n = 7 = last term #d = 2 def generateSeries(number1, number2): if number1 == number2: print("Error! End limits' can't be equal") difference = int((number2 - number1)/3) #d = a**n - a/(n-1) print("Series: = ",number1, number1 * difference, number1 + 2 * difference, number2) print(generateSeries(1,7)) print(generateSeries(2,8))
import matplotlib.pyplot as plt import numpy as np def tunediagram(order=range(1,4),integer=[0,0],lines=[1,1,1,1],colors='ordered',linestyle='-',fig=plt.gcf()): ''' plot resonance diagram up to specified order mx + ny = p x = (p-ny)/m x = 1 where y = (p-m)/n EXAMPLE: tunediagram(order=[1,2,3]) tunediagram([1,2,3],integer=[6,8],lines=[0,0,1,1]) tunediagram([1,2,3],integer=[6,8],lines=[0,0,1,1], colors='black3', linestyle='--') INPUT: 1. order - array of tune orders to plot. e.g. up to 3rd order, [1,2,3] 2. integers - integer part of the tune to plot in x,y, default is [0,0]. e.g. plot from 6-7 and 9-10, integer=[6,9] 2. lines - a boolean of which resonance lines to plot. e.g. [vertical,horizontal,sum,diff]. e.g. plot only vert/horz lines, lines = [1,1,0,0] 4. colors - option to plot lines in different colors. default is ordered. color options only go up to 10th order ordered - each order resonance is a different color black - all lines are black blackX - X here is a number. all resonances X+ will be in black. e.g. black3 means plot resonances 1-2 in color and 3,4,5,... in black 6. linestyle - linestyle option from matplotlib 7. fig - pass in a handle to a figure, otherwise things will be plotted in the current figure. Written by Levon Dovlatyan University of Maryland, Department of Physics Oct 2018 ''' # define some variables pval = 40 # increase for more/higher order lines p = np.linspace(0,pval,pval+1) qxmin,qymin = integer[0],integer[1] qxmax,qymax = qxmin+1,qymin+1 # define different colors, up to 10th order color = ['C0','C1','C2','C3','C4','C5','C6','C7','C8','C9'] if colors == 'black': color = ['k']*10 elif colors[0:-1] == 'black': idx = int(colors[-1]) color = color[0:idx-1] + (['k']*10)[idx-1:] # adjust plot limits plt.xlim((qxmin-0.01, qxmax+0.01)) plt.ylim((qymin-0.01, qymax+0.01)) # Plotting formula # we plot resonances in reverse order for i in order[::-1]: m = np.linspace(-i,i,2*i+1) n1 = (i-np.abs(m)) n2 = -1*n1 for j in range(0,m.size,1): # check to see equation is divided by 0 or not # ver & hor res lines if ((n1[j] == 0 and lines[1]) or (m[j] == 0 and lines[0])): # vertical lines if n1[j] == 0 and lines[1]: plt.vlines(p/m[j],qymin,qymax,color=color[i-1],linestyle=linestyle); # horizontal lines if m[j] == 0 and lines[0]: plt.hlines(p/n1[j],qxmin,qxmax,color=color[i-1],linestyle=linestyle); plt.hlines(p/n2[j],qxmin,qxmax,color=color[i-1],linestyle=linestyle); # sum and dif res lines elif not(n1[j] == 0) and not(m[j] == 0): # resonance sum lines if lines[2]: if np.sign(m[j]) > 0: plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n2[j] - np.array(m[j]*qxmin/n2[j]), p/n2[j] - np.array(m[j]*qxmax/n2[j])],color=color[i-1],linestyle=linestyle); else: plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n1[j] - np.array(m[j]*qxmin/n1[j]), p/n1[j] - np.array(m[j]*qxmax/n1[j])],color=color[i-1],linestyle=linestyle); # resonance dif lines if lines[3]: if np.sign(m[j]) > 0: plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n1[j] - np.array(m[j]*qxmin/n1[j]), p/n1[j] - np.array(m[j]*qxmax/n1[j])],color=color[i-1],linestyle=linestyle); else: plt.plot([[qxmin]*p.size,[qxmax]*p.size],[p/n2[j] - np.array(m[j]*qxmin/n2[j]), p/n2[j] - np.array(m[j]*qxmax/n2[j])],color=color[i-1],linestyle=linestyle);
# Copyright 2019 Kaloom, Inc. All rights reserved. # Copyright 2012 Cisco Systems, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os, pwd, grp import selinux import libvirt from lxml import objectify from neutron_lib import constants as n_const from neutron.agent import rpc as agent_rpc from neutron.common import rpc as common_rpc from oslo_log import log import oslo_messaging from kaloom_kvs_agent.common \ import constants as a_const LOG = log.getLogger(__name__) class kvsPluginApi(agent_rpc.PluginApi): def __init__(self, topic): target = oslo_messaging.Target(topic=topic, version='1.0') self.client = common_rpc.get_client(target) def get_knid(self, context, network_id): cctxt = self.client.prepare() LOG.info(_("KVS: RPC get_knid is called for network_id: %s."), network_id) return cctxt.call(context, 'get_knid', network_id=network_id) def get_mac(self, context, port_id): cctxt = self.client.prepare() LOG.info(_("KVS: RPC get_mac is called for port_id: %s."), port_id) return cctxt.call(context, 'get_mac', port_id=port_id) def get_parent_port_info(self, context, trunk_id): cctxt = self.client.prepare() LOG.info(_("KVS: RPC get_parent_port_info is called for trunk_id: %s."), trunk_id) return cctxt.call(context, 'get_parent_port_info', trunk_id=trunk_id) def get_info_sub_port(self, context, subport_ids): cctxt = self.client.prepare() LOG.info(_("KVS: RPC get_info_sub_port is called for subport_ids: %s."), subport_ids) return cctxt.call(context, 'get_info_sub_port', port_ids=subport_ids) def get_tap_device_name(interface_id): """Convert port ID into device name format expected by KVS""" if interface_id is None: LOG.warning("Invalid Interface ID, will lead to incorrect " "tap device name") tap_device_name = (n_const.TAP_DEVICE_PREFIX + interface_id[:a_const.RESOURCE_ID_LENGTH]) return tap_device_name def mac2ipv6(mac): # only accept MACs separated by a colon parts = mac.split(":") # modify parts to match IPv6 value parts.insert(3, "ff") parts.insert(4, "fe") parts[0] = "%x" % (int(parts[0], 16) ^ 2) # format output ipv6Parts = [] for i in range(0, len(parts), 2): ipv6Parts.append("".join(parts[i:i+2])) ipv6 = "fe80::%s" % (":".join(ipv6Parts)) return ipv6 def get_libvirt_capabilities_secmodel(): # secmodel defined in /etc/libvirt/qemu.conf # supports security_driver as [ "selinux", "apparmor" ] # The DAC security driver is always enabled; # SELinux basic confinement (root:system_r:qemu_t), SELinux sVirt confinement (system_u:system_r:svirt_t:s0), AppArmor sVirt confinement.. result = {} conn = libvirt.openReadOnly('qemu:///system') if conn == None: LOG.error("Failed to open connection to qemu:///system") return None raw_xml = conn.getCapabilities() conn.close() LOG.debug('Capabilities:\n %s', raw_xml) xml_root = objectify.fromstring(raw_xml).getroottree() secmodels = xml_root.findall('//secmodel') for secmodel in secmodels: model = secmodel.find("model") result[model]={} baselabels = secmodel.findall('baselabel') for baselabel in baselabels: type = baselabel.attrib['type'] label = baselabel.text result[model][type] = label return result def get_qemu_process_user(): dac_model = 'dac' virt_type = 'kvm' # read from /etc/nova/nova.conf secmodels = get_libvirt_capabilities_secmodel() if secmodels is None: return None LOG.debug('libvirt secmodels %s', secmodels) #{'selinux': {'kvm': 'system_u:system_r:svirt_t:s0', 'qemu': 'system_u:system_r:svirt_tcg_t:s0'}, 'dac': {'kvm': '+107:+107', 'qemu': '+107:+107'}} if dac_model in secmodels.keys() and virt_type in secmodels[dac_model].keys(): user_group = secmodels[dac_model][virt_type] user = user_group.split(':')[0] if user[0] == '+': #leading + forces numeric uid uid = int(user[1:]) return pwd.getpwuid(uid).pw_name else: return user else: return None def check_permission(path): #check selinux context_t if selinux.is_selinux_enabled(): context_t = selinux.getfilecon(path)[1].split(":")[2] #openstack-selinux already supports /var/run folder with var_run_t context. #for other folder, we expect virt_cache_t context. if not (((path == '/var/run' or path.startswith('/var/run/')) and context_t == 'var_run_t') or context_t == 'virt_cache_t'): msg = "selinux context is not properly configured on %s" % (path) return False, msg #check rx permission for qemu-kvm-user ##user that the (libvirt managed) QEMU VM(process)s are run as: that utimately requires permission on vhost sockets. ##The default user is "qemu" for RHEL7.5 (the comment in /etc/libvirt/qemu.conf seems wrong, which says default is root) ##ps -ef shows |grep qemu, confirms the user. ##We are checking "libvirt capabilities" to find out the user. qemu_kvm_user = get_qemu_process_user() if qemu_kvm_user is None: msg = "qemu_kvm_user couldnot be found." return False, msg uid_qemu_kvm_user = pwd.getpwnam(qemu_kvm_user).pw_uid gid_groups_qemu_kvm_user = [g.gr_gid for g in grp.getgrall() if qemu_kvm_user in g.gr_mem] stat_obj = os.stat(path) uid_path = stat_obj.st_uid gid_path = stat_obj.st_gid chmod_path = oct(stat_obj.st_mode)[-3:] #e.g. '755' #user falls in user/group/other if uid_path == uid_qemu_kvm_user: index = 0 elif gid_path in gid_groups_qemu_kvm_user: index = 1 else: index = 2 #check rx permission if chmod_path[index] in ['5', '7']: return True, '' else: msg = "%s does not have read/execute permission set on %s" % (qemu_kvm_user, path) return False, msg
# # Autogenerated by Thrift Compiler (0.13.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException from thrift.protocol.TProtocol import TProtocolException from thrift.TRecursive import fix_spec import sys from thrift.transport import TTransport all_structs = [] class ChannelErrorCode(object): ILLEGAL_ARGUMENT = 0 INTERNAL_ERROR = 1 CONNECTION_ERROR = 2 AUTHENTICATIONI_FAILED = 3 NEED_PERMISSION_APPROVAL = 4 COIN_NOT_USABLE = 5 WEBVIEW_NOT_ALLOWED = 6 _VALUES_TO_NAMES = { 0: "ILLEGAL_ARGUMENT", 1: "INTERNAL_ERROR", 2: "CONNECTION_ERROR", 3: "AUTHENTICATIONI_FAILED", 4: "NEED_PERMISSION_APPROVAL", 5: "COIN_NOT_USABLE", 6: "WEBVIEW_NOT_ALLOWED", } _NAMES_TO_VALUES = { "ILLEGAL_ARGUMENT": 0, "INTERNAL_ERROR": 1, "CONNECTION_ERROR": 2, "AUTHENTICATIONI_FAILED": 3, "NEED_PERMISSION_APPROVAL": 4, "COIN_NOT_USABLE": 5, "WEBVIEW_NOT_ALLOWED": 6, } class ChannelException(TException): """ Attributes: - code - reason - parameterMap """ def __init__(self, code=None, reason=None, parameterMap=None,): self.code = code self.reason = reason self.parameterMap = parameterMap def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.code = iprot.readI32() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.reason = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 3: if ftype == TType.MAP: self.parameterMap = {} (_ktype1, _vtype2, _size0) = iprot.readMapBegin() for _i4 in range(_size0): _key5 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() _val6 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() self.parameterMap[_key5] = _val6 iprot.readMapEnd() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('ChannelException') if self.code is not None: oprot.writeFieldBegin('code', TType.I32, 1) oprot.writeI32(self.code) oprot.writeFieldEnd() if self.reason is not None: oprot.writeFieldBegin('reason', TType.STRING, 2) oprot.writeString(self.reason.encode('utf-8') if sys.version_info[0] == 2 else self.reason) oprot.writeFieldEnd() if self.parameterMap is not None: oprot.writeFieldBegin('parameterMap', TType.MAP, 3) oprot.writeMapBegin(TType.STRING, TType.STRING, len(self.parameterMap)) for kiter7, viter8 in self.parameterMap.items(): oprot.writeString(kiter7.encode('utf-8') if sys.version_info[0] == 2 else kiter7) oprot.writeString(viter8.encode('utf-8') if sys.version_info[0] == 2 else viter8) oprot.writeMapEnd() oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __str__(self): return repr(self) def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class ChannelToken(object): """ Attributes: - token - obsToken - expiration - refreshToken - channelAccessToken """ def __init__(self, token=None, obsToken=None, expiration=None, refreshToken=None, channelAccessToken=None,): self.token = token self.obsToken = obsToken self.expiration = expiration self.refreshToken = refreshToken self.channelAccessToken = channelAccessToken def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.token = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.obsToken = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I64: self.expiration = iprot.readI64() else: iprot.skip(ftype) elif fid == 4: if ftype == TType.STRING: self.refreshToken = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 5: if ftype == TType.STRING: self.channelAccessToken = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('ChannelToken') if self.token is not None: oprot.writeFieldBegin('token', TType.STRING, 1) oprot.writeString(self.token.encode('utf-8') if sys.version_info[0] == 2 else self.token) oprot.writeFieldEnd() if self.obsToken is not None: oprot.writeFieldBegin('obsToken', TType.STRING, 2) oprot.writeString(self.obsToken.encode('utf-8') if sys.version_info[0] == 2 else self.obsToken) oprot.writeFieldEnd() if self.expiration is not None: oprot.writeFieldBegin('expiration', TType.I64, 3) oprot.writeI64(self.expiration) oprot.writeFieldEnd() if self.refreshToken is not None: oprot.writeFieldBegin('refreshToken', TType.STRING, 4) oprot.writeString(self.refreshToken.encode('utf-8') if sys.version_info[0] == 2 else self.refreshToken) oprot.writeFieldEnd() if self.channelAccessToken is not None: oprot.writeFieldBegin('channelAccessToken', TType.STRING, 5) oprot.writeString(self.channelAccessToken.encode('utf-8') if sys.version_info[0] == 2 else self.channelAccessToken) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class WebLoginResponse(object): """ Attributes: - returnUrl - optionalReturnUrl - redirectConfirmationPageUrl """ def __init__(self, returnUrl=None, optionalReturnUrl=None, redirectConfirmationPageUrl=None,): self.returnUrl = returnUrl self.optionalReturnUrl = optionalReturnUrl self.redirectConfirmationPageUrl = redirectConfirmationPageUrl def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.returnUrl = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.optionalReturnUrl = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.redirectConfirmationPageUrl = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('WebLoginResponse') if self.returnUrl is not None: oprot.writeFieldBegin('returnUrl', TType.STRING, 1) oprot.writeString(self.returnUrl.encode('utf-8') if sys.version_info[0] == 2 else self.returnUrl) oprot.writeFieldEnd() if self.optionalReturnUrl is not None: oprot.writeFieldBegin('optionalReturnUrl', TType.STRING, 2) oprot.writeString(self.optionalReturnUrl.encode('utf-8') if sys.version_info[0] == 2 else self.optionalReturnUrl) oprot.writeFieldEnd() if self.redirectConfirmationPageUrl is not None: oprot.writeFieldBegin('redirectConfirmationPageUrl', TType.STRING, 3) oprot.writeString(self.redirectConfirmationPageUrl.encode('utf-8') if sys.version_info[0] == 2 else self.redirectConfirmationPageUrl) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class WebLoginRequest(object): """ Attributes: - hookedFullUrl - sessionString - fromIAB - sourceApplication """ def __init__(self, hookedFullUrl=None, sessionString=None, fromIAB=None, sourceApplication=None,): self.hookedFullUrl = hookedFullUrl self.sessionString = sessionString self.fromIAB = fromIAB self.sourceApplication = sourceApplication def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.hookedFullUrl = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRING: self.sessionString = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) elif fid == 3: if ftype == TType.BOOL: self.fromIAB = iprot.readBool() else: iprot.skip(ftype) elif fid == 4: if ftype == TType.STRING: self.sourceApplication = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('WebLoginRequest') if self.hookedFullUrl is not None: oprot.writeFieldBegin('hookedFullUrl', TType.STRING, 1) oprot.writeString(self.hookedFullUrl.encode('utf-8') if sys.version_info[0] == 2 else self.hookedFullUrl) oprot.writeFieldEnd() if self.sessionString is not None: oprot.writeFieldBegin('sessionString', TType.STRING, 2) oprot.writeString(self.sessionString.encode('utf-8') if sys.version_info[0] == 2 else self.sessionString) oprot.writeFieldEnd() if self.fromIAB is not None: oprot.writeFieldBegin('fromIAB', TType.BOOL, 3) oprot.writeBool(self.fromIAB) oprot.writeFieldEnd() if self.sourceApplication is not None: oprot.writeFieldBegin('sourceApplication', TType.STRING, 4) oprot.writeString(self.sourceApplication.encode('utf-8') if sys.version_info[0] == 2 else self.sourceApplication) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) all_structs.append(ChannelException) ChannelException.thrift_spec = ( None, # 0 (1, TType.I32, 'code', None, None, ), # 1 (2, TType.STRING, 'reason', 'UTF8', None, ), # 2 (3, TType.MAP, 'parameterMap', (TType.STRING, 'UTF8', TType.STRING, 'UTF8', False), None, ), # 3 ) all_structs.append(ChannelToken) ChannelToken.thrift_spec = ( None, # 0 (1, TType.STRING, 'token', 'UTF8', None, ), # 1 (2, TType.STRING, 'obsToken', 'UTF8', None, ), # 2 (3, TType.I64, 'expiration', None, None, ), # 3 (4, TType.STRING, 'refreshToken', 'UTF8', None, ), # 4 (5, TType.STRING, 'channelAccessToken', 'UTF8', None, ), # 5 ) all_structs.append(WebLoginResponse) WebLoginResponse.thrift_spec = ( None, # 0 (1, TType.STRING, 'returnUrl', 'UTF8', None, ), # 1 (2, TType.STRING, 'optionalReturnUrl', 'UTF8', None, ), # 2 (3, TType.STRING, 'redirectConfirmationPageUrl', 'UTF8', None, ), # 3 ) all_structs.append(WebLoginRequest) WebLoginRequest.thrift_spec = ( None, # 0 (1, TType.STRING, 'hookedFullUrl', 'UTF8', None, ), # 1 (2, TType.STRING, 'sessionString', 'UTF8', None, ), # 2 (3, TType.BOOL, 'fromIAB', None, None, ), # 3 (4, TType.STRING, 'sourceApplication', 'UTF8', None, ), # 4 ) fix_spec(all_structs) del all_structs
# coding: utf-8 """ IdCheck.IO API Check identity documents OpenAPI spec version: 0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from setuptools import setup, find_packages NAME = "idcheckio_python_client" VERSION = "1.0.0" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"] setup( name=NAME, version=VERSION, description="IdCheck.IO API", author="ariadnext", author_email="dev@ariadnext.com", url="https://www.idcheck.io", keywords=["Swagger", "IdCheck.IO API", "idcheckio", "id", "verifications", "passport", "verification", "visa", "driving", "licence", "permit", "de", "sejour", "passeport", "carte", "d'identite"], install_requires=REQUIRES, packages=find_packages(), include_package_data=True, long_description="""\ Check identity documents """ )
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps helps['signalr'] = """ type: group short-summary: Manage Azure SignalR Service. """ helps['signalr key'] = """ type: group short-summary: Manage keys for Azure SignalR Service. """ helps['signalr list'] = """ type: command short-summary: Lists all the SignalR Service under the current subscription. examples: - name: List SignalR Service and show the results in a table. text: > az signalr list -o table - name: List SignalR Service in a resource group and show the results in a table. text: > az signalr list -g MySignalR -o table """ helps['signalr create'] = """ type: command short-summary: Creates a SignalR Service. examples: - name: Create a SignalR Service with the Basic SKU. text: > az signalr create -n MySignalR -g MyResourceGroup --sku Basic_DS2 --unit-count 1 """ helps['signalr delete'] = """ type: command short-summary: Deletes a SignalR Service. examples: - name: Delete a SignalR Service. text: > az signalr delete -n MySignalR -g MyResourceGroup """ helps['signalr show'] = """ type: command short-summary: Get the details of a SignalR Service. examples: - name: Get the sku for a SignalR Service. text: > az signalr show -n MySignalR -g MyResourceGroup --query sku """ helps['signalr key list'] = """ type: command short-summary: List the access keys for a SignalR Service. examples: - name: Get the primary key for a SignalR Service. text: > az signalr key list -n MySignalR -g MyResourceGroup --query primaryKey -o tsv """ helps['signalr key renew'] = """ type: command short-summary: Regenerate the access key for a SignalR Service. examples: - name: Renew the secondary key for a SignalR Service. text: > az signalr key renew -n MySignalR -g MyResourceGroup --key-type secondary """
#!/usr/bin/env python3 import argparse import logging import textwrap import sys import cryptography.hazmat.primitives import cryptography.x509 LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.StreamHandler()) LOGGER.setLevel(logging.INFO) def get_csr(common_name, out, keyout, rsa_key_size): log = LOGGER # generate private_key, RSA type # TODO support ECDSA type of certificates log.info("Generating a RSA private key...") private_key = cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key( public_exponent=65537, # this is the RSA e exponent. DO NOT CHANGE THIS VALUE! key_size=rsa_key_size ) # save private_key with open(keyout, "wb") as f: f.write( private_key.private_bytes( encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM, format=cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8, encryption_algorithm=cryptography.hazmat.primitives.serialization.NoEncryption() ) ) log.info("Private key saved to %s", keyout) # CSR creation log.info("Building a Certificate Signing Request (CSR)...") builder = cryptography.x509.CertificateSigningRequestBuilder() # set Common Name builder = builder.subject_name(cryptography.x509.Name( [cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.COMMON_NAME, common_name)] )) # set Basic Constraints builder = builder.add_extension(cryptography.x509.BasicConstraints( ca=False, path_length=None), critical=True) # set Key Usage builder = builder.add_extension(cryptography.x509.KeyUsage( digital_signature=True, key_encipherment=True, content_commitment=False, data_encipherment=False, key_agreement=False, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False), critical=True ) # set Extended Key Usage builder = builder.add_extension( cryptography.x509.ExtendedKeyUsage( [cryptography.x509.oid.ExtendedKeyUsageOID.SERVER_AUTH]), critical=False ) # set Common Name in SAN field too builder = builder.add_extension( cryptography.x509.SubjectAlternativeName( [cryptography.x509.DNSName(common_name)]), critical=False ) # sign the CSR with private key csr = builder.sign( private_key, cryptography.hazmat.primitives.hashes.SHA256()) # save CSR to file with open(out, "wb") as f: f.write( csr.public_bytes( encoding=cryptography.hazmat.primitives.serialization.Encoding.DER) ) log.info("CSR saved to %s", out) def main(argv=None): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent("""\ This script generates a CSR in DER format. Example Usage: python3 generate_csr.py --common-name example.com --keyout csr.key --out csr.der --rsa-key-size 2048 """) ) parser.add_argument("--common-name", required=True, help="X509 Common Name string") parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="Suppress output except for errors") parser.add_argument("--rsa-key-size", default=2048, type=int, choices=[2048, 3072, 4096], help="RSA key size in bits") parser.add_argument("--out", default="csr.der", help="Destination of the CSR") parser.add_argument("--keyout", default="csr.key", help="Destination of the CSR private key") args = parser.parse_args(argv) LOGGER.setLevel(args.quiet or LOGGER.level) # TODO add support for arbitrary SAN fields get_csr(args.common_name, args.out, args.keyout, args.rsa_key_size) if __name__ == "__main__": main(sys.argv[1:])
#!/usr/bin/env python import os, sys from run_folds import get_result from hyp_params import get_params, make_dir import numpy as np def main(seed, json_file, subject, scratch, bands, frac_train, randomize_labels=False, pca=False, avg_ff=False, avg_1f=False, ds=False): randomize_labels = str(randomize_labels) if randomize_labels.lower() == 'false': randomize_labels = False else: randomize_labels = True if pca.lower() == 'false': pca = False else: pca = True if avg_ff.lower() == 'false': avg_ff = False else: avg_ff = True if ds.lower() == 'false': ds = False else: ds = True print 'Imports done...' opt_params, fixed_params = get_params(json_file, subject, bands, frac_train, scratch, randomize_labels, pca, avg_ff, avg_1f, ds) rng = np.random.RandomState(int(seed)) job = random_params(rng, opt_params) fixed_params['job_id'] = seed make_dir(fixed_params) get_result(job, fixed_params) def random_params(rng, kwargs): params = {} for key, value in kwargs.iteritems(): if value['type'] == 'float': start = value['min'] width = value['max']-start params[key] = float(width)*rng.rand()+start elif value['type'] == 'int': low = value['min'] high = value['max'] params[key] = rng.randint(low=low, high=high+1) elif value['type'] == 'enum': n = len(value['options']) idx = rng.randint(n) params[key] = value['options'][idx] else: raise ValueError("Bad type '"+str(value['type']) +"' for parameter "+str(key)+'.') return params if __name__ == "__main__": main(*sys.argv[1:])
# Color Ghost # Create a class Ghost # Ghost objects are instantiated without any arguments. # Ghost objects are given a random color attribute # of "white" or "yellow" or "purple" or "red" when instantiated # ghost = Ghost() # ghost.color #=> "white" or "yellow" or "purple" or "red" # Цветной призрак # Создайте класс Ghost # Объекты-призраки создаются без каких-либо аргументов. # Объектам-призракам при создании экземпляра присваивается случайный атрибут # цвета «белый», «желтый», «фиолетовый» или «красный». import random class Ghost(object): def __init__(self, color = ["white", "yellow", "purple", "red"]): self.color = random.choice(color) ghost = Ghost() print(ghost.color)
""" Django settings for interludes project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ try: from . import secret except ImportError: raise ImportError( "The interludes/secret.py file is missing.\n" "Run 'make secret' to generate a secret." ) def import_secret(name): """ Shorthand for importing a value from the secret module and raising an informative exception if a secret is missing. """ try: return getattr(secret, name) except AttributeError: raise RuntimeError("Secret missing: {}".format(name)) SECRET_KEY = import_secret("SECRET_KEY") DB_NAME = import_secret("DB_NAME") ADMINS = import_secret("ADMINS") SERVER_EMAIL = import_secret("SERVER_EMAIL") DEFAULT_FROM_EMAIL = import_secret("DEFAULT_FROM_EMAIL") EMAIL_HOST = import_secret("EMAIL_HOST") EMAIL_PORT = import_secret("EMAIL_PORT") EMAIL_HOST_USER = import_secret("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = import_secret("EMAIL_HOST_PASSWORD") EMAIL_USE_SSL = True # FIXME - set to False in production DEBUG = True # FIXME - set hosts in production ALLOWED_HOSTS = [] if DEBUG: # This will display emails in Console. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' else: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' SECURE_SSL_REDIRECT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_PRELOAD = True SECURE_REFERRER_POLICY = "same-origin" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'home.apps.HomeConfig', 'admin_pages.apps.AdminPagesConfig', 'accounts.apps.AccountsConfig', 'site_settings.apps.SiteSettingsConfig', 'shared.apps.SharedConfig', 'cas_server', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'interludes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'interludes', 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'site_settings.context_processors.settings' ], }, }, ] WSGI_APPLICATION = 'interludes.wsgi.application' # Auto primary key type DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, DB_NAME), } } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_USER_MODEL = 'accounts.EmailUser' AUTH_PROFILE_MODULE = 'home.ParticipantModel' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Session time in seconds SESSION_COOKIE_AGE = 3600 # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'fr-fr' TIME_ZONE = 'CET' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') LOGIN_URL = 'accounts:login' LOGIN_REDIRECT_URL = 'profile' # Prefix to mails to admins EMAIL_SUBJECT_PREFIX = '[DJANGO WEBLUDES] ' # Signature to mails to admins EMAIL_SIGNATURE = '-- Site Interludes (mail généré automatiquement)' # Prefix to mails to users USER_EMAIL_SUBJECT_PREFIX = "[interludes] " # CAS SERVER CAS_AUTH_CLASS = "interludes.cas_model.InterLudesAuthUser"
from computable.contracts.deployed import Deployed class Voting(Deployed): def at(self, w3, address): super().at(w3, address, 'voting') def set_privileged(self, parameterizer, datatrust, listing, opts=None): """ @param parameterizer Address @param reserve Address @param datatrust Address @param listing Address """ opts = self.assign_transact_opts({'gas': self.get_gas('setPrivileged')}, opts) return self.deployed.functions.setPrivileged(parameterizer, datatrust, listing), opts def get_privileged(self, opts=None): opts = self.assign_transact_opts({'gas': self.get_gas('getPrivileged')}, opts) return self.deployed.functions.getPrivileged(), opts def has_privilege(self, addr, opts=None): opts = self.assign_transact_opts({'gas': self.get_gas('hasPrivilege')}, opts) return self.deployed.functions.hasPrivilege(addr), opts def candidate_is(self, hash, kind, opts=None): """ @param hash The keccak256 identifier for this candidate @param opts Optional callOpts for this view/constant type call """ opts = self.assign_transact_opts({'gas': self.get_gas('candidateIs')}, opts) return self.deployed.functions.candidateIs(hash, kind), opts def is_candidate(self, hash, opts=None): opts = self.assign_transact_opts({'gas': self.get_gas('isCandidate')}, opts) return self.deployed.functions.isCandidate(hash), opts def get_candidate(self, hash, opts=None): """ @return (kind, owner, stake, vote_by, yea, nay) """ opts = self.assign_transact_opts({'gas': self.get_gas('getCandidate')}, opts) return self.deployed.functions.getCandidate(hash), opts def get_candidate_owner(self, hash, opts=None): opts = self.assign_transact_opts({'gas': self.get_gas('getCandidateOwner')}, opts) return self.deployed.functions.getCandidateOwner(hash), opts def did_pass(self, hash, plurality, opts=None): opts = self.assign_transact_opts({'gas': self.get_gas('didPass')}, opts) return self.deployed.functions.didPass(hash, plurality), opts def poll_closed(self, hash, opts=None): opts = self.assign_transact_opts({'gas': self.get_gas('pollClosed')}, opts) return self.deployed.functions.pollClosed(hash), opts def vote(self, hash, option, opts=None): """ @param option Either the integer `1` for a "yea" vote or any other value which is translated as a "nay" """ opts = self.assign_transact_opts({'gas': self.get_gas('vote')}, opts) return self.deployed.functions.vote(hash, option), opts def get_stake(self, hash, addr, opts=None): """ @param addr Address that a possible staked amount, in Market Token, belongs to @return Staked amount in wei """ opts = self.assign_transact_opts({'gas': self.get_gas('getStake')}, opts) return self.deployed.functions.getStake(hash, addr), opts def unstake(self, hash, opts=None): """ Claim any staked amounts that an address has rights to """ opts = self.assign_transact_opts({'gas': self.get_gas('unstake')}, opts) return self.deployed.functions.unstake(hash), opts
import django from WEBTSA.settings.base import * DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', data['host']] SITE_ROOT = os.environ['APPL_PHYSICAL_PATH'] SITE_URL = os.environ['APPL_VIRTUAL_PATH'] + "/" STATIC_ROOT = os.path.join(SITE_ROOT, 'static') STATIC_URL = SITE_URL + 'static/' django.setup()
from glob import glob from os.path import dirname, join, basename, isfile import sys from data_function import MedData_train from numpy.lib.utils import source sys.path.append('./') import csv import torch from medpy.io import load import numpy as np from PIL import Image from torch import nn import torch.nn.functional as F import random import torchio as tio from torchio import AFFINE, DATA import torchio from torchio import ScalarImage, LabelMap, Subject, SubjectsDataset, Queue from torchio.data import UniformSampler from torchio.transforms import ( RandomFlip, RandomAffine, RandomElasticDeformation, RandomNoise, RandomMotion, RandomBiasField, RescaleIntensity, Resample, ToCanonical, ZNormalization, CropOrPad, HistogramStandardization, OneOf, Compose, ) from pathlib import Path from hparam import hparams as hp images_dir = 'source_dataset' images_dir = Path(images_dir) image_paths = sorted(images_dir.glob(hp.fold_arch)) # print(image_paths) # print('-----------------------') label_dir = 'label_dataset' label_dir = Path(label_dir) label_paths = sorted(label_dir.glob(hp.fold_arch)) # print(label_paths) #测试tio链接dataset和label: # subjects = [] # for (image_path, label_path) in zip(image_paths, label_paths): # subject = tio.Subject( # source=tio.ScalarImage(image_path), # label=tio.LabelMap(label_path), # ) # # print('source: ',tio.ScalarImage(image_path),type(tio.ScalarImage(image_path))) # # print('label: ',tio.LabelMap(label_path),type(tio.LabelMap(label_path))) # # print('subject: ',subject,type(subject)) # subjects.append(subject) # print(subjects) # images_dir = 'img' # images_dir = Path(images_dir) # image_paths = sorted(images_dir.glob(hp.fold_arch)) # print(image_paths) # print('-----------------------') # images_dir = 'label' # images_dir = Path(images_dir) # image_paths = sorted(images_dir.glob(hp.fold_arch)) # print(image_paths) # print('-----------------------') train_dataset = MedData_train(images_dir,label_dir) # print("train_dataset: ",type(train_dataset),train_dataset) print(train_dataset.queue_dataset)
from magicdb import db, ASCENDING, DESCENDING class Query: def __init__(self, cls): self.cls = cls self.collection_path = self.cls.get_collection_name() self.firebase_query = None self.create_query() def create_query(self): self.firebase_query = db.conn.collection(self.collection_path) def add_parent(self, parent_key): if not parent_key: return self.collection_path = parent_key + '/' + self.collection_path self.create_query() def parent(self, parent_key): self.add_parent(parent_key) return self def document(self, doc_path): self.firebase_query = self.firebase_query.document(doc_path) return self def collection_group(self): self.firebase_query = db.conn.collection_group(self.cls.get_collection_name()) return self def collection(self, collection_path): self.firebase_query = self.firebase_query.collection(collection_path) return self def where(self, field, action, value): self.firebase_query = self.firebase_query.where(field, action, value) return self def order_by(self, field, direction=None, **kwargs): if direction: kwargs['direction'] = direction if kwargs.get('direction', None) == 'asc': kwargs['direction'] = ASCENDING if kwargs.get('direction', None) == 'desc': kwargs['direction'] = DESCENDING self.firebase_query = self.firebase_query.order_by(field, **kwargs) return self def start_at(self, fields): self.firebase_query = self.firebase_query.start_at(fields) return self def start_after(self, fields): self.firebase_query = self.firebase_query.start_after(fields) return self def end_at(self, fields): self.firebase_query = self.firebase_query.end_at(fields) return self def end_before(self, fields): self.firebase_query = self.firebase_query.end_before(fields) return self def limit(self, limit): self.firebase_query = self.firebase_query.limit(limit) return self def stream(self, **kwargs): docs = list(self.firebase_query.stream(**kwargs)) return [self.cls(from_db=True, key=self.key_from_ref(doc.reference), **doc.to_dict()) for doc in docs] def get(self, id=None, create=False, **kwargs): paths = id.split('/') if len(paths) == 2: id = paths[-1] doc = self.firebase_query.get(**kwargs) if not id else self.firebase_query.document(id).get(**kwargs) if 'DocumentSnapshot' not in (str(type(doc))): return None d = doc.to_dict() if not d: return None if not create else self.cls(id=id) return self.cls(from_db=True, key=self.key_from_ref(doc.reference), **doc.to_dict()) def get_all(self, ids, **kwargs): doc_refs = [db.conn.collection(self.collection_path).document(id) for id in ids] docs = db.conn.get_all(doc_refs, **kwargs) return [self.cls(from_db=True, key=self.key_from_ref(doc.reference), **doc.to_dict()) for doc in docs] @staticmethod def key_from_ref(ref): return '/'.join(ref._path) def collections(self): return self.firebase_query.collections() def collections_names(self): return [coll.id for coll in self.firebase_query.collections()] # TODO not sure what this does, seems to get all sub colls of every class... OH, prob for old validation... def get_subcollections(self, id=None): # if this is not a doc ref then return if id: self.firebase_query = self.firebase_query.document(id) if 'DocumentReference' not in str(type(self.firebase_query)): raise Exception( f'You cannot get subcollections of a CollectionRefernce. This query is type: {type(self.firebase_query)}') collection_names_d = {cls.get_collection_name(): cls for cls in self.cls.get_all_subclasses_of_model()} queries = [] for collection in self.firebase_query.collections(): collection_name = collection._path[-1] if collection_name in collection_names_d: q = Query(collection_names_d[collection_name]) q.parent(Query.key_from_ref(self.firebase_query)) queries.append(q) return queries def __repr__(self): return f'<*Query* cls: {self.cls.__name__}>'
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from __nonexistent import foo # should raise ModuleNotFoundError def main(req): foo()
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test EuropeanCallPricingObjective""" import unittest from test import QiskitFinanceTestCase import numpy as np from qiskit.utils import algorithm_globals, QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction, TwoLocal from qiskit.quantum_info import Operator from qiskit_finance.circuit.library import EuropeanCallPricingObjective, NormalDistribution class TestEuropeanCallExpectedValue(QiskitFinanceTestCase): """Tests EuropeanCallPricingObjective.""" def setUp(self): super().setUp() self.seed = 457 algorithm_globals.random_seed = self.seed def test_ecev_circuit(self): """Test the expected circuit. If it equals the correct ``LinearAmplitudeFunction`` we know the circuit is correct. """ num_qubits = 3 rescaling_factor = 0.1 strike_price = 0.5 bounds = (0, 2) ecev = EuropeanCallPricingObjective(num_qubits, strike_price, rescaling_factor, bounds) breakpoints = [0, strike_price] slopes = [0, 1] offsets = [0, 0] image = (0, 2 - strike_price) domain = (0, 2) linear_function = LinearAmplitudeFunction( num_qubits, slopes, offsets, domain=domain, image=image, breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) self.assertTrue(Operator(ecev).equiv(linear_function)) def test_application(self): """Test an end-to-end application.""" try: from qiskit import ( Aer, ) # pylint: disable=unused-import,import-outside-toplevel except ImportError as ex: # pylint: disable=broad-except self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex))) return bounds = np.array([0.0, 7.0]) num_qubits = 3 # the distribution circuit is a normal distribution plus a QGAN-trained ansatz circuit dist = NormalDistribution(num_qubits, mu=1, sigma=1, bounds=bounds) ansatz = TwoLocal(num_qubits, "ry", "cz", reps=1, entanglement="circular") trained_params = [ 0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225, ] ansatz.assign_parameters(trained_params, inplace=True) dist.compose(ansatz, inplace=True) # create the European call expected value strike_price = 2 rescaling_factor = 0.25 european_call = EuropeanCallPricingObjective( num_state_qubits=num_qubits, strike_price=strike_price, rescaling_factor=rescaling_factor, bounds=bounds, ) # create the state preparation circuit state_preparation = european_call.compose(dist, front=True) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[num_qubits], post_processing=european_call.post_processing, ) q_i = QuantumInstance( Aer.get_backend("aer_simulator"), seed_simulator=125, seed_transpiler=80 ) iae = IterativeAmplitudeEstimation(epsilon_target=0.01, alpha=0.05, quantum_instance=q_i) result = iae.estimate(problem) self.assertAlmostEqual(result.estimation_processed, 1.0127253837345427) if __name__ == "__main__": unittest.main()
import base64 import hashlib import hmac import models.coinbase from models.create_db import db import requests from requests.auth import HTTPBasicAuth from requests.auth import AuthBase import os import time # API vars api_key = os.environ.get('ETHERSCAN_API_KEY') endpoint_base = 'https://api.etherscan.io/api' headers = {'Content-Type': 'application/json'} # API CALLS def get(call): r = requests.get(call, auth=HTTPBasicAuth('', api_key), headers=headers) if check_err(r): return None return r.json() def check_err(r): if r.status_code != 200: print(r.text) return True else: return False ''' Get all coinbase prices ''' def get_coinbase_prices(): coinbase_instance = db.session.query(models.coinbase.CoinbaseETH).order_by(models.coinbase.CoinbaseETH.timestamp.desc()).limit(2)[-2:] coinbase_price = 0 coinbase_timestamp = 0 coinbase_last_price = 0 if len(coinbase_instance) > 1: coinbase_last_price = coinbase_instance[1].price coinbase_price = coinbase_instance[0].price coinbase_timestamp = coinbase_instance[0].timestamp coinbase_btc_instance = db.session.query(models.coinbase.CoinbaseBTC).order_by(models.coinbase.CoinbaseBTC.timestamp.desc()).limit(2)[-2:] coinbase_btc_price = 0 coinbase_btc_timestamp = 0 coinbase_btc_last_price = 0 if len(coinbase_btc_instance) > 1: coinbase_btc_last_price = coinbase_btc_instance[1].price coinbase_btc_price = coinbase_btc_instance[0].price coinbase_btc_timestamp = coinbase_btc_instance[0].timestamp return coinbase_price, coinbase_timestamp, coinbase_last_price, coinbase_btc_price, coinbase_btc_timestamp, coinbase_btc_last_price ''' Move to separate file ''' class CoinbaseExchangeAuth(AuthBase): def __init__(self, api_key, secret_key, passphrase): self.api_key = api_key self.secret_key = secret_key self.passphrase = passphrase def __call__(self, request): timestamp = str(time.time()) message = timestamp + request.method + request.path_url + (request.body or b'').decode() hmac_key = base64.b64decode(self.secret_key) signature = hmac.new(hmac_key, message.encode(), hashlib.sha256) signature_b64 = base64.b64encode(signature.digest()).decode() request.headers.update({ 'CB-ACCESS-SIGN': signature_b64, 'CB-ACCESS-TIMESTAMP': timestamp, 'CB-ACCESS-KEY': self.api_key, 'CB-ACCESS-PASSPHRASE': self.passphrase, 'Content-Type': 'application/json' }) return request ''' Get Coinbase current ETH Price ''' def get_coinbase_price(): api_url = 'https://api.pro.coinbase.com/' auth = CoinbaseExchangeAuth(os.environ.get('COINBASE_API_KEY'), os.environ.get('COINBASE_SECRET_KEY'), os.environ.get('COINBASE_PRIVATE_KEY')) r = requests.get(api_url + 'oracle', auth=auth).json() eth_price = r['prices']['ETH'] timestamp = r['timestamp'] f = open("coinbase.txt", "r") last_price = f.readline() f.close() if eth_price != float(last_price): os.remove('coinbase.txt') coinbase = models.coinbase.CoinbaseETH(timestamp=timestamp, price=eth_price) db.session.add(coinbase) db.session.commit() # Write new file print(eth_price) f = open("coinbase.txt", 'w') f.write('{}'.format(eth_price)) f.close() return eth_price, timestamp ''' Get Coinbase current BTC Price ''' def get_coinbase_btc_price(): api_url = 'https://api.pro.coinbase.com/' auth = CoinbaseExchangeAuth(os.environ.get('COINBASE_API_KEY'), os.environ.get('COINBASE_SECRET_KEY'), os.environ.get('COINBASE_PRIVATE_KEY')) r = requests.get(api_url + 'oracle', auth=auth).json() btc_price = r['prices']['BTC'] timestamp = r['timestamp'] f = open("coinbase_btc.txt", "r") last_price = f.readline() f.close() if btc_price != float(last_price): os.remove('coinbase_btc.txt') coinbase = models.coinbase.CoinbaseBTC(timestamp=timestamp, price=btc_price) db.session.add(coinbase) db.session.commit() print(btc_price) # Write new file f = open("coinbase_btc.txt", 'w') f.write('{}'.format(btc_price)) f.close() return btc_price, timestamp ''' Create all chainlink latest price files ''' def create_coinbase_files(): f = open('coinbae.txt', "w") f.write('1') f.close() f = open('coinbase_btc.txt', "w") f.write('1') f.close()
from defines_tcpip import offsets d = open("defines_tcpip.fs", "w") for nm,o in sorted(offsets.items()): print >>d, "%d constant %s" % (o, nm) import defines_tcpip2 d = open("defines_tcpip2.fs", "w") for nm,o in sorted(defines_tcpip2.offsets.items()): print >>d, "%d constant %s" % (o, nm)
from app import ma class HistoryAbsenPegawaiAll(ma.Schema): class Meta: fields = ( 'idUser', 'namaLengkap', 'tglAbsensi', 'jamMasuk', 'jamKeluar', 'namaStatus' ) class HistoryAbsenPegawai(ma.Schema): class Meta: fields = ( 'tglAbsensi', 'jamMasuk', 'jamKeluar', 'namaStatus' ) history_absensi_all_schema = HistoryAbsenPegawaiAll(many=True) history_absensi_schema = HistoryAbsenPegawai(many=True)
from typing import List, NoReturn def shell_sort(in_list: List[int], ini_step) -> NoReturn: length = len(in_list) step = ini_step while step > 1: for i in range(1, length): for j in range(i, 0, -int(step)): if in_list[j] < in_list[j-1]: in_list[j], in_list[j-1] = in_list[j-1], in_list[j] else: break step /= 2 if __name__ == "__main__": in_list = [15,12,73,23,89,2,87,94,54,3,162,12,33] shell_sort(in_list, len(in_list)-2) assert in_list == [2, 3, 12, 12, 15, 23, 33, 54, 73, 87, 89, 94, 162] print("Test succeeded.")
import numpy as np from pandas.api.types import is_list_like import ipaddress from . import AddrArray def to_ipaddress(values): """Convert values to AddrArray Parameters ---------- values : int, str, bytes, or sequence of those Returns ------- addresses : IPArray Examples -------- Parse strings >>> to_ipaddress(['192.168.1.1', ... '2001:0db8:85a3:0000:0000:8a2e:0370:7334']) <IPArray(['192.168.1.1', '0:8a2e:370:7334:2001:db8:85a3:0'])> Or integers >>> to_ipaddress([3232235777, 42540766452641154071740215577757643572]) <IPArray(['192.168.1.1', '0:8a2e:370:7334:2001:db8:85a3:0'])> Or packed binary representations >>> to_ipaddress([b'\xc0\xa8\x01\x01', b' \x01\r\xb8\x85\xa3\x00\x00\x00\x00\x8a.\x03ps4']) <IPArray(['192.168.1.1', '0:8a2e:370:7334:2001:db8:85a3:0'])> """ if not is_list_like(values): values = [values] return AddrArray(values)
import configparser import os from pathlib import Path config_path = "conf/config.ini" default_local_config_path = os.path.join(str(Path.home()), "tracker_config.ini") CONFIG = configparser.ConfigParser(allow_no_value=True) CONFIG.read([config_path, default_local_config_path])
import colander class ClientSchema(colander.MappingSchema): name = colander.SchemaNode(colander.String()) description = colander.SchemaNode(colander.String()) default_scope = colander.SchemaNode(colander.String(), missing='') redirect_uris = colander.SchemaNode(colander.Sequence(colander.String), missing=['http://localhost:8000'])
from py4j.java_gateway import JavaObject, is_instance_of from pyspark.sql.types import DataType, StructType from .jvm import JvmPackage _jvm_spark_sql_types = JvmPackage("org.apache.spark.sql.types") class DataTypes: @staticmethod def to_jvm(data_type: DataType) -> JavaObject: return _jvm_spark_sql_types.DataType.fromJson(data_type.json()) @staticmethod def from_jvm(jvm_data_type: JavaObject) -> DataType: if is_instance_of(jvm_data_type, "org.apache.spark.sql.types.StructType"): return StructType.fromJson(jvm_data_type.json()) else: empty_metadata = _jvm_spark_sql_types.Metadata.empty() jvm_struct_field = _jvm_spark_sql_types.StructField("dummy", jvm_data_type, True, empty_metadata) jvm_struct_type = _jvm_spark_sql_types.StructType([jvm_struct_field]) struct_type = StructType.fromJson(jvm_struct_type.json()) return struct_type.fields[0].dataType
from datetime import datetime from os import path import pytz from core_data_modules.traced_data import Metadata from core_data_modules.traced_data.io import TracedDataCodaV2IO from core_data_modules.util import TimeUtils from dateutil.parser import isoparse from project_redss.lib.redss_schemes import CodeSchemes class TranslateRapidProKeys(object): # TODO: Move the constants in this file to configuration json RAPID_PRO_KEY_MAP = [ # List of (new_key, old_key) ("uid", "avf_phone_id"), ("rqa_s01e01_run_id", "Rqa_S01E01 (Run ID) - csap_s01e01_activation"), ("rqa_s01e02_run_id", "Rqa_S01E02 (Run ID) - csap_s01e02_activation"), ("rqa_s01e03_run_id", "Rqa_S01E03 (Run ID) - csap_s01e03_activation"), ("rqa_s01e04_run_id", "Rqa_S01E04 (Run ID) - csap_s01e04_activation"), ("sent_on", "Rqa_S01E01 (Time) - csap_s01e01_activation"), ("sent_on", "Rqa_S01E02 (Time) - csap_s01e02_activation"), ("sent_on", "Rqa_S01E03 (Time) - csap_s01e03_activation"), ("sent_on", "Rqa_S01E04 (Time) - csap_s01e04_activation"), ("gender_raw", "Gender (Value) - csap_demog"), ("gender_time", "Gender (Time) - csap_demog"), ("mogadishu_sub_district_raw", "Mog_Sub_District (Value) - csap_demog"), ("mogadishu_sub_district_time", "Mog_Sub_District (Time) - csap_demog"), ("age_raw", "Age (Value) - csap_demog"), ("age_time", "Age (Time) - csap_demog"), ("idp_camp_raw", "Idp_Camp (Value) - csap_demog"), ("idp_camp_time", "Idp_Camp (Time) - csap_demog"), ("recently_displaced_raw", "Recently_Displaced (Value) - csap_demog"), ("recently_displaced_time", "Recently_Displaced (Time) - csap_demog"), ("hh_language_raw", "Hh_Language (Value) - csap_demog"), ("hh_language_time", "Hh_Language (Time) - csap_demog"), ("repeated_raw", "Repeated (Value) - csap_evaluation"), ("repeated_time", "Repeated (Time) - csap_evaluation"), ("involved_raw", "Involved (Value) - csap_evaluation"), ("involved_time", "Involved (Time) - csap_evaluation") ] SHOW_ID_MAP = { "Rqa_S01E01 (Value) - csap_s01e01_activation": 1, "Rqa_S01E02 (Value) - csap_s01e02_activation": 2, "Rqa_S01E03 (Value) - csap_s01e03_activation": 3, "Rqa_S01E04 (Value) - csap_s01e04_activation": 4 } RAW_ID_MAP = { 1: "rqa_s01e01_raw", 2: "rqa_s01e02_raw", 3: "rqa_s01e03_raw", 4: "rqa_s01e04_raw" } WEEK_3_TIME_KEY = "Rqa_S01E03 (Time) - csap_s01e03_activation" WEEK_3_VALUE_KEY = "Rqa_S01E03 (Value) - csap_s01e03_activation" WEEK_4_START = "2018-12-23T00:00:00+03:00" WEEK_4_TIME_KEY = "Rqa_S01E04 (Time) - csap_s01e04_activation" WEEK_4_VALUE_KEY = "Rqa_S01E04 (Value) - csap_s01e04_activation" THURSDAY_BURST_START = "2019-01-17T12:03:11+03:00" THURSDAY_BURST_END = "2019-01-17T12:24:42+03:00" THURSDAY_CORRECTION_TIME = "2018-12-13T00:00:00+03:00" FRIDAY_BURST_START = "2019-01-12T09:45:12+03:00" FRIDAY_BURST_END = "2019-01-12T09:51:57+03:00" FRIDAY_CORRECTION_TIME = "2018-12-14T00:00:00+03:00" @classmethod def _build_message_to_s01e02_dict(cls, user, data, coda_input_dir): # Duplicate the input list because reading the file requires appending data to the TracedData, # and we don't actually want to modify the input at this stage of the pipeline. data = [td.copy() for td in data] # Apply the week 3 codes from Coda. message_id_key = "radio_show_3_message_id" coded_ws_key = "radio_show_3_ws" TracedDataCodaV2IO.compute_message_ids(user, data, cls.WEEK_3_VALUE_KEY, message_id_key) coda_input_path = path.join(coda_input_dir, "s01e03.json") with open(coda_input_path) as f: TracedDataCodaV2IO.import_coda_2_to_traced_data_iterable( user, data, message_id_key, {coded_ws_key: CodeSchemes.WS_CORRECT_DATASET}, f) # Parse the loaded codes into a look-up table of raw message string -> is ws boolean. message_to_ws_dict = dict() for td in data: label = td.get(coded_ws_key) if label is not None: message_to_ws_dict[td.get(cls.WEEK_3_VALUE_KEY)] = \ label["CodeID"] == CodeSchemes.WS_CORRECT_DATASET.get_code_with_match_value("s01e02").code_id return message_to_ws_dict @classmethod def set_show_ids(cls, user, data, show_id_map): """ Sets a show_id for each message, using the presence of Rapid Pro value keys to determine which show each message belongs to. :param user: Identifier of the user running this program, for TracedData Metadata. :type user: str :param data: TracedData objects to set the show ids of. :type data: iterable of TracedData :param show_id_map: Dictionary of Rapid Pro value key to show id. :type show_id_map: dict of str -> int """ for td in data: show_dict = dict() for message_key, show_id in show_id_map.items(): if message_key in td: assert "rqa_message" not in show_dict show_dict["rqa_message"] = td[message_key] show_dict["show_id"] = show_id td.append_data(show_dict, Metadata(user, Metadata.get_call_location(), TimeUtils.utc_now_as_iso_string())) @classmethod def _remap_radio_show_by_time_range(cls, user, data, time_key, show_id_to_remap_to, range_start=None, range_end=None, time_to_adjust_to=None): """ Remaps radio show messages received in the given time range to another radio show. Optionally adjusts the datetime of re-mapped messages to a constant. :param user: Identifier of the user running this program, for TracedData Metadata. :type user: str :param data: TracedData objects to set the show ids of. :type data: iterable of TracedData :param time_key: Key in each TracedData of an ISO 8601-formatted datetime string to read the message sent on time from. :type time_key: str :param show_id_to_remap_to: Show id to assign to messages received within the given time range. :type show_id_to_remap_to: int :param range_start: Start datetime for the time range to remap radio show messages from, inclusive. If None, defaults to the beginning of time. :type range_start: datetime | None :param range_end: End datetime for the time range to remap radio show messages from, exclusive. If None, defaults to the end of time. :type range_end: datetime | None :param time_to_adjust_to: Datetime to assign to the 'sent_on' field of re-mapped shows. If None, re-mapped shows will not have timestamps re-adjusted. :type time_to_adjust_to: datetime | None """ if range_start is None: range_start = pytz.utc.localize(datetime.min) if range_end is None: range_end = pytz.utc.localize(datetime.max) for td in data: if time_key in td and range_start <= isoparse(td[time_key]) < range_end: remapped = { "show_id": show_id_to_remap_to } if time_to_adjust_to is not None: remapped[time_key] = time_to_adjust_to.isoformat() td.append_data(remapped, Metadata(user, Metadata.get_call_location(), TimeUtils.utc_now_as_iso_string())) @classmethod def remap_radio_shows(cls, user, data, coda_input_dir): """ Remaps radio shows which were in the wrong flow, and therefore have the wrong key/values set, to have the key/values they would have had if they had been received by the correct flow. :param user: Identifier of the user running this program, for TracedData Metadata. :type user: str :param data: TracedData objects to move the radio show messages in. :type data: iterable of TracedData :param coda_input_dir: Directory to read coded coda files from. :type coda_input_dir: str """ # TODO: Convert the show remapping code here into reusable functions for each case that they handle. # Note that ultimately we probably don't want to handle the 'WS' show remapping here, # because we get that for free when we implement 'WS' handling properly. # Build a map of raw week 3 messages to wrong scheme data message_to_s01e02_dict = cls._build_message_to_s01e02_dict(user, data, coda_input_dir) for td in data: mapped_dict = dict() if cls.WEEK_3_TIME_KEY in td: # Redirect any week 3 messages coded as s01e02 in the WS - Correct Dataset scheme to week 2 # Also, fake the timestamp of redirected week 3 messages to make it look like they arrived on the day # before the incorrect sms ad was sent, i.e. the last day of week 2. # This is super yucky, but works because (a) timestamps are never exported, and (b) this date # is being set to non_logical anyway in channels.py. if message_to_s01e02_dict.get(td["rqa_message"], False): mapped_dict["show_id"] = 2 mapped_dict["sent_on"] = "2018-12-15T00:00:00+03:00" td.append_data(mapped_dict, Metadata(user, Metadata.get_call_location(), TimeUtils.utc_now_as_iso_string())) # Redirect any week 4 messages which were in the week 3 flow due to a late flow change-over. cls._remap_radio_show_by_time_range(user, data, cls.WEEK_3_TIME_KEY, 4, range_start=isoparse(cls.WEEK_4_START)) # Redirect any week 2 messages which were in the week 4 flow, due to undelivered messages being delivered # in two bursts after the end of the radio shows. cls._remap_radio_show_by_time_range(user, data, cls.WEEK_4_TIME_KEY, 2, range_start=isoparse(cls.THURSDAY_BURST_START), range_end=isoparse(cls.THURSDAY_BURST_END), time_to_adjust_to=isoparse(cls.THURSDAY_CORRECTION_TIME)) cls._remap_radio_show_by_time_range(user, data, cls.WEEK_4_TIME_KEY, 2, range_start=isoparse(cls.FRIDAY_BURST_START), range_end=isoparse(cls.FRIDAY_BURST_END), time_to_adjust_to=isoparse(cls.FRIDAY_CORRECTION_TIME)) @classmethod def remap_key_names(cls, user, data, key_map): """ Remaps key names. :param user: Identifier of the user running this program, for TracedData Metadata. :type user: str :param data: TracedData objects to remap the key names of. :type data: iterable of TracedData :param key_map: Iterable of (new_key, old_key). :type key_map: iterable of (str, str) """ for td in data: remapped = dict() for new_key, old_key in key_map: if old_key in td and new_key not in td: remapped[new_key] = td[old_key] td.append_data(remapped, Metadata(user, Metadata.get_call_location(), TimeUtils.utc_now_as_iso_string())) @classmethod def set_rqa_raw_keys_from_show_ids(cls, user, data, raw_id_map): """ Despite the earlier phases of this pipeline stage using a common 'rqa_message' field and then a 'show_id' field to identify which radio show a message belonged to, the rest of the pipeline still uses the presence of a raw field for each show to determine which show a message belongs to. This function translates from the new 'show_id' method back to the old 'raw field presence` method. TODO: Update the rest of the pipeline to use show_ids, and/or perform remapping before combining the datasets. :param user: Identifier of the user running this program, for TracedData Metadata. :type user: str :param data: TracedData objects to set raw radio show message fields for. :type data: iterable of TracedData :param raw_id_map: Dictionary of show id to the rqa message key to assign each td[rqa_message} to. :type raw_id_map: dict of int -> str """ for td in data: for show_id, message_key in raw_id_map.items(): if "rqa_message" in td and td.get("show_id") == show_id: td.append_data({message_key: td["rqa_message"]}, Metadata(user, Metadata.get_call_location(), TimeUtils.utc_now_as_iso_string())) @classmethod def translate_rapid_pro_keys(cls, user, data, coda_input_dir): """ Remaps the keys of rqa messages in the wrong flow into the correct one, and remaps all Rapid Pro keys to more usable keys that can be used by the rest of the pipeline. TODO: Break this function such that the show remapping phase happens in one class, and the Rapid Pro remapping in another? """ # Set a show id field for each message, using the presence of Rapid Pro value keys in the TracedData. # Show ids are necessary in order to be able to remap radio shows and key names separately (because data # can't be 'deleted' from TracedData). cls.set_show_ids(user, data, cls.SHOW_ID_MAP) # Move rqa messages which ended up in the wrong flow to the correct one. cls.remap_radio_shows(user, data, coda_input_dir) # Remap the keys used by Rapid Pro to more usable key names that will be used by the rest of the pipeline. cls.remap_key_names(user, data, cls.RAPID_PRO_KEY_MAP) # Convert from the new show id format to the raw field format still used by the rest of the pipeline. cls.set_rqa_raw_keys_from_show_ids(user, data, cls.RAW_ID_MAP) return data
# Creative Commons Legal Code # # CC0 1.0 Universal # # CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE # LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN # ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS # INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES # REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS # PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM # THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED # HEREUNDER. # # Statement of Purpose # # The laws of most jurisdictions throughout the world automatically confer # exclusive Copyright and Related Rights (defined below) upon the creator # and subsequent owner(s) (each and all, an "owner") of an original work of # authorship and/or a database (each, a "Work"). # # Certain owners wish to permanently relinquish those rights to a Work for # the purpose of contributing to a commons of creative, cultural and # scientific works ("Commons") that the public can reliably and without fear # of later claims of infringement build upon, modify, incorporate in other # works, reuse and redistribute as freely as possible in any form whatsoever # and for any purposes, including without limitation commercial purposes. # These owners may contribute to the Commons to promote the ideal of a free # culture and the further production of creative, cultural and scientific # works, or to gain reputation or greater distribution for their Work in # part through the use and efforts of others. # # For these and/or other purposes and motivations, and without any # expectation of additional consideration or compensation, the person # associating CC0 with a Work (the "Affirmer"), to the extent that he or she # is an owner of Copyright and Related Rights in the Work, voluntarily # elects to apply CC0 to the Work and publicly distribute the Work under its # terms, with knowledge of his or her Copyright and Related Rights in the # Work and the meaning and intended legal effect of CC0 on those rights. # # 1. Copyright and Related Rights. A Work made available under CC0 may be # protected by copyright and related or neighboring rights ("Copyright and # Related Rights"). Copyright and Related Rights include, but are not # limited to, the following: # # i. the right to reproduce, adapt, distribute, perform, display, # communicate, and translate a Work; # ii. moral rights retained by the original author(s) and/or performer(s); # iii. publicity and privacy rights pertaining to a person's image or # likeness depicted in a Work; # iv. rights protecting against unfair competition in regards to a Work, # subject to the limitations in paragraph 4(a), below; # v. rights protecting the extraction, dissemination, use and reuse of data # in a Work; # vi. database rights (such as those arising under Directive 96/9/EC of the # European Parliament and of the Council of 11 March 1996 on the legal # protection of databases, and under any national implementation # thereof, including any amended or successor version of such # directive); and # vii. other similar, equivalent or corresponding rights throughout the # world based on applicable law or treaty, and any national # implementations thereof. # # 2. Waiver. To the greatest extent permitted by, but not in contravention # of, applicable law, Affirmer hereby overtly, fully, permanently, # irrevocably and unconditionally waives, abandons, and surrenders all of # Affirmer's Copyright and Related Rights and associated claims and causes # of action, whether now known or unknown (including existing as well as # future claims and causes of action), in the Work (i) in all territories # worldwide, (ii) for the maximum duration provided by applicable law or # treaty (including future time extensions), (iii) in any current or future # medium and for any number of copies, and (iv) for any purpose whatsoever, # including without limitation commercial, advertising or promotional # purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each # member of the public at large and to the detriment of Affirmer's heirs and # successors, fully intending that such Waiver shall not be subject to # revocation, rescission, cancellation, termination, or any other legal or # equitable action to disrupt the quiet enjoyment of the Work by the public # as contemplated by Affirmer's express Statement of Purpose. # # 3. Public License Fallback. Should any part of the Waiver for any reason # be judged legally invalid or ineffective under applicable law, then the # Waiver shall be preserved to the maximum extent permitted taking into # account Affirmer's express Statement of Purpose. In addition, to the # extent the Waiver is so judged Affirmer hereby grants to each affected # person a royalty-free, non transferable, non sublicensable, non exclusive, # irrevocable and unconditional license to exercise Affirmer's Copyright and # Related Rights in the Work (i) in all territories worldwide, (ii) for the # maximum duration provided by applicable law or treaty (including future # time extensions), (iii) in any current or future medium and for any number # of copies, and (iv) for any purpose whatsoever, including without # limitation commercial, advertising or promotional purposes (the # "License"). The License shall be deemed effective as of the date CC0 was # applied by Affirmer to the Work. Should any part of the License for any # reason be judged legally invalid or ineffective under applicable law, such # partial invalidity or ineffectiveness shall not invalidate the remainder # of the License, and in such case Affirmer hereby affirms that he or she # will not (i) exercise any of his or her remaining Copyright and Related # Rights in the Work or (ii) assert any associated claims and causes of # action with respect to the Work, in either case contrary to Affirmer's # express Statement of Purpose. # # 4. Limitations and Disclaimers. # # a. No trademark or patent rights held by Affirmer are waived, abandoned, # surrendered, licensed or otherwise affected by this document. # b. Affirmer offers the Work as-is and makes no representations or # warranties of any kind concerning the Work, express, implied, # statutory or otherwise, including without limitation warranties of # title, merchantability, fitness for a particular purpose, non # infringement, or the absence of latent or other defects, accuracy, or # the present or absence of errors, whether or not discoverable, all to # the greatest extent permissible under applicable law. # c. Affirmer disclaims responsibility for clearing rights of other persons # that may apply to the Work or any use thereof, including without # limitation any person's Copyright and Related Rights in the Work. # Further, Affirmer disclaims responsibility for obtaining any necessary # consents, permissions or other rights required for any use of the # Work. # d. Affirmer understands and acknowledges that Creative Commons is not a # party to this document and has no duty or obligation with respect to # this CC0 or use of the Work. # This file was compiled from a KSY format file downloaded from: # https://github.com/kaitai-io/kaitai_struct_formats # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version import kaitaistruct from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO import collections if parse_version(kaitaistruct.__version__) < parse_version('0.9'): raise Exception("Incompatible Kaitai Struct Python API: 0.9 or later is required, but you have %s" % (kaitaistruct.__version__)) class EfivarSignatureList(KaitaiStruct): """Parse UEFI variables db and dbx that contain signatures, certificates and hashes. On a Linux system using UEFI, these variables are readable from /sys/firmware/efi/efivars/db-d719b2cb-3d3a-4596-a3bc-dad00e67656f, /sys/firmware/efi/efivars/dbDefault-8be4df61-93ca-11d2-aa0d-00e098032b8c, /sys/firmware/efi/efivars/dbx-d719b2cb-3d3a-4596-a3bc-dad00e67656f and /sys/firmware/efi/efivars/dbxDefault-8be4df61-93ca-11d2-aa0d-00e098032b8c. ("d719b2cb-3d3a-4596-a3bc-dad00e67656f" is defined as EFI_IMAGE_SECURITY_DATABASE_GUID and "8be4df61-93ca-11d2-aa0d-00e098032b8c" as EFI_GLOBAL_VARIABLE). Each file contains an EFI attribute (32-bit integer) followed by a list of EFI_SIGNATURE_LIST structures. .. seealso:: Source - https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_final.pdf """ SEQ_FIELDS = ["var_attributes", "signatures"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['var_attributes']['start'] = self._io.pos() self.var_attributes = EfivarSignatureList.EfiVarAttr(self._io, self, self._root) self.var_attributes._read() self._debug['var_attributes']['end'] = self._io.pos() self._debug['signatures']['start'] = self._io.pos() self.signatures = [] i = 0 while not self._io.is_eof(): if not 'arr' in self._debug['signatures']: self._debug['signatures']['arr'] = [] self._debug['signatures']['arr'].append({'start': self._io.pos()}) _t_signatures = EfivarSignatureList.SignatureList(self._io, self, self._root) _t_signatures._read() self.signatures.append(_t_signatures) self._debug['signatures']['arr'][len(self.signatures) - 1]['end'] = self._io.pos() i += 1 self._debug['signatures']['end'] = self._io.pos() class SignatureList(KaitaiStruct): """ .. seealso:: EFI_SIGNATURE_LIST """ SEQ_FIELDS = ["signature_type", "len_signature_list", "len_signature_header", "len_signature", "header", "signatures"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['signature_type']['start'] = self._io.pos() self.signature_type = self._io.read_bytes(16) self._debug['signature_type']['end'] = self._io.pos() self._debug['len_signature_list']['start'] = self._io.pos() self.len_signature_list = self._io.read_u4le() self._debug['len_signature_list']['end'] = self._io.pos() self._debug['len_signature_header']['start'] = self._io.pos() self.len_signature_header = self._io.read_u4le() self._debug['len_signature_header']['end'] = self._io.pos() self._debug['len_signature']['start'] = self._io.pos() self.len_signature = self._io.read_u4le() self._debug['len_signature']['end'] = self._io.pos() self._debug['header']['start'] = self._io.pos() self.header = self._io.read_bytes(self.len_signature_header) self._debug['header']['end'] = self._io.pos() if self.len_signature > 0: self._debug['signatures']['start'] = self._io.pos() self._raw_signatures = [None] * (((self.len_signature_list - self.len_signature_header) - 28) // self.len_signature) self.signatures = [None] * (((self.len_signature_list - self.len_signature_header) - 28) // self.len_signature) for i in range(((self.len_signature_list - self.len_signature_header) - 28) // self.len_signature): if not 'arr' in self._debug['signatures']: self._debug['signatures']['arr'] = [] self._debug['signatures']['arr'].append({'start': self._io.pos()}) self._raw_signatures[i] = self._io.read_bytes(self.len_signature) _io__raw_signatures = KaitaiStream(BytesIO(self._raw_signatures[i])) _t_signatures = EfivarSignatureList.SignatureData(_io__raw_signatures, self, self._root) _t_signatures._read() self.signatures[i] = _t_signatures self._debug['signatures']['arr'][i]['end'] = self._io.pos() self._debug['signatures']['end'] = self._io.pos() @property def is_cert_sha512_x509(self): """SHA512 hash of an X.509 certificate's To-Be-Signed contents, and a time of revocation. .. seealso:: EFI_CERT_X509_SHA512_GUID """ if hasattr(self, '_m_is_cert_sha512_x509'): return self._m_is_cert_sha512_x509 if hasattr(self, '_m_is_cert_sha512_x509') else None self._m_is_cert_sha512_x509 = self.signature_type == b"\x63\xBF\x6D\x44\x02\x25\xDA\x4C\xBC\xFA\x24\x65\xD2\xB0\xFE\x9D" return self._m_is_cert_sha512_x509 if hasattr(self, '_m_is_cert_sha512_x509') else None @property def is_cert_sha224(self): """SHA-224 hash. .. seealso:: EFI_CERT_SHA224_GUID """ if hasattr(self, '_m_is_cert_sha224'): return self._m_is_cert_sha224 if hasattr(self, '_m_is_cert_sha224') else None self._m_is_cert_sha224 = self.signature_type == b"\x33\x52\x6E\x0B\x5C\xA6\xC9\x44\x94\x07\xD9\xAB\x83\xBF\xC8\xBD" return self._m_is_cert_sha224 if hasattr(self, '_m_is_cert_sha224') else None @property def is_cert_x509(self): """X.509 certificate. .. seealso:: EFI_CERT_X509_GUID """ if hasattr(self, '_m_is_cert_x509'): return self._m_is_cert_x509 if hasattr(self, '_m_is_cert_x509') else None self._m_is_cert_x509 = self.signature_type == b"\xA1\x59\xC0\xA5\xE4\x94\xA7\x4A\x87\xB5\xAB\x15\x5C\x2B\xF0\x72" return self._m_is_cert_x509 if hasattr(self, '_m_is_cert_x509') else None @property def is_cert_sha256_x509(self): """SHA256 hash of an X.509 certificate's To-Be-Signed contents, and a time of revocation. .. seealso:: EFI_CERT_X509_SHA256_GUID """ if hasattr(self, '_m_is_cert_sha256_x509'): return self._m_is_cert_sha256_x509 if hasattr(self, '_m_is_cert_sha256_x509') else None self._m_is_cert_sha256_x509 = self.signature_type == b"\x92\xA4\xD2\x3B\xC0\x96\x79\x40\xB4\x20\xFC\xF9\x8E\xF1\x03\xED" return self._m_is_cert_sha256_x509 if hasattr(self, '_m_is_cert_sha256_x509') else None @property def is_cert_rsa2048_key(self): """RSA-2048 key (only the modulus since the public key exponent is known to be 0x10001). .. seealso:: EFI_CERT_RSA2048_GUID """ if hasattr(self, '_m_is_cert_rsa2048_key'): return self._m_is_cert_rsa2048_key if hasattr(self, '_m_is_cert_rsa2048_key') else None self._m_is_cert_rsa2048_key = self.signature_type == b"\xE8\x66\x57\x3C\x9C\x26\x34\x4E\xAA\x14\xED\x77\x6E\x85\xB3\xB6" return self._m_is_cert_rsa2048_key if hasattr(self, '_m_is_cert_rsa2048_key') else None @property def is_cert_sha512(self): """SHA-512 hash. .. seealso:: EFI_CERT_SHA512_GUID """ if hasattr(self, '_m_is_cert_sha512'): return self._m_is_cert_sha512 if hasattr(self, '_m_is_cert_sha512') else None self._m_is_cert_sha512 = self.signature_type == b"\xAE\x0F\x3E\x09\xC4\xA6\x50\x4F\x9F\x1B\xD4\x1E\x2B\x89\xC1\x9A" return self._m_is_cert_sha512 if hasattr(self, '_m_is_cert_sha512') else None @property def is_cert_sha384(self): """SHA-384 hash. .. seealso:: EFI_CERT_SHA384_GUID """ if hasattr(self, '_m_is_cert_sha384'): return self._m_is_cert_sha384 if hasattr(self, '_m_is_cert_sha384') else None self._m_is_cert_sha384 = self.signature_type == b"\x07\x53\x3E\xFF\xD0\x9F\xC9\x48\x85\xF1\x8A\xD5\x6C\x70\x1E\x01" return self._m_is_cert_sha384 if hasattr(self, '_m_is_cert_sha384') else None @property def is_cert_sha1(self): """SHA-1 hash. .. seealso:: EFI_CERT_SHA1_GUID """ if hasattr(self, '_m_is_cert_sha1'): return self._m_is_cert_sha1 if hasattr(self, '_m_is_cert_sha1') else None self._m_is_cert_sha1 = self.signature_type == b"\x12\xA5\x6C\x82\x10\xCF\xC9\x4A\xB1\x87\xBE\x01\x49\x66\x31\xBD" return self._m_is_cert_sha1 if hasattr(self, '_m_is_cert_sha1') else None @property def is_cert_rsa2048_sha1(self): """RSA-2048 signature of a SHA-1 hash. .. seealso:: EFI_CERT_RSA2048_SHA1_GUID """ if hasattr(self, '_m_is_cert_rsa2048_sha1'): return self._m_is_cert_rsa2048_sha1 if hasattr(self, '_m_is_cert_rsa2048_sha1') else None self._m_is_cert_rsa2048_sha1 = self.signature_type == b"\x4F\x44\xF8\x67\x43\x87\xF1\x48\xA3\x28\x1E\xAA\xB8\x73\x60\x80" return self._m_is_cert_rsa2048_sha1 if hasattr(self, '_m_is_cert_rsa2048_sha1') else None @property def is_cert_sha256(self): """SHA-256 hash. .. seealso:: EFI_CERT_SHA256_GUID """ if hasattr(self, '_m_is_cert_sha256'): return self._m_is_cert_sha256 if hasattr(self, '_m_is_cert_sha256') else None self._m_is_cert_sha256 = self.signature_type == b"\x26\x16\xC4\xC1\x4C\x50\x92\x40\xAC\xA9\x41\xF9\x36\x93\x43\x28" return self._m_is_cert_sha256 if hasattr(self, '_m_is_cert_sha256') else None @property def is_cert_sha384_x509(self): """SHA384 hash of an X.509 certificate's To-Be-Signed contents, and a time of revocation. .. seealso:: EFI_CERT_X509_SHA384_GUID """ if hasattr(self, '_m_is_cert_sha384_x509'): return self._m_is_cert_sha384_x509 if hasattr(self, '_m_is_cert_sha384_x509') else None self._m_is_cert_sha384_x509 = self.signature_type == b"\x6E\x87\x76\x70\xC2\x80\xE6\x4E\xAA\xD2\x28\xB3\x49\xA6\x86\x5B" return self._m_is_cert_sha384_x509 if hasattr(self, '_m_is_cert_sha384_x509') else None @property def is_cert_rsa2048_sha256(self): """RSA-2048 signature of a SHA-256 hash. .. seealso:: EFI_CERT_RSA2048_SHA256_GUID """ if hasattr(self, '_m_is_cert_rsa2048_sha256'): return self._m_is_cert_rsa2048_sha256 if hasattr(self, '_m_is_cert_rsa2048_sha256') else None self._m_is_cert_rsa2048_sha256 = self.signature_type == b"\x90\x61\xB3\xE2\x9B\x87\x3D\x4A\xAD\x8D\xF2\xE7\xBB\xA3\x27\x84" return self._m_is_cert_rsa2048_sha256 if hasattr(self, '_m_is_cert_rsa2048_sha256') else None @property def is_cert_der_pkcs7(self): """DER-encoded PKCS #7 version 1.5 [RFC2315]. .. seealso:: EFI_CERT_TYPE_PKCS7_GUID """ if hasattr(self, '_m_is_cert_der_pkcs7'): return self._m_is_cert_der_pkcs7 if hasattr(self, '_m_is_cert_der_pkcs7') else None self._m_is_cert_der_pkcs7 = self.signature_type == b"\x9D\xD2\xAF\x4A\xDF\x68\xEE\x49\x8A\xA9\x34\x7D\x37\x56\x65\xA7" return self._m_is_cert_der_pkcs7 if hasattr(self, '_m_is_cert_der_pkcs7') else None class SignatureData(KaitaiStruct): """ .. seealso:: EFI_SIGNATURE_DATA """ SEQ_FIELDS = ["owner", "data"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['owner']['start'] = self._io.pos() self.owner = self._io.read_bytes(16) self._debug['owner']['end'] = self._io.pos() self._debug['data']['start'] = self._io.pos() self.data = self._io.read_bytes_full() self._debug['data']['end'] = self._io.pos() class EfiVarAttr(KaitaiStruct): """Attributes of a UEFI variable.""" SEQ_FIELDS = ["enhanced_authenticated_access", "append_write", "time_based_authenticated_write_access", "authenticated_write_access", "hardware_error_record", "runtime_access", "bootservice_access", "non_volatile", "reserved1"] def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._debug = collections.defaultdict(dict) def _read(self): self._debug['enhanced_authenticated_access']['start'] = self._io.pos() self.enhanced_authenticated_access = self._io.read_bits_int_be(1) != 0 self._debug['enhanced_authenticated_access']['end'] = self._io.pos() self._debug['append_write']['start'] = self._io.pos() self.append_write = self._io.read_bits_int_be(1) != 0 self._debug['append_write']['end'] = self._io.pos() self._debug['time_based_authenticated_write_access']['start'] = self._io.pos() self.time_based_authenticated_write_access = self._io.read_bits_int_be(1) != 0 self._debug['time_based_authenticated_write_access']['end'] = self._io.pos() self._debug['authenticated_write_access']['start'] = self._io.pos() self.authenticated_write_access = self._io.read_bits_int_be(1) != 0 self._debug['authenticated_write_access']['end'] = self._io.pos() self._debug['hardware_error_record']['start'] = self._io.pos() self.hardware_error_record = self._io.read_bits_int_be(1) != 0 self._debug['hardware_error_record']['end'] = self._io.pos() self._debug['runtime_access']['start'] = self._io.pos() self.runtime_access = self._io.read_bits_int_be(1) != 0 self._debug['runtime_access']['end'] = self._io.pos() self._debug['bootservice_access']['start'] = self._io.pos() self.bootservice_access = self._io.read_bits_int_be(1) != 0 self._debug['bootservice_access']['end'] = self._io.pos() self._debug['non_volatile']['start'] = self._io.pos() self.non_volatile = self._io.read_bits_int_be(1) != 0 self._debug['non_volatile']['end'] = self._io.pos() self._debug['reserved1']['start'] = self._io.pos() self.reserved1 = self._io.read_bits_int_be(24) self._debug['reserved1']['end'] = self._io.pos()
listagem = ('Pão', 0.8, 'Lápis', 1, 'Arroz', 10, 'monitor', 600, 'Suco de Pêra', 6, 'sorvete', 10) print('=' * 40) print(f'{"LISTAGEM DE PREÇOS":^40}') print('=' * 40) print(f'Nome{"Valor":>36}') for c in range(0, len(listagem)): if (c / 2).is_integer(): print(f'{listagem[c]:.<31}', end='') tamanho = len(listagem[c]) else: print(f'R${float(listagem[c]):>7.2f}') print('=' * 40)
#import packages import os import sys import time import json import numpy as np import pandas as pd import urllib.parse import urllib.request from tqdm import tqdm from datetime import datetime from pandas import json_normalize # generate game review df: #steam 'chunks' their json files (the game reviews) in sets of 100 #ending with a signature, a 'cursor'. This cursor is then pasted #onto the the same url, to 'grab' the next chunk and so on. #This sequence block with an 'end cursor' of 'AoJ4tey90tECcbOXSw==' #set variables url_base = 'https://store.steampowered.com/appreviews/393380?json=1&filter=updated&language=all&review_type=all&purchase_type=all&num_per_page=100&cursor=' working_dir = os.getcwd() output_dir = working_dir[:-8]+"data/raw/game_reviews_raw.csv" #first pass url = urllib.request.urlopen("https://store.steampowered.com/appreviews/393380?json=1&filter=updated&language=all&review_type=all&purchase_type=all&num_per_page=100&cursor=*") data = json.loads(url.read().decode()) next_cursor = data['cursor'] next_cursor = next_cursor.replace('+', '%2B') df1 = json_normalize(data['reviews']) print(next_cursor) #add results till stopcursor met, then send all results to csv while True: time.sleep(0.5) # sleep for half-second url_temp = url_base + next_cursor url = urllib.request.urlopen(url_temp) data = json.loads(url.read().decode()) next_cursor = data['cursor'] next_cursor = next_cursor.replace('+', '%2B') df2 = json_normalize(data['reviews']) df1 = pd.concat([df1, df2]) print(next_cursor) if next_cursor == 'AoJ44PCp0tECd4WXSw==' or next_cursor == '*': #stopcursor df_game_reviews = df1 df1 = None df_game_reviews.to_csv(output_dir, index=False) print('All finished! Check raw data directory for output.') break #the hash output is each 'cursor' we loop through until the 'end cursor'. #use this to monitor the download.
"""Arguments parsing""" from copy import deepcopy from functools import wraps from .argsparser import QuartParser class ArgumentsMixin: """Extend Blueprint to add arguments parsing feature""" ARGUMENTS_PARSER = QuartParser() def arguments( self, schema, *, location='json', content_type=None, required=True, description=None, example=None, examples=None, **kwargs ): """Decorator specifying the schema used to deserialize parameters :param type|Schema schema: Marshmallow ``Schema`` class or instance used to deserialize and validate the argument. :param str location: Location of the argument. :param str content_type: Content type of the argument. Should only be used in conjunction with ``json``, ``form`` or ``files`` location. The default value depends on the location and is set in ``Blueprint.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING``. This is only used for documentation purpose. :param bool required: Whether argument is required (default: True). :param str description: Argument description. :param dict example: Parameter example. :param list examples: List of parameter examples. :param dict kwargs: Keyword arguments passed to the webargs :meth:`use_args <webargs.core.Parser.use_args>` decorator used internally. The `required` and `description` only affect `body` arguments (OpenAPI 2) or `requestBody` (OpenAPI 3), because the docs expose the whole schema. For other locations, the schema is turned into an array of parameters and the required/description value of each parameter item is taken from the corresponding field in the schema. The `example` and `examples` parameters are mutually exclusive and should only be used with OpenAPI 3 and when location is ``json``. See :doc:`Arguments <arguments>`. """ # At this stage, put schema instance in doc dictionary. Il will be # replaced later on by $ref or json. parameters = { 'in': location, 'required': required, 'schema': schema, } if content_type is not None: parameters['content_type'] = content_type if example is not None: parameters['example'] = example if examples is not None: parameters['examples'] = examples if description is not None: parameters['description'] = description def decorator(func): @wraps(func) async def wrapper(*f_args, **f_kwargs): return await func(*f_args, **f_kwargs) # Add parameter to parameters list in doc info in function object # The deepcopy avoids modifying the wrapped function doc wrapper._apidoc = deepcopy(getattr(wrapper, '_apidoc', {})) wrapper._apidoc.setdefault('parameters', []).append(parameters) # Call use_args (from webargs) to inject params in function return self.ARGUMENTS_PARSER.use_args( schema, locations=[location], **kwargs)(wrapper) return decorator
import re from typing import List, Union from requirement_auditor.exceptions import RequirementAuditorException class VersionRequirement: operator: str = '==' version: str = '' def __init__(self, operator, version): self.operator = operator self.version = version class Comment: content: str = '' class PythonRequirement: name: str = '' comment: str = '' line_number: int = -1 REGEXP_REQUIREMENT = re.compile( r"(?P<library>[\w_-]+)(?P<specs>(?:[\>\<\=]=))(?P<version>[\w\.\-_]+)" r",?((?P<specs2>[><]=)(?P<version2>[\w\.\-_]+))?\s*(?:#(?P<comment>.*))?" ) REGEXP_FILE = re.compile(r'^-r\s+(?P<file>[\w\-_\.\\\/]+txt)\s*#?(?P<comment>.*)?') def __init__(self, line: str): self.versions: List[VersionRequirement] = list() self.raw_line: str = line def __str__(self): if len(self.versions) == 1: return f'{self.name}{self.versions[0].operator}{self.versions[0].version}' elif len(self.versions) == 2: return f'{self.name}{self.versions[0].operator}{self.versions[0].version},' \ f'{self.versions[1].operator}{self.versions[1].version}' else: return f'# [RAW] {self.raw_line}' def add_version(self, operator, version): if len(self.versions) == 2: msg = 'You can only have up to 2 versions in a requirement.' raise RequirementAuditorException(msg) self.versions.append(VersionRequirement(operator, version)) @classmethod def parse_line(cls, line: str) -> Union['PythonRequirement']: match = cls.REGEXP_REQUIREMENT.match(line) requirement = PythonRequirement(line) if match: requirement.name = match.group('library') if match.group('specs'): requirement.add_version(match.group('specs'), match.group('version')) if match.group('specs2'): requirement.add_version(match.group('specs2'), match.group('version2')) requirement.comment = match.group('comment') return requirement class RequirementFile: def __init__(self, filename: str): self.filename = filename self.requirement_list: Union[List[PythonRequirement], None] = None @property def requirements(self): if self.requirement_list is None: self.requirement_list = list(self) return self.requirement_list def __iter__(self): if isinstance(self.requirement_list, list): for req in self.requirement_list: yield req return with open(self.filename, 'r') as txt_file: for line in txt_file: requirement = PythonRequirement.parse_line(line.strip()) yield requirement
import io import math import os import re import random import sys import time from datetime import datetime import argparse import logging import logging.config import traceback import concurrent.futures import threading import requests from configobj import ConfigObj import shapefile import shapely.geometry from PIL import Image, ImageEnhance, ImageOps Image.MAX_IMAGE_PIXELS = None import tweepy TILE_SIZE = 256 # in pixels EARTH_CIRCUMFERENCE = 40075.016686 * 1000 # in meters, at the equator USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36" LOGGER = None VERBOSITY = None class WebMercator: """Various functions related to the Web Mercator projection.""" @staticmethod def project(geopoint, zoom): """ An implementation of the Web Mercator projection (see https://en.wikipedia.org/wiki/Web_Mercator_projection#Formulas) that returns floats. That's required for cropping of stitched-together tiles such that they only show the configured area, hence no use of math.floor here. """ factor = (1 / (2 * math.pi)) * 2 ** zoom x = factor * (math.radians(geopoint.lon) + math.pi) y = factor * (math.pi - math.log(math.tan((math.pi / 4) + (math.radians(geopoint.lat) / 2)))) return (x, y) class GeoPoint: """ A latitude-longitude coordinate pair, in that order due to ISO 6709, see: https://stackoverflow.com/questions/7309121/preferred-order-of-writing-latitude-longitude-tuples """ def __init__(self, lat, lon): assert -90 <= lat <= 90 and -180 <= lon <= 180 self.lat = lat self.lon = lon def __repr__(self): return f"GeoPoint({self.lat}, {self.lon})" def fancy(self): """Stringifies the point in a more fancy way than __repr__, e.g. "44°35'27.6"N 100°21'53.1"W", i.e. with minutes and seconds.""" # helper function as both latitude and longitude are stringified # basically the same way def fancy_coord(coord, pos, neg): coord_dir = pos if coord > 0 else neg coord_tmp = abs(coord) coord_deg = math.floor(coord_tmp) coord_tmp = (coord_tmp - math.floor(coord_tmp)) * 60 coord_min = math.floor(coord_tmp) coord_sec = round((coord_tmp - math.floor(coord_tmp)) * 600) / 10 coord = f"{coord_deg}°{coord_min}'{coord_sec}\"{coord_dir}" return coord lat = fancy_coord(self.lat, "N", "S") lon = fancy_coord(self.lon, "E", "W") return f"{lat} {lon}" @classmethod def random(cls, georect): """ Generating a random point with regard to actual surface area is a bit tricky due to meridians being closer together at high latitudes (see https://en.wikipedia.org/wiki/Mercator_projection#Distortion_of_sizes), which is why this isn't just a matter of doing something like this: lat = random.uniform(georect.sw.lat, georect.ne.lat) lon = random.uniform(georect.sw.lon, georect.ne.lon) """ # latitude north = math.radians(georect.ne.lat) south = math.radians(georect.sw.lat) lat = math.degrees(math.asin(random.random() * (math.sin(north) - math.sin(south)) + math.sin(south))) # longitude west = georect.sw.lon east = georect.ne.lon width = east - west if width < 0: width += 360 lon = west + width * random.random() if lon > 180: lon -= 360 elif lon < -180: lon += 360 # for debugging: """ for i in range(1000): p = GeoPoint.random(GeoRect(GeoPoint(0,0),GeoPoint(90,10))) print(f"{p.lon} {p.lat}") sys.exit() # run as: python3 aerialbot.py | gnuplot -p -e "plot '<cat'" """ return cls(lat, lon) def to_maptile(self, zoom): """ Conversion of this geopoint to a tile through application of the Web Mercator projection and flooring to get integer tile corrdinates. """ x, y = WebMercator.project(self, zoom) return MapTile(zoom, math.floor(x), math.floor(y)) def to_shapely_point(self): """ Conversion to a point as expected by shapely. Note that latitude and longitude are reversed here – this matches their order in shapefiles. """ return shapely.geometry.Point(self.lon, self.lat) def compute_zoom_level(self, max_meters_per_pixel): """ Computes the outermost (i.e. lowest) zoom level that still fulfills the constraint. See: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale """ meters_per_pixel_at_zoom_0 = ((EARTH_CIRCUMFERENCE / TILE_SIZE) * math.cos(math.radians(self.lat))) # 23 seems to be highest zoom level supported anywhere in the world, see # https://stackoverflow.com/a/32407072 (although 19 or 20 is the highest # in many places in practice) for zoom in reversed(range(0, 23+1)): meters_per_pixel = meters_per_pixel_at_zoom_0 / (2 ** zoom) # once meters_per_pixel eclipses the maximum, we know that the # previous zoom level was correct if meters_per_pixel > max_meters_per_pixel: return zoom + 1 else: # if no match, the required zoom level would have been too high raise RuntimeError("your settings seem to require a zoom level higher than is commonly available") class GeoRect: """ A rectangle between two points. The first point must be the southwestern corner, the second point the northeastern corner: +---+ ne | | sw +---+ """ def __init__(self, sw, ne): assert sw.lat <= ne.lat # not assert sw.lon < ne.lon since it may stretch across the date line self.sw = sw self.ne = ne def __repr__(self): return f"GeoRect({self.sw}, {self.ne})" @classmethod def from_shapefile_bbox(cls, bbox): """ Basically from [sw_lon, sw_lat, ne_lon, sw_lat], which is the order pyshp stores bounding boxes in. """ sw = GeoPoint(bbox[1], bbox[0]) ne = GeoPoint(bbox[3], bbox[2]) return cls(sw, ne) @classmethod def around_geopoint(cls, geopoint, width, height): """ Creates a rectangle with the given point at its center. Like the random point generator, this accounts for high-latitude longitudes being closer together than at the equator. See also: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale """ assert width > 0 and height > 0 meters_per_degree = (EARTH_CIRCUMFERENCE / 360) width_geo = width / (meters_per_degree * math.cos(math.radians(geopoint.lat))) height_geo = height / meters_per_degree southwest = GeoPoint(geopoint.lat - height_geo / 2, geopoint.lon - width_geo / 2) northeast = GeoPoint(geopoint.lat + height_geo / 2, geopoint.lon + width_geo / 2) return cls(southwest, northeast) class GeoShape: """ This class is where shapefiles (of the form detailed in the config example, i.e. containing one layer with one polygon shape with lon/lat coordinates) are loaded and queried. Note that shapefiles use (lon, lat) coordinates, which are sequestered to this class only. """ def __init__(self, shapefile_path): sf = shapefile.Reader(shapefile_path) shapes = sf.shapes() assert len(shapes) == 1 assert shapes[0].shapeTypeName == 'POLYGON' self.outline = shapes[0] def contains(self, geopoint): """Does the shape contain the point?""" point = geopoint.to_shapely_point() polygon = shapely.geometry.shape(self.outline) return polygon.contains(point) def random_geopoint(self): """ A random geopoint, using rejection sampling to make sure it's contained within the shape. """ bounds = GeoRect.from_shapefile_bbox(self.outline.bbox) geopoint = GeoPoint.random(bounds) i = 0 while not self.contains(geopoint): i += 1 if i > 250: raise ValueError("cannot seem to find a point in the shape's bounding box that's within the shape – is your data definitely okay (it may well be if it's a bunch of spread-out islands)? if you're sure, you'll need to raise the iteration limit in this function") geopoint = GeoPoint.random(bounds) return geopoint class MapTileStatus: """An enum type used to keep track of the current status of map tiles.""" PENDING = 1 CACHED = 2 DOWNLOADING = 3 DOWNLOADED = 4 ERROR = 5 class MapTile: """ A map tile: coordinates and, if it's been downloaded yet, image, plus some housekeeping stuff. """ # static class members set based on the configuration tile_path_template = None tile_url_template = None def __init__(self, zoom, x, y): self.zoom = zoom self.x = x self.y = y # initialize the other variables self.status = MapTileStatus.PENDING self.image = None self.filename = None if (MapTile.tile_path_template): self.filename = MapTile.tile_path_template.format(zoom=self.zoom, x=self.x, y=self.y) def __repr__(self): return f"MapTile({self.zoom}, {self.x}, {self.y})" def zoomed(self, zoom_delta): """ Returns a MapTileGrid of the area covered by this map tile, but zoomed by zoom_delta. This works this way because by increasing the zoom level by 1, a tile's area is subdivided into 4 quadrants. """ zoom = self.zoom + zoom_delta fac = (2 ** zoom_delta) return MapTileGrid([[MapTile(zoom, self.x * fac + x, self.y * fac + y) for y in range(0, fac)] for x in range(0, fac)]) def load(self): """Loads the image either from cache or initiates a download.""" if self.filename is None: self.download() else: # check if already downloaded in tile store, otherwise download try: self.image = Image.open(self.filename) self.image.load() self.status = MapTileStatus.CACHED except IOError: self.download() def download(self): """ Downloads a tile image. Sets the status to ERROR if things don't work out for whatever reason. Finally, writes the image to the cache if enabled. """ self.status = MapTileStatus.DOWNLOADING try: url = MapTile.tile_url_template.format(x=self.x, y=self.y, zoom=self.zoom) r = requests.get(url, headers={'User-Agent': USER_AGENT}) except requests.exceptions.ConnectionError: self.status = MapTileStatus.ERROR return # error handling (note that a warning is appropriate here – if this tile # is one of a tiles used in imagery quality testing, an error is not an # unexpected outcome and should thus not be thrown) if r.status_code != 200: LOGGER.warning(f"Unable to download {self}, status code {r.status_code}.") self.status = MapTileStatus.ERROR return # convert response into an image data = r.content self.image = Image.open(io.BytesIO(data)) # sanity check assert self.image.mode == "RGB" assert self.image.size == (TILE_SIZE, TILE_SIZE) # save original data (not: re-encoded via image.save) in tile store if # enabled (and create the directory first if it doesn't already exist) if self.filename is not None: d = os.path.dirname(self.filename) if not os.path.isdir(d): os.makedirs(d) with open(self.filename, 'wb') as f: f.write(data) self.status = MapTileStatus.DOWNLOADED class ProgressIndicator: """ Displays and updates a progress indicator during tile download. Designed to run in a separate thread, polling for status updates frequently. """ def __init__(self, maptilegrid): self.maptilegrid = maptilegrid def update_tile(self, maptile): """ Updates a single tile depending on its state: pending tiles are grayish, cached tiles are blue, downloading tiles are yellow, successfully downloaded tiles are green, and tiles with errors are red. For each tile, two characters are printed – in most fonts, this is closer to a square than a single character. See https://stackoverflow.com/a/39452138 for color escapes. """ def p(s): print(s + "\033[0m", end='') if maptile.status == MapTileStatus.PENDING: p("░░") elif maptile.status == MapTileStatus.CACHED: p("\033[34m" + "██") elif maptile.status == MapTileStatus.DOWNLOADING: p("\033[33m" + "▒▒") elif maptile.status == MapTileStatus.DOWNLOADED: p("\033[32m" + "██") elif maptile.status == MapTileStatus.ERROR: p("\033[41m\033[37m" + "XX") def update_text(self): """ Displays percentage and counts only. """ cached = 0 downloaded = 0 errors = 0 for maptile in self.maptilegrid.flat(): if maptile.status == MapTileStatus.CACHED: cached += 1 elif maptile.status == MapTileStatus.DOWNLOADED: downloaded += 1 elif maptile.status == MapTileStatus.ERROR: errors += 1 done = cached + downloaded total = self.maptilegrid.width * self.maptilegrid.height percent = int(10 * (100 * done / total)) / 10 details = f"{done}/{total}" if cached: details += f", {cached} cached" if downloaded: details += f", {downloaded} downloaded" if errors: details += f", {errors} error" if errors > 1: details += "s" # need a line break after it so that the first line of the next # iteration of the progress indicator starts at col 0 print(f"{percent}% ({details})") def update(self): """Updates the progress indicator.""" # if normal verbosity is selected, don't do anything fancy if VERBOSITY == "normal": self.update_text() return for y in range(self.maptilegrid.height): for x in range(self.maptilegrid.width): maptile = self.maptilegrid.at(x, y) self.update_tile(maptile) print() # line break self.update_text() # move cursor back up to the beginning of the progress indicator for # the next iteration, see # http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html print(f"\033[{self.maptilegrid.height + 1}A", end='') def loop(self): """Main loop.""" if VERBOSITY == "quiet": return while any([maptile.status is MapTileStatus.PENDING or maptile.status is MapTileStatus.DOWNLOADING for maptile in self.maptilegrid.flat()]): self.update() time.sleep(0.1) self.update() # final update to show that we're all done def cleanup(self): """Moves the cursor back to the bottom after completion.""" if VERBOSITY == "quiet" or VERBOSITY == "normal": return print(f"\033[{self.maptilegrid.height}B") class MapTileGrid: """ A grid of map tiles, kepts as a nested list such that indexing works via [x][y]. Manages the download and stitching of map tiles into a preliminary result image. """ def __init__(self, maptiles): self.maptiles = maptiles self.width = len(maptiles) self.height = len(maptiles[0]) self.image = None def __repr__(self): return f"MapTileGrid({self.maptiles})" @classmethod def from_georect(cls, georect, zoom): """Divides a GeoRect into a grid of map tiles.""" southwest = georect.sw.to_maptile(zoom) northeast = georect.ne.to_maptile(zoom) maptiles = [] for x in range(southwest.x, northeast.x + 1): col = [] # it's correct to have northeast and southwest reversed here (with # regard to the outer loop) since y axis of the tile coordinates # points toward the south, while the latitude axis points due north for y in range(northeast.y, southwest.y + 1): maptile = MapTile(zoom, x, y) col.append(maptile) maptiles.append(col) return cls(maptiles) def at(self, x, y): """Accessor with wraparound for negative values: x/y<0 => x/y+=w/h.""" if x < 0: x += self.width if y < 0: y += self.height return self.maptiles[x][y] def flat(self): """Returns the grid as a flattened list.""" return [maptile for col in self.maptiles for maptile in col] def has_high_quality_imagery(self): """ Checks if the corners of the grid are available two levels more zoomed in, which should make sure that we're getting high-quality imagery at the original zoom level. """ zoom_delta = 2 # since the at() function wraps around, [self.at(x, y) for x and y in # [0,-1]] selects the four corners of the grid, then for each of them a # "subgrid" is generated using .zoomed(), and for each of them, the # relevant corner is accessed through reuse of x and y corners = [self.at(x, y).zoomed(zoom_delta).at(x, y) for x in [0, -1] for y in [0, -1]] # check if they have all downloaded successfully all_good = True for c in corners: c.load() if c.status == MapTileStatus.ERROR: all_good = False break return all_good def download(self): """ Downloads the constitudent tiles using a threadpool for performance while updating the progress indicator. """ # set up progress indicator prog = ProgressIndicator(self) prog_thread = threading.Thread(target=prog.loop) prog_thread.start() # shuffle the download order of the tiles, this serves no actual purpose # but it makes the progress indicator look really cool! tiles = self.flat() random.shuffle(tiles) # download tiles using threadpool (2-10 times faster than # [maptile.load() for maptile in self.flat()]), see # https://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example threads = max(self.width, self.height) with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as executor: {executor.submit(maptile.load): maptile for maptile in tiles} # retry failed downloads if fewer than 2% of tiles are missing (happens # frequently when pulling from naver map) missing_tiles = [maptile for maptile in self.flat() if maptile.status == MapTileStatus.ERROR] if 0 < len(missing_tiles) < 0.02 * len(self.flat()): if VERBOSITY != "quiet": print("Retrying missing tiles...") for maptile in missing_tiles: maptile.load() # finish up progress indicator prog_thread.join() prog.cleanup() # check if we've got everything now missing_tiles = [maptile for maptile in self.flat() if maptile.status == MapTileStatus.ERROR] if missing_tiles: raise RuntimeError(f"unable to load one or more map tiles: {missing_tiles}") def stitch(self): """ Stitches the tiles together. Must not be called before all tiles have been loaded. """ image = Image.new('RGB', (self.width * TILE_SIZE, self.height * TILE_SIZE)) for x in range(0, self.width): for y in range(0, self.height): image.paste(self.maptiles[x][y].image, (x * TILE_SIZE, y * TILE_SIZE)) self.image = image class MapTileImage: """Image cropping, resizing and enhancement.""" def __init__(self, image): self.image = image def save(self, path, quality=90): self.image.save(path, quality=quality) def crop(self, zoom, georect): """ Crops the image such that it really only covers the area within the input GeoRect. This function must only be called once per image. """ sw_x, sw_y = WebMercator.project(georect.sw, zoom) ne_x, ne_y = WebMercator.project(georect.ne, zoom) # determine what we'll cut off sw_x_crop = round(TILE_SIZE * (sw_x % 1)) sw_y_crop = round(TILE_SIZE * (1 - sw_y % 1)) ne_x_crop = round(TILE_SIZE * (1 - ne_x % 1)) ne_y_crop = round(TILE_SIZE * (ne_y % 1)) # left, top, right, bottom crop = (sw_x_crop, ne_y_crop, ne_x_crop, sw_y_crop) # snip snap self.image = ImageOps.crop(self.image, crop) def scale(self, width, height): """ Scales an image. This can distort the image if width and height don't match the original aspect ratio. """ # Image.LANCZOS apparently provides the best quality, see # https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-filters self.image = self.image.resize((round(width), round(height)), resample=Image.LANCZOS) def enhance(self): """Slightly increases contrast and brightness.""" # these values seem to work well for most images – a more adaptive # method would but nice, but it's not a priority contrast = 1.07 brightness = 1.01 self.image = ImageEnhance.Contrast(self.image).enhance(contrast) self.image = ImageEnhance.Brightness(self.image).enhance(brightness) class Log: """ A simplifying wrapper around the parts of the logging module that are relevant here, plus some minor extensions. Goal: Logging of warnings (depending on verbosity level), errors and exceptions on stderr, other messages (modulo verbosity) on stdout, and everything (independent of verbosity) in a logfile. """ def __init__(self, logfile): # name and initialize logger self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) # via https://stackoverflow.com/a/36338212 class LevelFilter(logging.Filter): def __init__(self, low, high): self.low = low self.high = high logging.Filter.__init__(self) def filter(self, record): return self.low <= record.levelno <= self.high # log errors (and warnings if a higher verbosity level is dialed in) on # stderr eh = logging.StreamHandler() if VERBOSITY == "quiet": eh.setLevel(logging.ERROR) else: eh.setLevel(logging.WARNING) eh.addFilter(LevelFilter(logging.WARNING, logging.CRITICAL)) stream_formatter = logging.Formatter('%(message)s') eh.setFormatter(stream_formatter) self.logger.addHandler(eh) # log other messages on stdout if verbosity not set to quiet if VERBOSITY != "quiet": oh = logging.StreamHandler(stream=sys.stdout) if VERBOSITY == "deafening": oh.setLevel(logging.DEBUG) elif VERBOSITY == "verbose" or VERBOSITY == "normal": oh.setLevel(logging.INFO) oh.addFilter(LevelFilter(logging.DEBUG, logging.INFO)) stream_formatter = logging.Formatter('%(message)s') oh.setFormatter(stream_formatter) self.logger.addHandler(oh) # log everything to file independent of verbosity if logfile is not None: fh = logging.FileHandler(logfile) fh.setLevel(logging.DEBUG) file_formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%dT%H:%M:%S') fh.setFormatter(file_formatter) self.logger.addHandler(fh) def debug(self, s): self.logger.debug(s) def info(self, s): self.logger.info(s) def warning(self, s): self.logger.warning(s) def error(self, s): self.logger.error(s) def critical(self, s): self.logger.critical(s) def exception(self, e): """ Logging of game-breaking exceptions, based on: https://stackoverflow.com/a/40428650 """ e_traceback = traceback.format_exception(e.__class__, e, e.__traceback__) traceback_lines = [] for line in [line.rstrip('\n') for line in e_traceback]: traceback_lines.extend(line.splitlines()) for line in traceback_lines: self.critical(line) sys.exit(1) class Tweeter: """Basic class for tweeting images, a simple wrapper around tweepy.""" def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret): # for references, see: # http://docs.tweepy.org/en/latest/api.html#status-methods # https://developer.twitter.com/en/docs/tweets/post-and-engage/guides/post-tweet-geo-guide auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(auth) def get_location(self, geopoint): full_name = "" country = "" try: location = self.api.reverse_geocode(geopoint.lat, geopoint.lon) if location: full_name = location[0].full_name country = location[0].country except KeyError: # can apparently sometimes occur if twitter doesn't have geodata # for the selected location pass return (full_name, country) def upload(self, path): """Uploads an image to Twitter.""" return self.api.media_upload(path) def tweet(self, text, media, geopoint=None): if geopoint: self.api.update_status( text, media_ids=[media.media_id], lat=geopoint.lat, long=geopoint.lon, display_coordinates=True ) else: self.api.update_status(text, media_ids=[media.media_id]) def main(): global VERBOSITY global LOGGER # handle potential cli arguments parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--help', action='help', default=argparse.SUPPRESS, help=argparse._('show this help message and exit')) # override default help argument so that only --help (and not -h) can call parser.add_argument('config_path', metavar='CONFIG_PATH', type=str, nargs='?', default="config.ini", help='config file to use instead of looking for config.ini in the current working directory') parser.add_argument('-p', '--point', dest='point', metavar='LAT,LON', type=str, help='a point, e.g. \'37.453896,126.446829\', that will override your configuration (if its latitide is negative, option parsing might throw an error – simply write -p="LAT,LON" in that case)') # https://stackoverflow.com/questions/16174992/cant-get-argparse-to-read-quoted-string-with-dashes-in-it parser.add_argument('-m', '--max-meters-per-pixel', dest='max_meters_per_pixel', metavar='N', type=float, help='a maximum meters per pixel constraint that will override your configuration') parser.add_argument('-w', '--width', dest='width', metavar='N', type=float, help='width of the depicted area in meters, will override your configuration') parser.add_argument('-h', '--height', dest='height', metavar='N', type=float, help='height of the depicted area in meters, will override your configuration') parser.add_argument('--image_width', dest='image_width', metavar='N', type=float, help='width of the result image, will override your configuration (where you can also find an explanation of how this option interacts with the -m, -w, and -h options)') parser.add_argument('--image_height', dest='image_height', metavar='N', type=float, help='height of the result image, will override your configuration (where you can also find an explanation of how this option interacts with the -m, -w, and -h options)') args = parser.parse_args() # load configuration either from config.ini or from a user-supplied file # (the latter option is handy if you want to run multiple instances of # ærialbot with different configurations) config = ConfigObj(args.config_path, unrepr=True) # first of all, set up logging at the correct verbosity (and make the # verbosity available globally since it's needed for the progress indicator) VERBOSITY = config['GENERAL']['verbosity'] logfile = config['GENERAL']['logfile'] LOGGER = Log(logfile) ############################################################################ # copy the configuration into variables for brevity tile_path_template = config['GENERAL']['tile_path_template'] image_path_template = config['GENERAL']['image_path_template'] tile_url_template = config['GEOGRAPHY']['tile_url_template'] shapefile = config['GEOGRAPHY']['shapefile'] point = config['GEOGRAPHY']['point'] width = config['GEOGRAPHY']['width'] height = config['GEOGRAPHY']['height'] image_width = config['IMAGE']['image_width'] image_height = config['IMAGE']['image_height'] max_meters_per_pixel = config['IMAGE']['max_meters_per_pixel'] apply_adjustments = config['IMAGE']['apply_adjustments'] image_quality = config['IMAGE']['image_quality'] consumer_key = config['TWITTER']['consumer_key'] consumer_secret = config['TWITTER']['consumer_secret'] access_token = config['TWITTER']['access_token'] access_token_secret = config['TWITTER']['access_token_secret'] tweet_text = config['TWITTER']['tweet_text'] include_location_in_metadata = config['TWITTER']['include_location_in_metadata'] # override configured options with values supplied via the cli if args.point: point = tuple(map(float, args.point.split(","))) if args.max_meters_per_pixel: max_meters_per_pixel = args.max_meters_per_pixel if args.width: width = args.width if args.height: height = args.height if args.image_width: image_width = args.image_width if args.image_height: image_height = args.image_height ############################################################################ LOGGER.info("Processing configuration...") # handle tile url special cases if tile_url_template == "googlemaps": tile_url_template = "https://khms2.google.com/kh/v={google_maps_version}?x={x}&y={y}&z={zoom}" elif tile_url_template == "navermap": tile_url_template = "https://map.pstatic.net/nrb/styles/satellite/{naver_map_version}/{zoom}/{x}/{y}.jpg?mt=bg" if "{google_maps_version}" in tile_url_template: LOGGER.info("Determining current Google Maps version and patching tile URL template...") # automatic fallback: current as of July 2021, will likely continue # to work for at least a while google_maps_version = '904' try: google_maps_page = requests.get("https://maps.googleapis.com/maps/api/js", headers={"User-Agent": USER_AGENT}).content match = re.search(rb"khms0\.googleapis\.com\/kh\?v=([0-9]+)", google_maps_page) if match: google_maps_version = match.group(1).decode('ascii') LOGGER.debug(google_maps_version) else: LOGGER.warning(f"Unable to extract current version, proceeding with outdated version {google_maps_version} instead.") except requests.RequestException as e: LOGGER.warning(f"Unable to load Google Maps, proceeding with outdated version {google_maps_version} instead.") tile_url_template = tile_url_template.replace("{google_maps_version}", google_maps_version) if "{naver_map_version}" in tile_url_template: LOGGER.info("Determining current Naver Map version and patching tile URL template...") naver_map_version = requests.get("https://map.pstatic.net/nrb/styles/satellite.json", headers={'User-Agent': USER_AGENT}).json()["version"] LOGGER.debug(naver_map_version) tile_url_template = tile_url_template.replace("{naver_map_version}", naver_map_version) MapTile.tile_path_template = tile_path_template MapTile.tile_url_template = tile_url_template # process max_meters_per_pixel setting if image_width is None and image_height is None: assert max_meters_per_pixel is not None elif image_height is None: max_meters_per_pixel = (max_meters_per_pixel or 1) * (width / image_width) elif image_width is None: max_meters_per_pixel = (max_meters_per_pixel or 1) * (height / image_height) else: # if both are set, effectively use whatever imposes a tighter constraint if width / image_width <= height / image_height: max_meters_per_pixel = (max_meters_per_pixel or 1) * (width / image_width) else: max_meters_per_pixel = (max_meters_per_pixel or 1) * (height / image_height) # process image width and height for scaling if image_width is not None or image_height is not None: if image_height is None: image_height = height * (image_width / width) elif image_width is None: image_width = width * (image_height / height) # whether to enable or disable tweeting tweeting = all(x is not None for x in [consumer_key, consumer_secret, access_token, access_token_secret]) ############################################################################ if shapefile is None and point is None: raise RuntimeError("neither shapefile path nor point configured") elif point is None: LOGGER.info("Loading shapefile...") LOGGER.debug(shapefile) shape = GeoShape(shapefile) tries = 0 while True: tries += 1 if tries > 10: raise RuntimeError("too many retries – maybe there's no internet connection? either that, or your max_meters_per_pixel setting is too low") if point is None: LOGGER.info("Generating random point within shape...") p = shape.random_geopoint() else: LOGGER.info("Using configured point instead of shapefile...") p = GeoPoint(point[0], point[1]) LOGGER.debug(p) LOGGER.info("Computing required tile zoom level at point...") zoom = p.compute_zoom_level(max_meters_per_pixel) LOGGER.debug(zoom) LOGGER.info("Generating rectangle with your selected width and height around point...") rect = GeoRect.around_geopoint(p, width, height) LOGGER.debug(rect) LOGGER.info("Turning rectangle into a grid of map tiles at the required zoom level...") grid = MapTileGrid.from_georect(rect, zoom) LOGGER.debug(grid) # no need to do check quality if the point was set manually – clearly # the user won't mind low-quality imagery if point is not None: break LOGGER.info("Checking quality of imagery available for the map tile grid...") if not grid.has_high_quality_imagery(): LOGGER.info("Not good enough, let's try this again...") else: LOGGER.info("Lookin' good, let's proceed!") break ############################################################################ LOGGER.info("Downloading tiles...") grid.download() LOGGER.info("Stitching tiles together into an image...") grid.stitch() image = MapTileImage(grid.image) LOGGER.info("Cropping image to match the chosen area width and height...") LOGGER.debug((width, height)) image.crop(zoom, rect) if image_width is not None or image_height is not None: LOGGER.info("Scaling image...") LOGGER.debug((image_width, image_height)) image.scale(image_width, image_height) if apply_adjustments: LOGGER.info("Enhancing image...") image.enhance() LOGGER.info("Saving image to disk...") image_path = image_path_template.format( datetime=datetime.today().strftime("%Y-%m-%dT%H.%M.%S"), latitude=p.lat, longitude=p.lon, width=width, height=height, max_meters_per_pixel=max_meters_per_pixel, xmin=grid.at(0, 0).x, xmax=grid.at(0, 0).x+grid.width, ymin=grid.at(0, 0).y, ymax=grid.at(0, 0).y+grid.height, zoom=zoom, georect=f"sw{rect.sw.lat},{rect.sw.lon}ne{rect.ne.lat},{rect.ne.lon}" ) LOGGER.debug(image_path) d = os.path.dirname(image_path) if not os.path.isdir(d): os.makedirs(d) image.save(image_path, image_quality) ############################################################################ if tweeting: LOGGER.info("Connecting to Twitter...") tweeter = Tweeter(consumer_key, consumer_secret, access_token, access_token_secret) #if "location_full_name" in tweet_text or "location_country" in tweet_text: LOGGER.info("Getting location information from Twitter...") (location_full_name, location_country) = tweeter.get_location(p) LOGGER.debug((location_full_name, location_country)) osm_url = f"https://www.openstreetmap.org/#map={zoom}/{p.lat}/{p.lon}" googlemaps_url = f"https://www.google.com/maps/@{p.lat},{p.lon},{zoom}z" LOGGER.info("Uploading image to Twitter...") media = tweeter.upload(image_path) LOGGER.info("Sending tweet...") tweet_text = tweet_text.format( latitude=p.lat, longitude=p.lon, point_fancy=p.fancy(), osm_url=osm_url, googlemaps_url=googlemaps_url, location_full_name=location_full_name, location_country=location_country ) LOGGER.debug(tweet_text) if include_location_in_metadata: tweeter.tweet(tweet_text, media, p) else: tweeter.tweet(tweet_text, media) LOGGER.info("All done!") if __name__ == "__main__": # log all exceptions try: main() except Exception as e: LOGGER.exception(e)
# -*- coding: utf-8 -*- # pylint: disable=unused-import """IPv4 constant enumerations.""" from pcapkit.const.ipv4.classification_level import ClassificationLevel as IPv4_ClassificationLevel from pcapkit.const.ipv4.option_class import OptionClass as IPv4_OptionClass from pcapkit.const.ipv4.option_number import OptionNumber as IPv4_OptionNumber from pcapkit.const.ipv4.protection_authority import ProtectionAuthority as IPv4_ProtectionAuthority from pcapkit.const.ipv4.qs_function import QSFunction as IPv4_QSFunction from pcapkit.const.ipv4.router_alert import RouterAlert as IPv4_RouterAlert from pcapkit.const.ipv4.tos_del import ToSDelay as IPv4_ToSDelay from pcapkit.const.ipv4.tos_ecn import ToSECN as IPv4_ToSECN from pcapkit.const.ipv4.tos_pre import ToSPrecedence as IPv4_ToSPrecedence from pcapkit.const.ipv4.tos_rel import ToSReliability as IPv4_ToSReliability from pcapkit.const.ipv4.tos_thr import ToSThroughput as IPv4_ToSThroughput __all__ = ['IPv4_ClassificationLevel', 'IPv4_OptionClass', 'IPv4_OptionNumber', 'IPv4_ProtectionAuthority', 'IPv4_QSFunction', 'IPv4_RouterAlert', 'IPv4_ToSDelay', 'IPv4_ToSECN', 'IPv4_ToSPrecedence', 'IPv4_ToSReliability', 'IPv4_ToSThroughput']
# Copyright 2016 Google Inc. All Rights Reserved. # # 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. # # pylint: disable=invalid-name """Configuration file for the database. Includes connection parameters, and a convenience function for connecting to the database.""" import os import MySQLdb as mysql # Connection type and parameters can be specified in the environment # itself by manipulating the appropriate env vars. connection = os.getenv('DB_CONNECTION_TYPE', 'tcp_direct') # One dictionary entry for each connection type. This allows us to # store multiple connections in our config and select them at runtime. con_type = { 'tcp_direct': {}, 'cloudsql_proxy': {}, 'cloudsql_tcp': {}, } con_type['tcp_direct'] = { # params for connecting to a db over tcp. 'host': os.getenv('DB_HOST', '127.0.0.1'), 'port': int(os.getenv('DB_PORT', 3306)), } con_type['cloudsql_proxy'] = { # https://github.com/GoogleCloudPlatform/cloudsql-proxy 'project': os.getenv('GCP_PROJECT', 'your-project-name'), 'host': os.getenv('DB_HOST', 'localhost'), 'zone': os.getenv('DB_ZONE', 'your-cloudsql-zone'), 'instance_name': os.getenv('DB_NAME', 'your-cloudsql-instance-name'), } con_type['cloudsql_tcp'] = { # params for connecting to a db over tcp. 'host': os.getenv('DB_HOST', 'your-cloudsql-ip-address'), 'port': int(os.getenv('DB_PORT', 3306)), } # Look in env var for what kind of db connection this environment is using. dbc = con_type[connection] # Elements common to all connection types. dbc.update({ #'user': 'root', #'pass': '/!GLwL`W$)+BdnF', 'user': 'mimus', 'pass': '9dc1b3ae-584c-434e-b899-da2c8ad093fb', 'name': os.getenv('DB_TABLE', 'mimus'), }) # Build the fully qualified cloud sql db name from the config if all # the pieces are there. if 'project' in dbc and 'zone' in dbc and 'instance_name' in dbc: dbc['cloud_sql_db'] = ':'.join( [dbc['project'], dbc['zone'], dbc['instance_name']]) # Build the Cloud SQL proxy socket path from the config # https://cloud.google.com/sql/docs/sql-proxy dbc['path'] = os.path.join('/cloudsql', dbc['cloud_sql_db']) def db_connect(): '''Convenience mysql connect function with args already populated.''' if connection in ['cloudsql_proxy']: # Use the cloudsql proxy return mysql.connect(host=dbc['host'], user=dbc['user'], passwd=dbc['pass'], db=dbc['name'], unix_socket=dbc['path']) else: # standard TCP mysql connection return mysql.connect(host=dbc['host'], port=dbc['port'], user=dbc['user'], passwd=dbc['pass'], db=dbc['name'])
from malwareconfig import crypto from malwareconfig.common import Decoder from malwareconfig.common import string_printable class Alina(Decoder): decoder_name = "Alina" decoder__version = 1 decoder_author = ["@botnet_hunter, @kevthehermit"] decoder_description = "Point of sale malware designed to extract credit card information from RAM" hash_list = ['efd57cde8eee0aae832aac414e1b5577'] def __init__(self): self.config = {} def get_config(self): ''' This is the main entry :return: ''' print(self.file_info.ascii_strings(min_len=4)) config_dict = {} # Set the config to the class for use self.config = config_dict
import re import os import collections import operator def extend(d, u): for k, v in u.items(): if isinstance(v, collections.Mapping): r = extend(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d def list_dirs(path): folders = [] while path != "" and path != None: path, folder = os.path.split(path) if folder != "": folders.append(folder) else: if path!="": folders.append(path) break folders.reverse() return folders def uncapitalize(s): return s[:1].lower() + s[1:] if s else '' def extract_str(raw_string, start_marker, end_marker): start = raw_string.index(start_marker) + len(start_marker) end = raw_string.index(end_marker, start) return raw_string[start:end] first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def camel_case_to_underscore(name): s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() def camel_case_to_hyphenate(name): s1 = first_cap_re.sub(r'\1-\2', name) return all_cap_re.sub(r'\1-\2', s1).lower() def copy_dict(source_dict, diffs): result=dict(source_dict) # Shallow copy result.update(diffs) return result def sort_dict_keys(d): return sorted(d) def sort_dict_values(d): return sorted(d.items(), key=operator.itemgetter(0)) def upcase_first(s): return s[0].upper() + s[1:] def lowercase_first(s): return s[0].lower() + s[1:] def human_string_list(strs, conjunction='or'): n = len(strs) if n == 0: return '' if n == 1: return str(strs[0]) if n == 2: return '{} {} {}'.format(strs[0], conjunction, strs[1]) # else list of >= 3 strs_safe = list(strs) strs_safe[-1] = '{} {}'.format(conjunction, strs_safe[-1]) return ', '.join(strs_safe) def is_primitive_type(type_obj): return (type_obj['name'] in ['null', 'boolean', 'int', 'float', 'string', 'list', 'dictionary'])
from typing import Iterator from cog import BasePredictor, Path class Predictor(BasePredictor): def predict(self, path: Path) -> Iterator[Path]: with open(path) as f: prefix = f.read() predictions = ["foo", "bar", "baz"] for i, prediction in enumerate(predictions): out_path = Path(f"/tmp/out-{i}.txt") with out_path.open("w") as f: f.write(prefix + " " + prediction) yield out_path
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and complete. It calls print_words() and print_top() functions which you write. 1. implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ import sys # +++your code here+++ # Define print_words(filename) and print_top(filename) functions. # You could write a helper utility function that reads a file # and builds and returns a word/count dict for it. # Then print_words() and print_top() can just call the utility function. ### # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(filepath, top=False): if top: print_top(filepath) else: print_words(filepath) main('small.txt', True)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from mathics.core.expression import Expression, Symbol, strip_context, KeyComparable from mathics.core.pattern import Pattern, StopGenerator class StopGenerator_BaseRule(StopGenerator): pass class BaseRule(KeyComparable): def __init__(self, pattern, system=False): super(BaseRule, self).__init__() self.pattern = Pattern.create(pattern) self.system = system def apply(self, expression, evaluation, fully=True, return_list=False, max_list=None): result_list = [] # count = 0 if return_list and max_list is not None and max_list <= 0: return [] def yield_match(vars, rest): if rest is None: rest = ([], []) if 0 < len(rest[0]) + len(rest[1]) == len(expression.get_leaves()): # continue return options = {} for name, value in list(vars.items()): if name.startswith('_option_'): options[name[len('_option_'):]] = value del vars[name] new_expression = self.do_replace(vars, options, evaluation) if new_expression is None: new_expression = expression if rest[0] or rest[1]: result = Expression(expression.get_head(), *( rest[0] + [new_expression] + rest[1])) else: result = new_expression # Flatten out sequences (important for Rule itself!) def flatten(expr): new_expr = expr.flatten(Symbol('Sequence'), pattern_only=True) if not new_expr.is_atom(): for index, leaf in enumerate(new_expr.leaves): new_expr.leaves[index] = flatten(leaf) if hasattr(expr, 'options'): new_expr.options = expr.options return new_expr result = flatten(result) if return_list: result_list.append(result) # count += 1 if max_list is not None and len(result_list) >= max_list: # return result_list raise StopGenerator_BaseRule(result_list) else: raise StopGenerator_BaseRule(result) # only first possibility counts try: self.pattern.match( yield_match, expression, {}, evaluation, fully=fully) except StopGenerator_BaseRule as exc: return exc.value if return_list: return result_list else: return None def get_sort_key(self): return (self.system, self.pattern.get_sort_key(True)) class Rule(BaseRule): def __init__(self, pattern, replace, system=False): super(Rule, self).__init__(pattern, system=system) self.replace = replace def do_replace(self, vars, options, evaluation): new = self.replace.replace_vars(vars) new.options = options # if options is a non-empty dict, we need to ensure reevaluation of the whole expression, since 'new' will # usually contain one or more matching OptionValue[symbol_] patterns that need to get replaced with the # options' values. this is achieved through Expression.evaluate(), which then triggers OptionValue.apply, # which in turn consults evaluation.options to return an option value. # in order to get there, our expression 'new' (or parts of it) must not have is_evaluated True, since this # would make Expression.evaluate() quit early. doing a clean deep copy here, will reset # Expression.is_evaluated for all nodes in the tree. # if the expression contains OptionValue[] patterns, but options is empty here, we don't need to act, as the # expression won't change in that case. the Expression.options would be None anyway, so OptionValue.apply # would just return the unchanged expression (which is what we have already). if options: new = new.copy() return new def __repr__(self): return '<Rule: %s -> %s>' % (self.pattern, self.replace) class BuiltinRule(BaseRule): def __init__(self, pattern, function, system=False): super(BuiltinRule, self).__init__(pattern, system=system) self.function = function def do_replace(self, vars, options, evaluation): # The Python function implementing this builtin expects # argument names corresponding to the symbol names without # context marks. vars_noctx = dict(((strip_context(s), vars[s]) for s in vars)) if options: return self.function( evaluation=evaluation, options=options, **vars_noctx) else: return self.function(evaluation=evaluation, **vars_noctx) def __repr__(self): return '<BuiltinRule: %s -> %s>' % (self.pattern, self.function) def __getstate__(self): odict = self.__dict__.copy() del odict['function'] odict['function_'] = ( self.function.__self__.get_name(), self.function.__name__) return odict def __setstate__(self, dict): from mathics.builtin import builtins self.__dict__.update(dict) # update attributes cls, name = dict['function_'] self.function = getattr(builtins[cls], name)
"""Hackerrank Problem: https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem You are given N mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx The given mobile numbers may have +91, 91 or 0 written before the actual 10 digit number. Alternatively, there may not be any prefix at all. """ def wrapper(f): def fun(l): f('+91 {0} {1}'.format(n[-10:-5], n[-5:]) for n in l) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l = [input() for _ in range(int(input()))] sort_phone(l)
import sys from datapackage import Package from ..helpers.extended_json import ejson def unstream(file=sys.stdin): if isinstance(file, str): file = open(file) def read(): line = file.readline().strip() if len(line) > 0: return ejson.loads(line) return None def res_reader(): while True: r = read() if r is not None: yield r else: break def func(package): descriptor = read() yield Package(descriptor) for _ in descriptor['resources']: yield res_reader() return func
from gyomu.db_connection_factory import DbConnectionFactory, GYOMU_COMMON_MAINDB_CONNECTION from gyomu.gyomu_db_model import * import os from gyomu.user_factory import UserFactory from gyomu.user import User from gyomu.gyomu_db_access import GyomuAppsInfoCdtblAccess TEST_APPLICATION_ID2 = 32651 TEST_APPLICAIONT_ID_AMEND=32652 def test_insert_app_info(environment_setup): app = GyomuAppsInfoCdtblAccess.get(TEST_APPLICATION_ID2) if app is not None: GyomuAppsInfoCdtblAccess.delete(app) original_apps_count = len(GyomuAppsInfoCdtblAccess.get_all()) app = GyomuAppsInfoCdtbl() app.application_id = TEST_APPLICATION_ID2 app.description = "Test Application" user: User = UserFactory.get_current_user() app.mail_from_name = user.userid app.mail_from_address = "Test@test.com" GyomuAppsInfoCdtblAccess.add(app) new_apps_count = len(GyomuAppsInfoCdtblAccess.get_all()) assert new_apps_count == (original_apps_count+1) app = GyomuAppsInfoCdtblAccess.get(TEST_APPLICATION_ID2) amend_description="Test2 Application" app.description=amend_description amend_mail_name='dummy' app.mail_from_name=amend_mail_name amend_mail_address='Test2@test.com' app.mail_from_address = amend_mail_address GyomuAppsInfoCdtblAccess.update(app) app = GyomuAppsInfoCdtblAccess.get(TEST_APPLICATION_ID2) assert app.description == amend_description assert app.mail_from_name==amend_mail_name assert app.mail_from_address == amend_mail_address app.application_id= TEST_APPLICAIONT_ID_AMEND GyomuAppsInfoCdtblAccess.update(app, original_application_id=TEST_APPLICATION_ID2) app = GyomuAppsInfoCdtblAccess.get(TEST_APPLICATION_ID2) assert app is None app = GyomuAppsInfoCdtblAccess.get(TEST_APPLICAIONT_ID_AMEND) assert app.application_id == TEST_APPLICAIONT_ID_AMEND GyomuAppsInfoCdtblAccess.delete(app)
import re file = open('./input', 'r') lines = file.readlines() width = len(lines[0]) - 1 count = 0 j = 0 for i in range(len(lines)): if lines[i][j] == '#': count += 1 j = (j + 3) % width print(count)
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ def check(i, j): if i > -1 and j > -1 and i < len(grid) and j < len(grid[0]): return True return False def containsOne(i, j): if check(i, j): if grid[i][j] == 1: return 1 return 0 p = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: p += 4 p -= containsOne(i - 1, j) + containsOne(i, j - 1) + containsOne(i + 1, j) + containsOne(i, j + 1) return p
# pyright: strict from typing import Optional from discord.enums import ButtonStyle from discord.interactions import Interaction from discord.ui.button import button from discord.ui.view import View from discord.embeds import Embed class Paginator(View): def __init__( self, executor_id: int, embeds: list[Embed], timeout: Optional[float] = 60 ): super().__init__(timeout=timeout) self.embeds = embeds self.executor_id = executor_id self.index = 0 @property def total(self): return len(self.embeds) async def interaction_check(self, interaction: Interaction) -> bool: if user := interaction.user: if user.id == self.executor_id: return True await interaction.response.send_message( "명령어 실행자만 상호작용이 가능합니다.", ephemeral=True ) return False @button(label="다음", style=ButtonStyle.primary, emoji="▶️") async def next_page(self, _, interaction: Interaction): self.index += 1 if self.index >= self.total: self.index = 0 await interaction.response.edit_message(embed=self.embeds[self.index]) @button(label="이전", style=ButtonStyle.primary, emoji="◀") async def prev_page(self, _, interaction: Interaction): self.index -= 1 if self.index < 0: self.index = self.total - 1 await interaction.response.edit_message(embed=self.embeds[self.index]) @button(label="닫기", style=ButtonStyle.danger, emoji="❌") async def close(self, _, interaction: Interaction): if message := interaction.message: self.stop() await message.delete()
from tkinter import* from Crnobelo import* import logging import random import threading # V slovar spravimo seznam sosedov vsakega polja. SLOVAR_SOSEDOV = {} #Vrne nasprotnika def nasprotnik(igralec): if igralec == BELI: return CRNI elif igralec == CRNI: return BELI else: assert False, "neveljaven nasprotnik" ##################################################################### ## Racunalnik class Racunalnik(): def __init__(self, Crnobelo, algoritem): self.Crnobelo = Crnobelo self.algoritem = algoritem # Algoritem, ki izracuna potezo self.mislec = None # Vlakno (thread), ki razmislja def igraj(self): """Igraj potezo, ki jo vrne algoritem.""" # Tu sprozimo vzporedno vlakno, ki racuna potezo. Ker tkinter ne deluje, # ce vzporedno vlakno direktno uporablja tkinter (glej http://effbot.org/zone/tkinter-threads.htm), # zadeve organiziramo takole: # - pozenemo vlakno, ki poisce potezo # - to vlakno nekam zapise potezo, ki jo je naslo # - glavno vlakno, ki sme uporabljati tkinter, vsakih 100ms pogleda, ali # je ze bila najdena poteza (metoda preveri_potezo spodaj). # Ta resitev je precej amaterska. Z resno knjiznico za GUI bi zadeve lahko # naredili bolje (vlakno bi samo sporocilo GUI-ju, da je treba narediti potezo). # Naredimo vlakno, ki mu podamo *kopijo* igre (da ne bo zmedel GUIja): # logging.debug("Velikost: {0}".format(self.Crnobelo.igra.kopija())) self.Crnobelo.napis.set("Razmisljam.") self.mislec = threading.Thread( target=lambda: self.algoritem.izracunaj_potezo(self.Crnobelo.igra.kopija())) # Pozenemo vlakno: self.mislec.start() # Gremo preverjati, ali je bila najdena poteza: self.Crnobelo.canvas.after(100, self.preveri_potezo) # Funkicja, ki preveri, ce je algoritem izracunal potezo. def preveri_potezo(self): """Vsakih 100ms preveri, ali je algoritem ze izracunal potezo.""" if self.algoritem.poteza is not None: # Algoritem je nasel potezo, povleci jo, ce ni bilo prekinitve self.Crnobelo.izberi(self.algoritem.poteza) logging.debug("{0}".format(self.Crnobelo.igra.zgodovina)) logging.debug("{0}".format(self.Crnobelo.igra.matrika)) # Vzporedno vlakno ni vec aktivno, zato ga "pozabimo" self.mislec = None else: # Algoritem se ni nasel poteze, preveri se enkrat cez 100ms self.Crnobelo.canvas.after(100, self.preveri_potezo) # To metodo klice GUI, ce je treba prekiniti razmisljanje. def prekini(self): if self.mislec: logging.debug ("Prekinjamo {0}".format(self.mislec)) # Algoritmu sporocimo, da mora nehati z razmisljanjem self.algoritem.prekini() # Pocakamo, da se vlakno ustavi self.mislec.join() self.mislec = None def klik(self, p): # Racunalnik ignorira klike pass ###################################################################### ## Algoritem minimax class Minimax(): def __init__(self, globinaM): self.prekiitev = False self.igra = None self.jaz = None self.poteza = None self.globina = globinaM # Določimo vrednosti polj in zmage. ZMAGA = 10000 VREDNOST_1 = ZMAGA//20 VREDNOST_2 = ZMAGA//200 VREDNOST_3 = ZMAGA//2000 VREDNOST_4 = 0 NESKONCNO = 2*ZMAGA + 1 # Funkcija, ki prekine. def prekini(self): self.prekinitev = True # Izracuna vrednost pozicije. def vrednost_pozicije(self): ocena = 0 # Oceni pristejemo vrednost vsakega polja. for i in self.igra.veljavne_poteze(): ocena += self.tip_polja(i) self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) # Oceni odstejemo dvakratno vrednost vsakega polja nasprotnika.(Bolj napadalna igra.) for i in self.igra.veljavne_poteze(): ocena -= 2*self.tip_polja(i) self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) if self.globina % 2 == 1: ocena = -ocena return ocena # Funkcija, ki izracuna potezo. def izracunaj_potezo(self, igra): logging.debug("Igra minimax") self.igra = igra self.prekinitev = False self.jaz = self.igra.na_vrsti self.poteza = None (poteza, vrednost) = self.minimax(self.globina + (self.igra.st_potez//(self.igra.velikost()//3)), True) self.jaz = None self.igra = None if not self.prekinitev: # Potezo izvedemo v primeru, da nismo bili prekinjeni self.poteza = poteza def minimax(self, globina, maksimiziramo): """Glavna metoda minimax.""" if self.prekinitev: # Sporocili so nam, da moramo prekiniti. logging.debug ("Minimax prekinja, globina = {0}".format(globina)) return (None, 0) if self.igra.je_konec(): if self.igra.na_vrsti == self.jaz: return (None, -Minimax.ZMAGA) elif self.igra.na_vrsti == nasprotnik(self.jaz): return (None, Minimax.ZMAGA) else: assert False, "Napaka v koncu igre v Minimaxu." else: logging.debug("Sm v minimaxu...") if globina == 0: return (None, self.vrednost_pozicije()) else: logging.debug("Globina ni 0...") # Naredimo eno stopnjo minimax if maksimiziramo: logging.debug("Je maksimiziramo...") # Maksimiziramo najboljsa_poteza = None vrednost_najboljse = -Minimax.NESKONCNO logging.debug("{0}".format(self.igra.veljavne_poteze())) for p in self.igra.veljavne_poteze(): logging.debug("Sem v for zanki...") self.igra.povleci_potezo(p) vrednost = self.minimax(globina-1, not maksimiziramo)[1] logging.debug("Zdaj bom razveljavil...") logging.debug("{0}".format(self.igra.zgodovina)) self.igra.razveljavi() if vrednost > vrednost_najboljse: vrednost_najboljse = vrednost najboljsa_poteza = p else: logging.debug("Ni maksimiziramo...") # Minimiziramo najboljsa_poteza = None vrednost_najboljse = Minimax.NESKONCNO logging.debug("{0}".format(self.igra.veljavne_poteze())) for p in self.igra.veljavne_poteze(): self.igra.povleci_potezo(p) vrednost = self.minimax(globina-1, not maksimiziramo)[1] logging.debug("Zdaj bom razveljavil...") logging.debug("{0}".format(self.igra.zgodovina)) self.igra.razveljavi() if vrednost < vrednost_najboljse: vrednost_najboljse = vrednost najboljsa_poteza = p assert (najboljsa_poteza is not None), "minimax: izracunana poteza je None" return (najboljsa_poteza, vrednost_najboljse) # Ustvari seznam sosedov polja xy. def sez_sosedov(self, xy): if xy in SLOVAR_SOSEDOV: return SLOVAR_SOSEDOV[xy] else: x, y = xy sez = [] sez_polj = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] for (i, j) in sez_polj: if i >= 0 and j >= 0 and self.igra.velikost() > i and self.igra.velikost() > j: sez.append((i,j)) SLOVAR_SOSEDOV[xy] = sez return sez #Funkcija vrne vrednost polja def tip_polja(self, xy): sosedi = self.sez_sosedov(xy) a = self.igra.veljavne_poteze() self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) b = self.igra.veljavne_poteze() self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) c = True for i in sosedi: if i in b: c = False break #Polje tipa 1. Polje smo zavzeli mi. if xy in a and xy not in b and c: return Minimax.VREDNOST_1 #Polje nam lahko odzame. elif xy in a and xy not in b: return Minimax.VREDNOST_2 #Polje je prosto. elif xy in a and xy in b: return Minimax.VREDNOST_3 #Polje je neveljavno. else: return Minimax.VREDNOST_4 ###################################################################### ## Igralec alfabeta class Alfabeta(): def __init__(self, globinaAB): self.prekinitev = False self.igra = None self.jaz = None self.poteza = None self.globina = globinaAB # Vrednosti polj in zmage. ZMAGA = 10000 VREDNOST_1 = ZMAGA//20 VREDNOST_2 = ZMAGA//200 VREDNOST_3 = ZMAGA//2000 VREDNOST_4 = 0 NESKONCNO = 10*ZMAGA + 1 # Prekinitev igralca def prekini(self): self.prekinitev = True #Izracuna vrednost pozicije def vrednost_pozicije(self): ocena = 0 for i in self.igra.veljavne_poteze(): ocena += self.tip_polja(i) self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) for i in self.igra.veljavne_poteze(): ocena -= 1.2*self.tip_polja(i) self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) if self.globina % 2 == 1: ocena = -ocena return ocena #Izracuna vrednost poteze def izracunaj_potezo(self, igra): logging.debug("Igra minimax") self.igra = igra self.prekinitev = False self.jaz = self.igra.na_vrsti self.poteza = None (poteza, vrednost) = self.alfabeta(self.globina + (self.igra.st_potez//(self.igra.velikost()//3)), -Alfabeta.NESKONCNO, Alfabeta.NESKONCNO, True) self.jaz = None self.igra = None if not self.prekinitev: # Potezo izvedemo v primeru, da nismo bili prekinjeni self.poteza = poteza # Alfabeta def alfabeta(self, globina, a, b, maksimiziramo): """Glavna metoda alfabeta.""" if self.prekinitev: # Sporocili so nam, da moramo prekiniti logging.debug ("Alfabeta prekinja, globina = {0}".format(globina)) return (None, 0) if self.igra.je_konec(): if self.igra.na_vrsti == self.jaz: return (None, -Alfabeta.ZMAGA) elif self.igra.na_vrsti == nasprotnik(self.jaz): return (None, Alfabeta.ZMAGA) else: assert False, "Napaka v koncu igre v Alfabeta." else: #logging.debug("Sm v alfabeta...") if globina == 0: return (None, self.vrednost_pozicije()) else: logging.debug("Globina ni 0...") # Naredimo eno stopnjo alfabeta if maksimiziramo: #logging.debug("Je maksimiziramo...") # Maksimiziramo najboljsa_poteza = None vrednost_najboljse = -Alfabeta.NESKONCNO logging.debug("{0}".format(self.igra.veljavne_poteze())) for p in self.igra.veljavne_poteze(): logging.debug("Sem v for zanki...") self.igra.povleci_potezo(p) vrednost = self.alfabeta(globina-1, a, b, not maksimiziramo)[1] logging.debug("Zdaj bom razveljavil...") logging.debug("{0}".format(self.igra.zgodovina)) self.igra.razveljavi() if vrednost > vrednost_najboljse: vrednost_najboljse = vrednost najboljsa_poteza = p a = max(a, vrednost_najboljse) if b <= a: break else: logging.debug("Ni maksimiziramo...") # Minimiziramo najboljsa_poteza = None vrednost_najboljse = Alfabeta.NESKONCNO logging.debug("{0}".format(self.igra.veljavne_poteze())) for p in self.igra.veljavne_poteze(): self.igra.povleci_potezo(p) vrednost = self.alfabeta(globina-1, a, b, not maksimiziramo)[1] logging.debug("Zdaj bom razveljavil...") logging.debug("{0}".format(self.igra.zgodovina)) self.igra.razveljavi() if vrednost < vrednost_najboljse: vrednost_najboljse = vrednost najboljsa_poteza = p b = min(b, vrednost_najboljse) if b <= a: break assert (najboljsa_poteza is not None), "alfabeta: izracunana poteza je None" return (najboljsa_poteza, vrednost_najboljse) # Ustvari seznam sosedov polja xy. def sez_sosedov(self, xy): if xy in SLOVAR_SOSEDOV: return SLOVAR_SOSEDOV[xy] else: x, y = xy sez = [] sez_polj = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] for (i, j) in sez_polj: if i >= 0 and j >= 0 and self.igra.velikost() > i and self.igra.velikost() > j: sez.append((i,j)) SLOVAR_SOSEDOV[xy] = sez return sez # Funkcija vrne vrednost polja. def tip_polja(self, xy): sosedi = self.sez_sosedov(xy) a = self.igra.veljavne_poteze() self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) b = self.igra.veljavne_poteze() self.igra.na_vrsti = nasprotnik(self.igra.na_vrsti) c = True for i in sosedi: if i in b: c = False break #Polje tipa 1. Polje smo zavzeli mi. if xy in a and xy not in b and c: return Alfabeta.VREDNOST_1 * (self.igra.VREDNOST_POLJ[xy]) #Polje nam lahko odzame. elif xy in a and xy not in b: return Alfabeta.VREDNOST_2 * (self.igra.VREDNOST_POLJ[xy]) #Polje je prosto. elif xy in a and xy in b: return Alfabeta.VREDNOST_3 * (self.igra.VREDNOST_POLJ[xy]) #Polje je neveljavno. else: return Alfabeta.VREDNOST_4 ##################################################################### ## Igralec naklucje # Razred za igralca, ki igra nakljucne dovoljene poteze. class Nakljucje(): def __init__(self): self.prekiitev = False self.igra = None self.jaz = None self.poteza = None # Funkcija, ki prekine igralca. def prekini(self): self.prekinitev = True # Funkcija, ki oceni pozicijo. def vrednost_pozicije(self): # Nakljucni igralec ne ocenjuje pozicij, igra nakljucno. pass # Funkcija, ki izracuna potezo. def izracunaj_potezo(self, igra): logging.debug("Igra random") self.igra = igra self.prekinitev = False self.jaz = self.igra.na_vrsti self.poteza = None poteza = self.nakljucje(igra) if not self.prekinitev: # Potezo izvedemo v primeru, da nismo bili prekinjeni self.poteza = poteza # Vrne nakljucno veljavno potezo def nakljucje(self, igra): do_kdaj = False while not do_kdaj: x = random.randint(0, (self.igra.velikost()) - 1) y = random.randint(0, (self.igra.velikost()) - 1) logging.debug("{0},{1}".format(x,y)) do_kdaj = self.igra.dovoljeno(x,y) return (x,y) ###################################################################### ## Igralec clovek class Clovek(): def __init__(self, Crnobelo): self.Crnobelo = Crnobelo def igraj(self): # Smo na potezi. Zaenkrat ne naredimo nic, ampak # cakamo, da bo uporanik kliknil na plosco. Ko se # bo to zgodilo, nas bo Gui obvestil preko metode # klik. #Pobarvaj mozne poteze. self.Crnobelo.pobarvaj_poteze() logging.debug("Igra clovek") logging.debug("{0}".format(self.Crnobelo.igra.matrika)) pass def prekini(self): # To metodo klice GUI, ce je treba prekiniti razmisljanje. # Clovek jo lahko ignorira. pass def klik(self, event): velikost = self.Crnobelo.velikost #Izbrisemo namig, ce je vklopljen self.Crnobelo.canvas.delete(Crnobelo.TAG_NAMIG) # Povlecemo potezo. Ce ni veljavna, se ne bo zgodilo nic. x, y = (event.x -50) // (100*6/(velikost)), (event.y -50) // (100*6/(velikost)) if x >= 0 and y >= 0 and x < self.Crnobelo.velikost and y <self.Crnobelo.velikost: #Ko kliknemo se mozne poteze zbrisejo. self.Crnobelo.pobrisi_poteze() self.Crnobelo.izberi((int(x),int(y)))
import asyncio import datetime import re import aiohttp from babel.dates import format_datetime from bs4 import BeautifulSoup, SoupStrainer from core.exceptions import LoginError from core.utils import get_beautiful_soup_parser, safe_path_join from settings.config import ConfigString from sites.ilias import login from sites.ilias.constants import GOTO_URL from sites.utils import remove_vz_id ILIAS_ID_CONFIG = ConfigString(gui_name="ID") async def get_folder_name(session, ilias_id, **kwargs): url = GOTO_URL + str(ilias_id) async with session.get(url) as response: html = await response.text() soup = BeautifulSoup(html, get_beautiful_soup_parser()) ol = soup.find("ol", class_="breadcrumb") name = str(ol.find_all("li")[2].string) return remove_vz_id(name) async def producer(session, queue, base_path, download_settings, ilias_id: ILIAS_ID_CONFIG): await search_tree(session, queue, base_path, download_settings, ilias_id) async def search_tree(session, queue, base_path, download_settings, ilias_id): url = GOTO_URL + str(ilias_id) async with session.get(url) as response: html = await response.text() if str(response.url) != url: raise LoginError("Module ilias isn't logged in or you are not allowed to access these files") strainer = SoupStrainer("div", attrs={"class": "ilCLI ilObjListRow row"}) soup = BeautifulSoup(html, get_beautiful_soup_parser(), parse_only=strainer) rows = soup.find_all("div", attrs={"class": "ilCLI ilObjListRow row"}) tasks = [] for row in rows: content = row.find("div", attrs={"class": "ilContainerListItemContent"}) link = content.find("a") href = link["href"] name = str(link.string) path = safe_path_join(base_path, name) if "download" in href: extension = str(content.find("span", attrs={"class": "il_ItemProperty"}).string).strip() checksum = "".join([str(x.string).strip() for x in content.find_all("span", attrs={"class": "il_ItemProperty"})]) if "Today" in checksum: today_date = datetime.datetime.now() checksum = checksum.replace("Today", format_datetime(today_date, locale='en', format="dd. MMM YYYY")) elif "Yesterday" in checksum: yesterday_date = datetime.datetime.now() - datetime.timedelta(days=1) checksum = checksum.replace("Yesterday", format_datetime(yesterday_date, locale='en', format="dd. MMM YYYY")) await queue.put({"url": href, "path": f"{path}.{extension}", "checksum": checksum}) else: ref_id = re.search("ref_id=([0-9]+)&", href).group(1) coroutine = search_tree(session, queue, path, download_settings, ref_id) tasks.append(asyncio.ensure_future(coroutine)) await asyncio.gather(*tasks) if __name__ == "__main__": async def main(): async with aiohttp.ClientSession(raise_for_status=True) as session: await login(session) await get_folder_name(session, "187834") loop = asyncio.get_event_loop() loop.run_until_complete(main())
import hyperion, time, datetime import math n=hyperion.ledCount u=18 v=11 maxIntensity=128 a=[] # # 0 x x x # x # x # 0 x x x def ledDirs(): pos=[] for i in range(hyperion.ledCount): l=i%(u+v) if l < u: x,y=l+1,0 else: x,y=u+1,l-u +1 if i>= u+v: x,y=1+u-x,1+v-y x,y=x,-y x-=(u+1)/2.0 y+=(v+1)/2.0 phi=math.atan2(x,y) if phi<0: phi+=2*math.pi phi/=2*math.pi #pos+=[[x,y]] pos+=[phi] return pos pos=ledDirs() def ringDist(a,b): if a>b: return ringDist(b,a) # a<b return min(b-a,a+1-b) def dist2intensity(v,scale): return int(((1-v)**40) *scale* maxIntensity) # effect loop while not hyperion.abort(): now = datetime.datetime.now() c = (now.second + now.microsecond/1e6) / 60.0 b = (now.minute + c) / 60.0 a = ((now.hour % 12) + b ) / 12.0 led_data = bytearray() #print a for i in range(hyperion.ledCount): #off=(i/1.0/hyperion.ledCount+0/8.0)%1.0 off=pos[i] dC = ringDist(off,c) dB = ringDist(off,b) dA = ringDist(off,a) # print off # print dA led_data += bytearray(( dist2intensity(dC,.3),dist2intensity(dB,.6),dist2intensity(dA,1) )) #led_data += bytearray(( dist2intensity(dC),int(0),int(0) )) #led_data += bytearray(( int((i*now.second)%255),int((i*now.second)%255),int((i*now.second)%255))) #bFill(led_data,hyperion.ledCount,c,0) hyperion.setColor(led_data) hyperion.setColor(led_data) time.sleep(0.1)
#!/usr/bin/env python # coding: utf-8 # In[30]: import pandas as pd import matplotlib as plt import numpy as np import seaborn as sb from sklearn.ensemble import RandomForestClassifier # In[11]: #loading data df=pd.read_csv('social.csv') # In[12]: # meta data of pandas df.info() # In[13]: df['Age'] # In[14]: # installing seaborn get_ipython().system('sudo pip3 install seaborn') # In[15]: import seaborn as sb # In[16]: df.head() # In[18]: sb.countplot(df['Purchased']) # In[19]: # age count sb.countplot(df['Age']) # In[20]: sb.countplot(df['Gender']) # In[21]: # features and labels f=df.iloc[:,2:4].values l=df.iloc[:,-1].values # In[26]: # training and testing from sklearn.model_selection import train_test_split train_x,test_x,train_y,test_y=train_test_split(f,l,test_size=0.2,random_state=0) # In[27]: from sklearn.preprocessing import StandardScaler sc=StandardScaler() # In[28]: train_x=sc.fit_transform(train_x) # In[31]: test_x=sc.transform(test_x) # In[32]: # n_estimator=twenty trees (by default 10 trees) clf=RandomForestClassifier(n_estimators=20,criterion='entropy') # In[33]: trained=clf.fit(train_x,train_y) # In[34]: trained.predict(test_x) # In[ ]:
from setuptools import setup with open('README.md', 'r') as fh: long_description = fh.read() setup(name='pyinquirer_menu', version='0.1', author='Gerrie Crafford', description='Package that allows easy multi-level menu creation using PyInquirer', long_description=long_description, long_description_content_type='text/markdown', install_requires=[ 'PyInquirer==1.0.3', ], )
# Curso Python 13 # ---Desafio 52--- # Faça um programa que leia um número inteiro # e diga se ele é ou não um número primo. n = int(input('Digite um número: ')) s = int(0) for c in range(1, n + 1): a = n / c b = int(a) if n / c != 1 or n / c != n: if a == b: # Se a divisão entre a e c for inteira s += 1 # conta quantas divisões inteiras existem if s > 2: print(f'{n} tem {s} divisores, ele \033[31mnão é primo\033[m') else: print(f'{n} só pode ser dividido por 1 ou ele mesmo, ele \033[32mé primo\033[m')
""" The :mod:`sklearnext.preprocessing.data` includes utilities to select features and sample the input matrix. """ # Author: Georgios Douzas <gdouzas@icloud.com> # License: BSD 3 clause import warnings import numpy as np from sklearn.utils import indices_to_mask from sklearn.utils.validation import check_is_fitted, check_X_y, check_array, check_random_state from sklearn.feature_selection.univariate_selection import _BaseFilter from imblearn.base import SamplerMixin from imblearn.utils import hash_X_y def _generate_zero_scores(X, y): """Return an array of zero scores.""" return np.zeros((1, X.shape[1])) class FeatureSelector(_BaseFilter): """Select features according to an array of indices. Parameters ---------- indices : array-like, shape = [n_features] The selected features. """ def __init__(self, indices=None): super(FeatureSelector, self).__init__(_generate_zero_scores) self.indices = indices def _check_params(self, X, y): self.num_features_ = X.shape[1] if self.indices is not None: self.indices_ = check_array(self.indices, ensure_2d=False) else: self.indices_ = np.arange(0, self.num_features_) if not set(np.arange(self.num_features_)).issuperset(set(self.indices_)): raise ValueError("Parameter indices should be an array of any index of the features; Got %r." % self.indices) def _get_support_mask(self): check_is_fitted(self, 'scores_') mask = indices_to_mask(self.indices_, self.num_features_) return mask class RowSelector(SamplerMixin): """Select rows according to a defined percentage. Parameters ---------- percentage : float, optional (default=None) The ratio of samples to keep. The values should be in the [0.0, 1.0] range. random_state : str, int, RandomState instance or None, optional (default=None) If str, valid choices are 'head' or 'tail' where the first or last samples are used respectively. 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``. """ def __init__(self, ratio=None, random_state=None): self.ratio = ratio self.random_state = random_state def fit(self, X, y=None): """Save the initial input matrix and the number of samples to be removed. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Matrix containing the data which have to be sampled. y : array-like, shape (n_samples,) Corresponding label for each sample in X. Returns ------- self : object, Return self. """ X, y = check_X_y(X, y, accept_sparse=['csr', 'csc']) if self.ratio is not None and self.ratio != 1.0: self.ratio_ = self.ratio self.n_samples_ = int(self.ratio_ * len(X)) else: self.ratio_ = None self.X_hash_, self.y_hash_ = hash_X_y(X, y) return self def _sample(self, X, y): """Remove samples from input matrix. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Matrix containing the data which have to be sampled. y : array-like, shape (n_samples,) Corresponding label for each sample in X. Returns ------- X_resampled : {ndarray, sparse matrix}, shape (n_samples_new, n_features) The array containing the resampled data. y_resampled : ndarray, shape (n_samples_new,) The corresponding rows of `X_resampled` """ if self.ratio_ is None: return X.copy(), y.copy() if self.random_state == 'head': X_resampled = X[:self.n_samples_].copy() y_resampled = y[:self.n_samples_].copy() elif self.random_state == 'tail': X_resampled = X[-self.n_samples_:].copy() y_resampled = y[-self.n_samples_:].copy() else: indices = check_random_state(self.random_state).randint(0, len(X), self.n_samples_) X_resampled = X[indices].copy() y_resampled = y[indices].copy() return X_resampled, y_resampled
import argparse parser = argparse.ArgumentParser() parser.add_argument("--pdb", help="pdb file name output from idealize",required=True) parser.add_argument("--map", help="map file name ",required=True) parser.add_argument("--rms", help="rms to sample ",default=2.0) parser.add_argument("--resolution", help="reported resolution ",required=True, type=float) parser.add_argument("--tasks", help="number of jobs to submit",required=True,type=int) parser.add_argument("--nstruct", help="number of structures to generate per job",required=True,type=int) args = parser.parse_args() pdb_ideal = args.pdb map = args.map rms = args.rms resolution = args.resolution nstruct = args.nstruct tasks = args.tasks ### FROM GABE LANDER: # determine electron density weight # according to Rosetta: # this value should be 10 for 3A, 20-25 for 3.5-4A, and 50-60 for 4.5-5A dens = 5 if resolution > 2.8: dens = int((resolution-2.58)/0.0411) print "\n\n\ndensity weight set to {dens}\n\n\n".format(dens=dens) fout = open("launch_rosetta_refine.sh","w") fout.write("""#!/bin/bash # #$ -S /bin/bash #$ -o ./out #$ -e ./err #$ -cwd #$ -r y #$ -j y #$ -l mem_free=1G #$ -l arch=linux-x64 #$ -l netapp=1G,scratch=1G #$ -l h_rt=80:00:00 #$ -t 1-{tasks} hostname date source /programs/sbgrid.shrc rosetta_scripts.linuxgccrelease -database /netapp/home/jaimefraser/database -in::file::s {pdb} -edensity::mapfile {map} -parser::protocol new_multi_global.xml -edensity::mapreso {resolution} -default_max_cycles 200 -edensity::cryoem_scatterers -out::suffix $SGE_TASK_ID -crystal_refine -beta -parser::script_vars denswt={dens} rms={rms} -nstruct {nstruct} date """.format(pdb=pdb_ideal,map=map,dens=dens,rms=rms,resolution=resolution,tasks=tasks,nstruct=nstruct)) fout.close() fxml = open("new_multi_global.xml","w") fxml.write("""<ROSETTASCRIPTS> <SCOREFXNS> <ScoreFunction name="cen" weights="score4_smooth_cart"> <Reweight scoretype="elec_dens_fast" weight="20" /> </ScoreFunction> <ScoreFunction name="dens_soft" weights="beta_soft"> <Reweight scoretype="cart_bonded" weight="0.5" /> <Reweight scoretype="pro_close" weight="0.0" /> <Reweight scoretype="elec_dens_fast" weight="%%denswt%%" /> </ScoreFunction> <ScoreFunction name="dens" weights="beta_cart"> <Reweight scoretype="elec_dens_fast" weight="%%denswt%%" /> <Set scale_sc_dens_byres="R:0.76,K:0.76,E:0.76,D:0.76,M:0.76, C:0.81,Q:0.81,H:0.81,N:0.81,T:0.81,S:0.81,Y:0.88,W:0.88, A:0.88,F:0.88,P:0.88,I:0.88,L:0.88,V:0.88" /> </ScoreFunction> </SCOREFXNS> <MOVERS> <SetupForDensityScoring name="setupdens" /> <SwitchResidueTypeSetMover name="tocen" set="centroid" /> <MinMover name="cenmin" scorefxn="cen" type="lbfgs_armijo_nonmonotone" max_iter="200" tolerance="0.00001" bb="1" chi="1" jump="ALL" /> <CartesianSampler name="cen5_50" automode_scorecut="-0.5" scorefxn="cen" mcscorefxn="cen" fascorefxn="dens_soft" strategy="auto" fragbias="density" rms="%%rms%%" ncycles="200" fullatom="0" bbmove="1" nminsteps="25" temp="4" fraglens="7" nfrags="25" /> <CartesianSampler name="cen5_60" automode_scorecut="-0.3" scorefxn="cen" mcscorefxn="cen" fascorefxn="dens_soft" strategy="auto" fragbias="density" rms="%%rms%%" ncycles="200" fullatom="0" bbmove="1" nminsteps="25" temp="4" fraglens="7" nfrags="25" /> <CartesianSampler name="cen5_70" automode_scorecut="-0.1" scorefxn="cen" mcscorefxn="cen" fascorefxn="dens_soft" strategy="auto" fragbias="density" rms="%%rms%%" ncycles="200" fullatom="0" bbmove="1" nminsteps="25" temp="4" fraglens="7" nfrags="25" /> <CartesianSampler name="cen5_80" automode_scorecut="0.0" scorefxn="cen" mcscorefxn="cen" fascorefxn="dens_soft" strategy="auto" fragbias="density" rms="%%rms%%" ncycles="200" fullatom="0" bbmove="1" nminsteps="25" temp="4" fraglens="7" nfrags="25" /> <BfactorFitting name="fit_bs" max_iter="50" wt_adp="0.0005" init="1" exact="1" /> <FastRelax name="relaxcart" scorefxn="dens" repeats="1" cartesian="1" /> </MOVERS> <PROTOCOLS> <Add mover="setupdens" /> <Add mover="tocen" /> <Add mover="cenmin" /> <Add mover="relaxcart" /> <Add mover="cen5_50" /> <Add mover="relaxcart" /> <Add mover="cen5_60" /> <Add mover="relaxcart" /> <Add mover="cen5_70" /> <Add mover="relaxcart" /> <Add mover="cen5_80" /> <Add mover="relaxcart" /> <Add mover="relaxcart" /> </PROTOCOLS> <OUTPUT scorefxn="dens" /> </ROSETTASCRIPTS> """) fxml.close() import os os.system("qsub launch_rosetta_refine.sh")
from .bot_interface import BotInterface from discord.activity import Activity from discord.enums import ActivityType, Status from discord.user import User from holobot.sdk.logging import LogInterface from typing import Optional import discord.ext.commands as commands class Bot(commands.Bot, BotInterface): def __init__(self, log: LogInterface, *args, **kwargs): super().__init__(*args, **kwargs) self.__log: LogInterface = log.with_name("Discord", "Bot") async def set_status_text(self, type: ActivityType, text: str, status: Status = None): await self.change_presence( activity=Activity(name=text, type=type), status=status ) def get_user_by_id(self, user_id: int) -> Optional[User]: user = self.get_user(user_id) if user is None or not isinstance(user, User): return None return user
import numpy as np import scipy.misc def read_consistency_file(path): with open(path) as f: lines = f.readlines() width, height = [int(i) for i in lines[0].split(' ')] values = np.zeros((height, width), dtype=np.float32) for i in range(0, len(lines) - 1): line = lines[i + 1].rstrip().split(' ') consistency_values = np.array([np.float32(j) for j in line]) def convert(value): return value values[i] = list(map(convert, consistency_values)) # expand to 3 channels weights = np.dstack([values.astype(np.float32)] * 3) return weights def save_flow(flow, output_path): scipy.misc.imsave(output_path, flow) if __name__ == '__main__': forward = read_consistency_file('input_frame00001_input_frame00002_forward_reliable.txt') backward = read_consistency_file('input_frame00001_input_frame00002_backward_reliable.txt') save_flow(forward, 'forward.jpg') save_flow(backward, 'backward.jpg')
# -*- coding: utf-8 -*- """ Created on Fri Aug 3 15:28:28 2018 @author: MichaelEK """ import numpy as np import pandas as pd import geopandas as gpd from gistools import vector, util from gistools import data_io pd.options.display.max_columns = 10 #################################### ### Parameters stream_depletion_csv = '/media/sdb1/Projects/git/tethys/tethys-extraction-es-hilltop/permits/es_stream_depletion_ratios.csv' ####################################### ### Tests def test_sel_sites_poly(): pts1 = vector.sel_sites_poly(sites_shp_path, rec_catch_shp_path, buffer_dis=10) assert (len(pts1) == 2) & isinstance(pts1, gpd.GeoDataFrame)
import math import numpy as np import torch import torch.nn as nn from tqdm import tqdm def init_weight(linear_module): stdv = 1. / math.sqrt(linear_module.weight.size(1)) linear_module.weight.data.uniform_(-stdv, stdv) if linear_module.bias is not None: linear_module.bias.data.uniform_(-stdv, stdv) class UserEncoder(nn.Module): def __init__(self, layer_sizes, n_movies, f): """ :param layer_sizes: list giving the size of each layer :param n_movies: :param f: """ super(UserEncoder, self).__init__() self.layers = nn.ModuleList([nn.Linear(in_features=n_movies, out_features=layer_sizes[0]) if i == 0 else nn.Linear(in_features=layer_sizes[i - 1], out_features=layer_sizes[i]) for i in range(len(layer_sizes))]) if f == 'identity': self.f = lambda x: x elif f == 'sigmoid': self.f = nn.Sigmoid() elif f == 'relu': self.f = nn.ReLU() else: raise ValueError("Got invalid function name for f : {}".format(f)) def forward(self, input, raw_last_layer=False): for (i, layer) in enumerate(self.layers): if raw_last_layer and i == len(self.layers) - 1: # do not apply activation to last layer input = layer(input) else: input = self.f(layer(input)) return input class AutoRec(nn.Module): """ User-based Autoencoder for Collaborative Filtering """ def __init__(self, n_movies, params, resume=None): super(AutoRec, self).__init__() self.params = params self.cuda_available = torch.cuda.is_available() self.n_movies = n_movies self.layer_sizes = params['layer_sizes'] if params['g'] == 'identity': self.g = lambda x: x elif params['g'] == 'sigmoid': self.g = nn.Sigmoid() elif params['g'] == 'relu': self.g = nn.ReLU() else: raise ValueError("Got invalid function name for g : {}".format(params['g'])) if resume is not None: # Load pretrained model, keeping only the first n_movies. (see merge_indexes function in match_movies) if self.cuda_available: checkpoint = torch.load(resume) else: checkpoint = torch.load(resume, map_location=lambda storage, loc: storage) # get layer sizes from checkpoint if saved if "layer_sizes" in checkpoint: self.layer_sizes = checkpoint["layer_sizes"] self.encoder = UserEncoder(layer_sizes=self.layer_sizes, n_movies=n_movies, f=params['f']) self.user_representation_size = self.layer_sizes[-1] self.decoder = nn.Linear(in_features=self.user_representation_size, out_features=n_movies) model_dict = self.state_dict() # load all weights except for the weights of the first layer and the decoder model_dict.update({k: v for k, v in checkpoint['state_dict'].items() if k != "encoder.layers.0.weight" and "decoder" not in k}) # load first layer and decoder: assume the movies to keep are the n_movies first movies encoder0weight = checkpoint["state_dict"]["encoder.layers.0.weight"][:, :self.n_movies] decoderweight = checkpoint["state_dict"]["decoder.weight"][:self.n_movies, :] decoderbias = checkpoint["state_dict"]["decoder.bias"][:self.n_movies] # If checkpoint has fewer movies than the model, append zeros (no actual recommendations for new movies) # (When using an updated movie list) if encoder0weight.shape[1] < self.n_movies: tt = torch.cuda.FloatTensor if self.cuda_available else torch.FloatTensor encoder0weight = torch.cat(( encoder0weight, torch.zeros(encoder0weight.shape[0], self.n_movies - encoder0weight.shape[1], out=tt())), dim=1) decoderweight = torch.cat(( decoderweight, torch.zeros(self.n_movies - decoderweight.shape[0], decoderweight.shape[1], out=tt())), dim=0) decoderbias = torch.cat(( decoderbias, torch.zeros(self.n_movies - decoderbias.shape[0], out=tt())), dim=0) model_dict.update({ "encoder.layers.0.weight": encoder0weight, "decoder.weight": decoderweight, "decoder.bias": decoderbias, }) self.load_state_dict(model_dict) else: self.encoder = UserEncoder(layer_sizes=self.layer_sizes, n_movies=n_movies, f=params['f']) self.user_representation_size = self.layer_sizes[-1] self.decoder = nn.Linear(in_features=self.user_representation_size, out_features=n_movies) if self.cuda_available: self.cuda() def forward(self, input, additional_context=None, range01=True): """ :param input: (batch, n_movies) :param additional_context: potential information to add to user representation (batch, user_rep_size) :param range01: If true, apply sigmoid to the output :return: output recommendations (batch, n_movies) """ # get user representation encoded = self.encoder(input, raw_last_layer=True) # eventually use additional context if additional_context is not None: encoded = self.encoder.f(encoded + additional_context) else: encoded = self.encoder.f(encoded) # decode to get movie recommendations if range01: return self.g(self.decoder(encoded)) else: return self.decoder(encoded) def evaluate(self, batch_loader, criterion, subset, batch_input): """ Evaluate function :param batch_loader: :param criterion: :param batch_input: :param subset: in {"test", "valid", "train"}. Susbet on which to evaluate :return: the mean loss. """ self.eval() batch_loader.batch_index[subset] = 0 n_batches = batch_loader.n_batches[subset] losses = [] for _ in tqdm(range(n_batches)): # load batch batch = batch_loader.load_batch(subset=subset, batch_input=batch_input) if self.cuda_available: batch["input"] = batch["input"].cuda() batch["target"] = batch["target"].cuda() # compute output and loss output = self.forward(batch["input"]) loss = criterion(output, batch["target"]) losses.append(loss.item()) # normalize loss and reset nb of ratings observed final_loss = criterion.normalize_loss_reset(np.sum(losses)) print("{} loss with input={} : {}".format(subset, batch_input, final_loss)) self.train() return final_loss class ReconstructionLoss(nn.Module): def __init__(self): super(ReconstructionLoss, self).__init__() # Sum of losses self.mse_loss = nn.MSELoss(size_average=False) # Keep track of number of observer targets to normalize loss self.nb_observed_targets = 0 def forward(self, input, target): # only consider the observed targets mask = (target != -1) observed_input = torch.masked_select(input, mask) observed_target = torch.masked_select(target, mask) # increment nb of observed targets self.nb_observed_targets += len(observed_target) loss = self.mse_loss(observed_input, observed_target) return loss def normalize_loss_reset(self, loss): """ returns loss divided by nb of observed targets, and reset nb_observed_targets to 0 :param loss: Total summed loss :return: mean loss """ if self.nb_observed_targets == 0: raise ValueError( "Nb observed targets was 0. Please evaluate some examples before calling normalize_loss_reset") n_loss = loss / self.nb_observed_targets self.nb_observed_targets = 0 return n_loss
class FrontendPortCurrentSpeed(object): def read_get(self, name, idx_name, unity_client): return unity_client.get_frontend_port_current_speed(idx_name) class FrontendPortCurrentSpeedColumn(object): def get_idx(self, name, idx, unity_client): return unity_client.get_frontend_ports()
import re import networkx as nx from skbio import DNA def extract_node_attrs(node_declaration): """Returns three specific attributes of a FASTG node declaration. As an example, extract_node_attrs("EDGE_3_length_100_cov_28.087'") should return {"name": "3-", "length": 100, "cov": 28.087}. Parameters ---------- node_declaration: str A string tentatively representing a FASTG node declaration (even though it should start with ">EDGE"). We impose some pretty strict criteria on how this declaration can be structured in order to make sure that we get the same amount of information from all nodes in the assembly graph file. Returns ------- dict A mapping of "name", "length", and "cov" to the corresponding corresponding node attributes. The "name" value should be a str, the "length" value should be an int, the "cov" value should be a float, and the "rc" value should be a bool. Raises ------ If the regular expression we use to retrieve information from a node declaration does not match the node_declaration, this will raise a ValueError. """ rc = False if node_declaration.endswith("'"): rc = True node_declaration = node_declaration[0:-1] p = re.compile( r"EDGE_(?P<node>[a-zA-Z\d]+?)_length_(?P<length>\d+?)_cov_(?P<cov>[\d|\.]+)" # noqa ) m = p.search(node_declaration) if m is None: raise ValueError( 'Wasn\'t able to find all info in the node declaration "{}". ' "This assembly graph is likely formatted in a way that pyfastg " "does not support." ) name = m.group("node") if rc: name += "-" else: name += "+" return { "name": name, "length": int(m.group("length")), "cov": float(m.group("cov")), } def check_all_attrs_present( attr_mapping, attrs=("name", "length", "cov", "seq") ): """Given a dict of attributes, ensures that all attrs are keys in the dict. This is used to make sure all nodes in the graph have the information we expect nodes to have. Parameters ---------- attr_mapping: dict A dictionary describing the attributes of a node. attrs: collection All of the required attributes that we expect to be present as keys in attr_mapping. The defaults for this are pretty reasonable. Returns ------- None Raises ------ If any of the entries in "attrs" are not present in attr_mapping, this will raise a ValueError. """ for required_attr in attrs: if required_attr not in attr_mapping: raise ValueError( "{} not present for all nodes".format(required_attr) ) def add_node_to_digraph(digraph, node_attrs): """Adds a node (and potentially some edges) to an existing DiGraph object. Parameters ---------- digraph: networkx.DiGraph An existing graph object, to which a new node and potentially some edges will be added. node_attrs: dict A key/value representation of the attributes the new node will have. This includes everything check_all_attrs_present() looks for by default, as well as optionally an "outgoing_node_names" attribute: if this outgoing_node_names attribute is present as a key in node_attrs, then this will add edges from the new node to all of the node IDs contained in node_attrs["outgoing_node_names"]. (Even if the neighbor nodes referred to in these edges have not already been added to the graph, adding an edge referring to them should add the corresponding nodes to the graph -- and later on, when those nodes are explicitly added to the graph, the edges incident on them should remain.) Returns ------- None Raises ------ ValueError: if the length of the node's seq attribute differs from its actual length attribute. """ check_all_attrs_present(node_attrs) if len(node_attrs["seq"]) != node_attrs["length"]: raise ValueError( "Length given vs. actual seq. length differs for node {}".format( node_attrs["name"] ) ) node_gc_content = DNA(node_attrs["seq"]).gc_content() digraph.add_node( node_attrs["name"], length=node_attrs["length"], cov=node_attrs["cov"], gc=node_gc_content, ) if "outgoing_node_names" in node_attrs: for neighbor_node_name in node_attrs["outgoing_node_names"]: digraph.add_edge(node_attrs["name"], neighbor_node_name) def parse_fastg(f): """Given a path to a FASTG file, returns a representation of its structure. Parameters ---------- f: str Path to a (SPAdes-style) FASTG file. Returns ------- networkx.DiGraph A representation of the structure of the input assembly graph. This DiGraph can immediately be used with the NetworkX library. """ digraph = nx.DiGraph() curr_node_attrs = {} # First off, quickly validate the file on an initial pass through # (TODO: extend this to check up front that all IDs and sequences look # valid, etc.?) with open(f, "r") as graph_file: if not graph_file.readline().startswith(">"): raise ValueError( "File doesn't start with a \">\" character. This doesn't seem " "like a FASTG file." ) with open(f, "r") as graph_file: for line in graph_file: stripped_line = line.strip() if stripped_line.startswith(">"): if len(curr_node_attrs) > 0: add_node_to_digraph(digraph, curr_node_attrs) curr_node_attrs = {} line_no_sc = stripped_line.strip(";") colons = sum([1 for x in line_no_sc if x == ":"]) if colons > 1: raise ValueError( "multiple ':'s found in line, and can only " + "be used to separate nodes from neighbor " + "list\n" ) elif colons == 0: # orphaned node or terminal node curr_node_attrs = extract_node_attrs(line_no_sc) else: # This node has at least one outgoing edge line_no_sc_split = line_no_sc.split(":") curr_node_attrs = extract_node_attrs(line_no_sc_split[0]) curr_node_attrs["outgoing_node_names"] = [] for neighbor_decl in line_no_sc_split[1].split(","): neighbor_name = extract_node_attrs(neighbor_decl)[ "name" ] curr_node_attrs["outgoing_node_names"].append( neighbor_name ) elif len(stripped_line) > 0: if "seq" in curr_node_attrs: curr_node_attrs["seq"] += stripped_line else: curr_node_attrs["seq"] = stripped_line # Account for the last node described at the bottom of the file add_node_to_digraph(digraph, curr_node_attrs) # Ensure that all nodes referenced in the digraph have the guaranteed # attributes # This could *not* happen if node A has an edge to node B, but node B is # never actually declared in the FASTG file (i.e. we never see a line that # goes ">EDGE_B_..."). This scenario would mean the input graph is invalid. for node_name in digraph.nodes: check_all_attrs_present( digraph.nodes[node_name], attrs=("length", "cov", "gc") ) return digraph
#!/usr/bin/env python3 import json import logging import sys import tempfile import threading import time import unittest import warnings sys.path.append('.') from logger.readers.network_reader import NetworkReader from server.logger_manager import LoggerManager from server.in_memory_server_api import InMemoryServerAPI from server.server_api_command_line import ServerAPICommandLine sample_data = [ 'Permission is hereby granted, free of charge, to any person obtaining a copy', 'of this software and associated documentation files (the "Software"), to deal', 'in the Software without restriction, including without limitation the rights', 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell', 'copies of the Software, and to permit persons to whom the Software is', 'furnished to do so, subject to the following conditions:' ] sample_cruise = { "cruise": { "id": "NBP1700", "start": "2017-01-01", "end": "2017-02-01" }, "loggers": { "sample": { "configs": ["off", "sample->net"] }, }, "modes": { "off": { "sample": "off", }, "port": { "sample": "sample->net" } }, "default_mode": "off", "configs": { "off": {}, "sample->net": { "name": "sample->net", "readers": { "class": "TextFileReader", "kwargs": {"interval": 0.2, "file_spec": "fill this in" } }, "transforms": { "class": "PrefixTransform", "kwargs": {"prefix": "TestLoggerManager"} }, "writers": { "class": "NetworkWriter", "kwargs": {"network": ":8002"} } }, "sample->file": { "name": "sample->file", "readers": { "class": "TextFileReader", "kwargs": {"interval": 0.2, "file_spec": "fill this in" } }, "transforms": { "class": "PrefixTransform", "kwargs": {"prefix": "TestLoggerManager"} }, "writers": { "class": "TextFileWriter", "kwargs": {"filename": "fill this in"} } } }, "default_mode": "off" } ################################################################################ class TestLoggerManagerAPI(unittest.TestCase): ############################ def setUp(self): warnings.simplefilter("ignore", ResourceWarning) self.tmpdir = tempfile.TemporaryDirectory() self.tmpdirname = self.tmpdir.name logging.info('created temporary directory "%s"', self.tmpdirname) self.input_filename = self.tmpdirname + '/input.txt' self.output_filename = self.tmpdirname + '/output.txt' self.cruise_filename = self.tmpdirname + '/cruise.json' sample_cruise['configs']['sample->net']['readers']['kwargs']['file_spec'] \ = self.input_filename sample_cruise['configs']['sample->file']['readers']['kwargs']['filename'] \ = self.output_filename logging.info('Creating temp input file %s', self.input_filename) with open(self.input_filename, 'w') as f: for line in sample_data: f.write(line + '\n') logging.info('Creating temp cruise file %s', self.cruise_filename) with open(self.cruise_filename, 'w') as f: f.write(json.dumps(sample_cruise, indent=4)) ############################ def test_basic(self): ############################### # Create LoggerManager and test it api = InMemoryServerAPI() logger_manager = LoggerManager(api=api) ############################ def run_commands(logger_manager): reader = NetworkReader(network=':8002') api = logger_manager.api time.sleep(1) runner = ServerAPICommandLine(api) runner.process_command('load_cruise %s' % self.cruise_filename) runner.process_command('set_mode NBP1700 port') for i in range(4): self.assertEqual(reader.read(), 'TestLoggerManager ' + sample_data[i]) logging.info('NetworkReader done') logger_manager.quit() cmd_thread = threading.Thread(target=run_commands, daemon=True, args=(logger_manager,)) cmd_thread.start() logger_manager.start() cmd_thread.join() ################################################################################ if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbosity', dest='verbosity', default=0, action='count', help='Increase output verbosity') args = parser.parse_args() LOGGING_FORMAT = '%(asctime)-15s %(filename)s:%(lineno)d %(message)s' LOG_LEVELS = {0:logging.WARNING, 1:logging.INFO, 2:logging.DEBUG} logging.basicConfig(format=LOGGING_FORMAT) args.verbosity = min(args.verbosity, max(LOG_LEVELS)) logging.getLogger().setLevel(LOG_LEVELS[args.verbosity]) #logging.getLogger().setLevel(logging.DEBUG) unittest.main(warnings='ignore')
import unittest from ..models import Articles # News = news.Article class ArticleTest(unittest.TestCase): ''' a class to test the behaviour of the Article class ''' def setUp(self): ''' a method that will run before any test ''' self.new_article = Articles('Gizmodo.com','Daniel Kolitz','What\'s Going to Happen With Bitcoin?','Since its inception in 2009, Bitcoin has made and ruined fortunes, helped sell fentanyl and books about cryptocurrency', 'www.gizmodo.com','https://cdn.vox-cdn.com/thumbor/QjYjrRLVMwCgjZSfE7JjC7URQns=/0x300:3733x2254/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/19253276/1040241490.jpg.jpg','2019-10-02T17:40:33Z') def test_instance(self): self.assertTrue(isinstance(self.new_article,Articles)) if __name__ == '__main__': unittest.main()
def response(hey_bob): pass
""" Helper class for get_data and put_data Establishes swift connection and returns a connection object """ import os from google.cloud import storage from google.oauth2 import service_account class GCPHandler: def __init__(self, config): """ Returns a Swift connection object """ cred_path = config['GOOGLE_APPLICATION_CREDENTIALS'] or os.getenv('GOOGLE_APPLICATION_CREDENTIALS') credentials = service_account.Credentials.from_service_account_file(cred_path) self.storage_client = storage.Client(credentials=credentials) class GCPData: """ Upload files to a swift container, download files from a container, and create a container. """ def __init__(self, config): self.gcp_client = GCPHandler(config).storage_client self.cwd = os.getcwd() def create_bucket(self, bucket_name): """ Create a new bucket in specific location with storage class """ bucket = self.gcp_client.bucket(bucket_name) bucket.storage_class = "COLDLINE" new_bucket = self.gcp_client.create_bucket(bucket, location="us") print("Created bucket {} in {} with storage class {}".format(new_bucket.name, new_bucket.location, new_bucket.storage_class)) return new_bucket def get_data(self, bucket_name, file_path, out_file): """ Downloads a blob from the bucket """ bucket = self.gcp_client.bucket(bucket_name) # Construct a client side representation of a blob. # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve # any content from Google Cloud Storage. As we don't need additional data, # using `Bucket.blob` is preferred here. blob = bucket.blob(file_path) blob.download_to_filename(out_file) print("Blob {} downloaded to {}.".format(file_path, out_file)) def get_all_data(self, bucket_name): """ Retrieve all data from a container into a local file """ objects = self.gcp_client.list_blobs(bucket_name) for blob in objects: out_file = self.cwd + '/' + blob.name self.get_data(bucket_name, blob.name, out_file) def put_data(self, bucket_name, local_file_path, dest_file_path): """ Uploads a file to the bucket. """ buckets = self.gcp_client.list_buckets() names = [b.name for b in buckets] if bucket_name not in names: bucket = self.create_bucket(bucket_name) else: bucket = self.gcp_client.bucket(bucket_name) blob = bucket.blob(dest_file_path) blob.upload_from_filename(local_file_path) print("File {} uploaded to {}.".format(local_file_path, dest_file_path))
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Generate a series of TensorFlow graphs that become tflite test cases. Usage: generate_examples <output directory> bazel run //tensorflow/lite/testing:generate_examples To more easily debug failures use (or override) the --save_graphdefs flag to place text proto graphdefs into the generated zip files. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import datetime import functools import itertools import operator import os import random import re import string import traceback import zipfile import numpy as np from six import StringIO from six.moves import xrange # TODO(aselle): Disable GPU for now os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # pylint: disable=g-import-not-at-top import tensorflow as tf from google.protobuf import text_format # TODO(aselle): switch to TensorFlow's resource_loader from tensorflow.contrib.quantize.python import quantize_graph from tensorflow.lite.testing import generate_examples_report as report_lib from tensorflow.lite.testing import string_util_wrapper from tensorflow.python.framework import graph_util as tf_graph_util from tensorflow.python.framework import test_util from tensorflow.python.ops import rnn from tensorflow.python.ops import array_ops RANDOM_SEED = 342 TEST_INPUT_DEPTH = 3 # A map from regular expression to bug number. Any test failure with label # matching the expression will be considered due to the corresponding bug. KNOWN_BUGS = { # TOCO doesn't support scalars as input. # Concat doesn't work with a single input tensor r"concat.*num_tensors=1": "67378344", # Softmax graphs are too complex. r"softmax.*dim=0": "67749831", # BatchToSpaceND only supports 4D tensors. r"batch_to_space_nd.*input_shape=\[8,2,2,2,1,1\]": "70594733", # Div will use floordiv. r"div.*int32": "72051395", # Strided slice cannot handle new_axis_mask. r"strided_slice.*spec=\[None": "137470173", } class MultiGenState(object): """State of multiple set generation process. This state class stores the information needed when generating the examples for multiple test set. The stored informations are open archive object to be shared, information on test target for current iteration of generation, accumulated generation results. """ def __init__(self): # Open archive. self.archive = None # Test name for current generation. self.test_name = None # Label base path containing the test name. # Each of the test data path in the zip archive is derived from this path. # If this path is "a/b/c/d.zip", an example of generated test data path # is "a/b/c/d_input_type=tf.float32,input_shape=[2,2].inputs". # The test runner interpretes the test name of this path as "d". # Label base path also should finish with ".zip". self.label_base_path = None # Zip manifests. self.zip_manifest = [] # Number of all parameters accumulated. self.parameter_count = 0 class Options(object): """All options for example generation.""" def __init__(self): # Directory where the outputs will be go. self.output_path = None # Particular zip to output. self.zip_to_output = None # Path to toco tool. self.toco = None # If a particular model is affected by a known bug count it as a Toco # error. self.known_bugs_are_errors = False # Raise an exception if any converter error is encountered. self.ignore_converter_errors = False # Include intermediate graphdefs in the output zip files. self.save_graphdefs = False # Whether the TFLite Flex converter is being used. self.run_with_flex = False # Whether to generate test cases for edgetpu. self.make_edgetpu_tests = False # The function to convert a TensorFLow model to TFLite model. # See the document for `toco_convert` function for its required signature. self.tflite_convert_function = None # A map from regular expression to bug number. Any test failure with label # matching the expression will be considered due to the corresponding bug. self.known_bugs = KNOWN_BUGS # Make tests by setting TF forward compatibility horizon to the future. self.make_forward_compat_test = False # No limitation on the number of tests. self.no_tests_limit = False # Do not create conversion report. self.no_conversion_report = False # State of multiple test set generation. This stores state values those # should be kept and updated while generating examples over multiple # test sets. # TODO(juhoha): Separate the state from the options. self.multi_gen_state = None # A map from names to functions which make test cases. _MAKE_TEST_FUNCTIONS_MAP = {} # A decorator to register the make test functions. # Usage: # All the make_*_test should be registered. Example: # @register_make_test_function() # def make_conv_tests(options): # # ... # If a function is decorated by other decorators, it's required to specify the # name explicitly. Example: # @register_make_test_function(name="make_unidirectional_sequence_lstm_tests") # @test_util.enable_control_flow_v2 # def make_unidirectional_sequence_lstm_tests(options): # # ... def register_make_test_function(name=None): def decorate(function, name=name): if name is None: name = function.__name__ _MAKE_TEST_FUNCTIONS_MAP[name] = function return decorate class ExtraTocoOptions(object): """Additional toco options besides input, output, shape.""" def __init__(self): # Whether to ignore control dependency nodes. self.drop_control_dependency = False # Allow custom ops in the toco conversion. self.allow_custom_ops = False # Rnn states that are used to support rnn / lstm cells. self.rnn_states = None # Split the LSTM inputs from 5 inoputs to 18 inputs for TFLite. self.split_tflite_lstm_inputs = None # The inference input type passed to TFLiteConvert. self.inference_input_type = None # The inference output type passed to TFLiteConvert. self.inference_output_type = None def format_result(t): """Convert a tensor to a format that can be used in test specs.""" if t.dtype.kind not in [np.dtype(np.string_).kind, np.dtype(np.object_).kind]: # Output 9 digits after the point to ensure the precision is good enough. values = ["{:.9f}".format(value) for value in list(t.flatten())] return ",".join(values) else: return string_util_wrapper.SerializeAsHexString(t.flatten()) def write_examples(fp, examples): """Given a list `examples`, write a text format representation. The file format is csv like with a simple repeated pattern. We would ike to use proto here, but we can't yet due to interfacing with the Android team using this format. Args: fp: File-like object to write to. examples: Example dictionary consiting of keys "inputs" and "outputs" """ def write_tensor(fp, x): """Write tensor in file format supported by TFLITE example.""" fp.write("dtype,%s\n" % x.dtype) fp.write("shape," + ",".join(map(str, x.shape)) + "\n") fp.write("values," + format_result(x) + "\n") fp.write("test_cases,%d\n" % len(examples)) for example in examples: fp.write("inputs,%d\n" % len(example["inputs"])) for i in example["inputs"]: write_tensor(fp, i) fp.write("outputs,%d\n" % len(example["outputs"])) for i in example["outputs"]: write_tensor(fp, i) def write_test_cases(fp, model_name, examples): """Given a dictionary of `examples`, write a text format representation. The file format is protocol-buffer-like, even though we don't use proto due to the needs of the Android team. Args: fp: File-like object to write to. model_name: Filename where the model was written to, relative to filename. examples: Example dictionary consiting of keys "inputs" and "outputs" """ fp.write("load_model: %s\n" % os.path.basename(model_name)) for example in examples: fp.write("reshape {\n") for t in example["inputs"]: fp.write(" input: \"" + ",".join(map(str, t.shape)) + "\"\n") fp.write("}\n") fp.write("invoke {\n") for t in example["inputs"]: fp.write(" input: \"" + format_result(t) + "\"\n") for t in example["outputs"]: fp.write(" output: \"" + format_result(t) + "\"\n") fp.write(" output_shape: \"" + ",".join([str(dim) for dim in t.shape]) + "\"\n") fp.write("}\n") TF_TYPE_INFO = { tf.float32: (np.float32, "FLOAT"), tf.float16: (np.float16, "FLOAT"), tf.int32: (np.int32, "INT32"), tf.uint8: (np.uint8, "QUANTIZED_UINT8"), tf.int16: (np.int16, "QUANTIZED_INT16"), tf.int64: (np.int64, "INT64"), tf.bool: (np.bool, "BOOL"), tf.string: (np.string_, "STRING"), } def create_tensor_data(dtype, shape, min_value=-100, max_value=100): """Build tensor data spreading the range [min_value, max_value).""" if dtype in TF_TYPE_INFO: dtype = TF_TYPE_INFO[dtype][0] if dtype in (tf.float32, tf.float16): value = (max_value-min_value)*np.random.random_sample(shape)+min_value elif dtype in (tf.int32, tf.uint8, tf.int64, tf.int16): value = np.random.randint(min_value, max_value+1, shape) elif dtype == tf.bool: value = np.random.choice([True, False], size=shape) elif dtype == np.string_: # Not the best strings, but they will do for some basic testing. letters = list(string.ascii_uppercase) return np.random.choice(letters, size=shape).astype(dtype) return np.dtype(dtype).type(value) if np.isscalar(value) else value.astype( dtype) def create_scalar_data(dtype, min_value=-100, max_value=100): """Build scalar tensor data range from min_value to max_value exclusively.""" if dtype in TF_TYPE_INFO: dtype = TF_TYPE_INFO[dtype][0] if dtype in (tf.float32, tf.float16): value = (max_value - min_value) * np.random.random() + min_value elif dtype in (tf.int32, tf.uint8, tf.int64, tf.int16): value = np.random.randint(min_value, max_value + 1) return np.array(value, dtype=dtype) def freeze_graph(session, outputs): """Freeze the current graph. Args: session: Tensorflow sessions containing the graph outputs: List of output tensors Returns: The frozen graph_def. """ return tf_graph_util.convert_variables_to_constants( session, session.graph.as_graph_def(), [x.op.name for x in outputs]) @register_make_test_function() def make_control_dep_tests(options): """Make a set of tests that use control dependencies.""" test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32) assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1) with tf.control_dependencies([assert_op]): out = tf.nn.conv2d(input_tensor, filter_value, strides=(1, 1, 1, 1), padding="SAME") return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) extra_toco_options = ExtraTocoOptions() extra_toco_options.drop_control_dependency = True make_zip_of_tests( options, test_parameters, build_graph, build_inputs, extra_toco_options, expected_tf_failures=3) def get_input_shapes_map(input_tensors): """Gets a map of input names to shapes. Args: input_tensors: List of input tensor tuples `(name, shape, type)`. Returns: {string : list of integers}. """ input_arrays = [tensor[0] for tensor in input_tensors] input_shapes_list = [] for _, shape, _ in input_tensors: dims = None if shape: dims = [dim.value for dim in shape.dims] input_shapes_list.append(dims) input_shapes = { name: shape for name, shape in zip(input_arrays, input_shapes_list) if shape } return input_shapes def normalize_output_name(output_name): """Remove :0 suffix from tensor names.""" return output_name.split(":")[0] if output_name.endswith( ":0") else output_name # How many test cases we may have in a zip file. Too many test cases will # slow down the test data generation process. _MAX_TESTS_PER_ZIP = 500 def make_zip_of_tests(options, test_parameters, make_graph, make_test_inputs, extra_toco_options=ExtraTocoOptions(), use_frozen_graph=False, expected_tf_failures=0): """Helper to make a zip file of a bunch of TensorFlow models. This does a cartestian product of the dictionary of test_parameters and calls make_graph() for each item in the cartestian product set. If the graph is built successfully, then make_test_inputs() is called to build expected input/output value pairs. The model is then converted to tflite with toco, and the examples are serialized with the tflite model into a zip file (2 files per item in the cartesian product set). Args: options: An Options instance. test_parameters: Dictionary mapping to lists for each parameter. e.g. `{"strides": [[1,3,3,1], [1,2,2,1]], "foo": [1.2, 1.3]}` make_graph: function that takes current parameters and returns tuple `[input1, input2, ...], [output1, output2, ...]` make_test_inputs: function taking `curr_params`, `session`, `input_tensors`, `output_tensors` and returns tuple `(input_values, output_values)`. extra_toco_options: Additional toco options. use_frozen_graph: Whether or not freeze graph before toco converter. expected_tf_failures: Number of times tensorflow is expected to fail in executing the input graphs. In some cases it is OK for TensorFlow to fail because the one or more combination of parameters is invalid. Raises: RuntimeError: if there are converter errors that can't be ignored. """ zip_path = os.path.join(options.output_path, options.zip_to_output) parameter_count = 0 for parameters in test_parameters: parameter_count += functools.reduce( operator.mul, [len(values) for values in parameters.values()]) all_parameter_count = parameter_count if options.multi_gen_state: all_parameter_count += options.multi_gen_state.parameter_count if not options.no_tests_limit and all_parameter_count > _MAX_TESTS_PER_ZIP: raise RuntimeError( "Too many parameter combinations for generating '%s'.\n" "There are at least %d combinations while the upper limit is %d.\n" "Having too many combinations will slow down the tests.\n" "Please consider splitting the test into multiple functions.\n" % (zip_path, all_parameter_count, _MAX_TESTS_PER_ZIP)) if options.multi_gen_state: options.multi_gen_state.parameter_count = all_parameter_count # TODO(aselle): Make this allow multiple inputs outputs. if options.multi_gen_state: archive = options.multi_gen_state.archive else: archive = zipfile.PyZipFile(zip_path, "w") zip_manifest = [] convert_report = [] toco_errors = 0 processed_labels = set() if options.make_edgetpu_tests: extra_toco_options.inference_input_type = tf.lite.constants.QUANTIZED_UINT8 extra_toco_options.inference_output_type = tf.lite.constants.QUANTIZED_UINT8 label_base_path = zip_path if options.multi_gen_state: label_base_path = options.multi_gen_state.label_base_path for parameters in test_parameters: keys = parameters.keys() for curr in itertools.product(*parameters.values()): label = label_base_path.replace(".zip", "_") + (",".join( "%s=%r" % z for z in sorted(zip(keys, curr))).replace(" ", "")) if label[0] == "/": label = label[1:] if label in processed_labels: # Do not populate data for the same label more than once. It will cause # errors when unzipping. continue processed_labels.add(label) param_dict = dict(zip(keys, curr)) if options.make_edgetpu_tests and not param_dict.get( "fully_quantize", False): continue def build_tflite_inputs(tflite_model_binary): # Build input values and output values of the given tflite model. interpreter = tf.lite.Interpreter(model_content=tflite_model_binary) interpreter.allocate_tensors() input_details = interpreter.get_input_details() input_values = [] for input_detail in input_details: # TODO(yunluli): Set proper min max value according to dtype. input_value = create_tensor_data( input_detail["dtype"], input_detail["shape"], min_value=0, max_value=255) interpreter.set_tensor(input_detail["index"], input_value) input_values.append(input_value) interpreter.invoke() output_details = interpreter.get_output_details() output_values = [] for output_detail in output_details: output_values.append(interpreter.get_tensor(output_detail["index"])) return input_values, output_values def build_example(label, param_dict_real): """Build the model with parameter values set in param_dict_real. Args: label: Label of the model (i.e. the filename in the zip). param_dict_real: Parameter dictionary (arguments to the factories make_graph and make_test_inputs) Returns: (tflite_model_binary, report) where tflite_model_binary is the serialized flatbuffer as a string and report is a dictionary with keys `toco_log` (log of toco conversion), `tf_log` (log of tf conversion), `toco` (a string of success status of the conversion), `tf` (a string success status of the conversion). """ np.random.seed(RANDOM_SEED) report = {"toco": report_lib.NOTRUN, "tf": report_lib.FAILED} # Build graph report["tf_log"] = "" report["toco_log"] = "" tf.reset_default_graph() with tf.device("/cpu:0"): try: inputs, outputs = make_graph(param_dict_real) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report sess = tf.compat.v1.Session() try: baseline_inputs, baseline_outputs = (make_test_inputs( param_dict_real, sess, inputs, outputs)) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report report["toco"] = report_lib.FAILED report["tf"] = report_lib.SUCCESS # Convert graph to toco input_tensors = [(input_tensor.name.split(":")[0], input_tensor.shape, input_tensor.dtype) for input_tensor in inputs] output_tensors = [normalize_output_name(out.name) for out in outputs] graph_def = freeze_graph( sess, tf.global_variables() + inputs + outputs) if use_frozen_graph else sess.graph_def if "split_tflite_lstm_inputs" in param_dict_real: extra_toco_options.split_tflite_lstm_inputs = param_dict_real[ "split_tflite_lstm_inputs"] tflite_model_binary, toco_log = options.tflite_convert_function( options, graph_def, input_tensors, output_tensors, extra_toco_options=extra_toco_options, test_params=param_dict_real) report["toco"] = (report_lib.SUCCESS if tflite_model_binary is not None else report_lib.FAILED) report["toco_log"] = toco_log if options.save_graphdefs: archive.writestr(label + ".pbtxt", text_format.MessageToString(graph_def), zipfile.ZIP_DEFLATED) if tflite_model_binary: if options.make_edgetpu_tests: baseline_inputs, baseline_outputs = build_tflite_inputs( tflite_model_binary) archive.writestr(label + ".bin", tflite_model_binary, zipfile.ZIP_DEFLATED) example = {"inputs": baseline_inputs, "outputs": baseline_outputs} example_fp = StringIO() write_examples(example_fp, [example]) archive.writestr(label + ".inputs", example_fp.getvalue(), zipfile.ZIP_DEFLATED) example_fp2 = StringIO() write_test_cases(example_fp2, label + ".bin", [example]) archive.writestr(label + "_tests.txt", example_fp2.getvalue(), zipfile.ZIP_DEFLATED) zip_manifest.append(label + "\n") return tflite_model_binary, report _, report = build_example(label, param_dict) if report["toco"] == report_lib.FAILED: ignore_error = False if not options.known_bugs_are_errors: for pattern, bug_number in options.known_bugs.items(): if re.search(pattern, label): print("Ignored converter error due to bug %s" % bug_number) ignore_error = True if not ignore_error: toco_errors += 1 print("-----------------\nconverter error!\n%s\n-----------------\n" % report["toco_log"]) convert_report.append((param_dict, report)) if not options.no_conversion_report: report_io = StringIO() report_lib.make_report_table(report_io, zip_path, convert_report) if options.multi_gen_state: archive.writestr("report_" + options.multi_gen_state.test_name + ".html", report_io.getvalue()) else: archive.writestr("report.html", report_io.getvalue()) if options.multi_gen_state: options.multi_gen_state.zip_manifest.extend(zip_manifest) else: archive.writestr("manifest.txt", "".join(zip_manifest), zipfile.ZIP_DEFLATED) # Log statistics of what succeeded total_conversions = len(convert_report) tf_success = sum(1 for x in convert_report if x[1]["tf"] == report_lib.SUCCESS) toco_success = sum(1 for x in convert_report if x[1]["toco"] == report_lib.SUCCESS) percent = 0 if tf_success > 0: percent = float(toco_success) / float(tf_success) * 100. tf.logging.info(("Archive %s Considered %d graphs, %d TF evaluated graphs " " and %d TOCO converted graphs (%.1f%%"), zip_path, total_conversions, tf_success, toco_success, percent) tf_failures = parameter_count - tf_success if tf_failures / parameter_count > 0.8: raise RuntimeError(("Test for '%s' is not very useful. " "TensorFlow fails in %d percent of the cases.") % (zip_path, int(100 * tf_failures / parameter_count))) if not options.make_edgetpu_tests and tf_failures != expected_tf_failures: raise RuntimeError(("Expected TF to fail %d times while generating '%s', " "but that happened %d times") % (expected_tf_failures, zip_path, tf_failures)) if not options.ignore_converter_errors and toco_errors > 0: raise RuntimeError( "Found %d errors while generating toco models" % toco_errors) def make_pool_tests(pool_op_in): """Make a set of tests to do average pooling. Args: pool_op_in: TensorFlow pooling operation to test i.e. `tf.nn.avg_pool2d`. Returns: A function representing the true generator (after curried pool_op_in). """ pool_op = pool_op_in def f(options, expected_tf_failures=0): """Actual function that generates examples. Args: options: An Options instance. expected_tf_failures: number of expected tensorflow failures. """ # Chose a set of parameters test_parameters = [{ "ksize": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], "strides": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]). "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = pool_op( input_tensor, ksize=parameters["ksize"], strides=parameters["strides"], data_format=parameters["data_format"], padding=parameters["padding"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=expected_tf_failures) return f @register_make_test_function() def make_l2_pool_tests(options): make_pool_tests(make_l2_pool)(options, expected_tf_failures=80) @register_make_test_function() def make_avg_pool_tests(options): make_pool_tests(tf.nn.avg_pool)(options, expected_tf_failures=80) @register_make_test_function() def make_max_pool_tests(options): make_pool_tests(tf.nn.max_pool)(options, expected_tf_failures=80) @register_make_test_function() def make_abs_tests(options): """Make a set of tests to do relu.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.abs(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-10, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_elu_tests(options): """Make a set of tests to do (float) tf.nn.elu.""" test_parameters = [ { "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }, ] def build_graph(parameters): """Build the graph for the test case.""" input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.elu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): """Build the inputs for the test case.""" input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_hardswish_tests(options): """Make a set of tests to do hardswish.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): inp = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = inp * tf.nn.relu6(inp + np.float32(3)) * np.float32(1. / 6.) return [inp], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-10, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) # Add additional validation if we are using toco. # Flex and mlir doesn't yet support this. TODO(b/139193008): Fix if not options.run_with_flex: options.tflite_convert_function = functools.partial( _tflite_convert_verify_num_ops, options.tflite_convert_function, num_ops=2) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) def _tflite_convert_verify_num_ops(tflite_convert_function, *args, **kwargs): """Verifies that the result of the conversion is a single op.""" num_ops = kwargs.pop("num_ops", 2) result = tflite_convert_function(*args, **kwargs) tflite_model_binary = result[0] if not result[0]: tf.logging.error(result[1]) # stderr from running tflite_convert. raise RuntimeError("Failed to bulid model: \n\n" + result[1]) interpreter = tf.lite.Interpreter(model_content=tflite_model_binary) interpreter.allocate_tensors() if len(interpreter.get_tensor_details()) != num_ops: raise RuntimeError("Expected to generate two node graph got %r " % interpreter.get_tensor_details()) return result @register_make_test_function() def make_uint8_hardswish_tests(options): """Make a set of tests to do hardswish.""" # Chose a set of parameters. test_parameters = [{ "input_shape": [[2, 3]], "fully_quantize": [True], }] def build_graph(parameters): """Builds tensorflow graph.""" inp = tf.placeholder(dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Note: there is some magic about the inputs being in the range [-1,1] # or else some quantization range need to be fixed. qinp = array_ops.fake_quant_with_min_max_args( inp, min=-1, max=1, num_bits=8) relu6 = tf.nn.relu6(qinp + np.float32(3)) * np.float32(1. / 6.) out = qinp * relu6 quantize_graph.experimental_create_eval_graph( inp.graph, weight_bits=8, activation_bits=8) return [qinp], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-1, max_value=1) output_values = sess.run(outputs, feed_dict=dict(zip(inputs, [input_values]))) return [input_values], output_values # Add additional validation if we are using toco. # Flex, doesn't yet support this. TODO(b/139193008): Remove this constraitn if not options.run_with_flex: # Expect 2 quantize operators and one hard swish resulting in 4 tensors. options.tflite_convert_function = functools.partial( _tflite_convert_verify_num_ops, options.tflite_convert_function, num_ops=4) extra_toco_options = ExtraTocoOptions() extra_toco_options.inference_input_type = tf.lite.constants.QUANTIZED_UINT8 extra_toco_options.inference_output_type = tf.lite.constants.QUANTIZED_UINT8 make_zip_of_tests( options, test_parameters, build_graph, build_inputs, extra_toco_options=extra_toco_options, use_frozen_graph=True) @register_make_test_function() def make_identity_tests(options): """Make a set of tests to do identity.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [3, 3]], "op_to_use": [ "identity", "identity_n", "snapshot", "identity_n_with_2_inputs" ], }] def build_graph(parameters): input_tensors = [] input_count = (2 if parameters["op_to_use"] == "identity_n_with_2_inputs" else 1) input_tensors = [ tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) for _ in range(input_count) ] # We add the Multiply before Identity just as a walk-around to make the test # pass when input_shape is scalar. # During graph transformation, TOCO will replace the Identity op with # Reshape when input has shape. However, currently TOCO can't distinguish # between missing shape and scalar shape. As a result, when input has scalar # shape, this conversion still fails. # TODO(b/129197312), remove the walk-around code once the bug is fixed. inputs_doubled = [input_tensor * 2.0 for input_tensor in input_tensors] if parameters["op_to_use"] == "identity": identity_outputs = [tf.identity(inputs_doubled[0])] elif parameters["op_to_use"] == "snapshot": identity_outputs = [array_ops.snapshot(inputs_doubled[0])] elif parameters["op_to_use"] in ("identity_n", "identity_n_with_2_inputs"): identity_outputs = tf.identity_n(inputs_doubled) return input_tensors, identity_outputs def build_inputs(parameters, sess, inputs, outputs): input_values = [ create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) for _ in range(len(inputs)) ] return input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_relu_tests(options): """Make a set of tests to do relu.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_relu1_tests(options): """Make a set of tests to do relu1.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Note that the following is not supported: # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0)) out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0)) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_relu6_tests(options): """Make a set of tests to do relu6.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_prelu_tests(options): """Make a set of tests to do PReLU.""" test_parameters = [ { # The canonical case for image processing is having a 4D `input` # (NHWC)and `shared_axes`=[1, 2], so the alpha parameter is per # channel. "input_shape": [[1, 10, 10, 3], [3, 3, 3, 3]], "shared_axes": [[1, 2], [1]], }, { # 2D-3D example. Share the 2nd axis. "input_shape": [[20, 20], [20, 20, 20]], "shared_axes": [[1]], } ] def build_graph(parameters): """Build the graph for the test case.""" input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) prelu = tf.keras.layers.PReLU(shared_axes=parameters["shared_axes"]) out = prelu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): """Build the inputs for the test case.""" input_shape = parameters["input_shape"] input_values = create_tensor_data( np.float32, input_shape, min_value=-10, max_value=10) shared_axes = parameters["shared_axes"] alpha_shape = [] for dim in range(1, len(input_shape)): alpha_shape.append(1 if dim in shared_axes else input_shape[dim]) alpha_values = create_tensor_data(np.float32, alpha_shape) # There should be only 1 trainable variable tensor. variables = tf.all_variables() assert len(variables) == 1 sess.run(variables[0].assign(alpha_values)) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, use_frozen_graph=True) @register_make_test_function() def make_leaky_relu_tests(options): """Make a set of tests to do LeakyRelu.""" test_parameters = [ { "input_shape": [[], [1], [5], [1, 10, 10, 3], [3, 3, 3, 3]], "alpha": [0.1, 1.0, 2.0, -0.1, -1.0, -2.0], }, ] def build_graph(parameters): """Build the graph for the test case.""" input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.leaky_relu(input_tensor, alpha=parameters["alpha"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): """Build the inputs for the test case.""" input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) # This function tests various TensorFLow functions that generates Const op, # including `tf.ones`, `tf.zeros` and random functions. @register_make_test_function() def make_constant_tests(options): """Make a set of tests to do constant ops.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[], [1], [2], [1, 1, 1, 1], [2, 2, 2, 2]], "constant_is_also_output": [True, False], # This is a regression test for a bug where Toco rejects models with # unread inputs. "has_unread_input": [True, False], }] def build_graph(parameters): dummy_input = tf.placeholder( dtype=parameters["dtype"], name="input1", shape=parameters["input_shape"]) constant = tf.constant( create_tensor_data(parameters["dtype"], parameters["input_shape"])) outputs = [tf.maximum(dummy_input, constant)] if parameters["constant_is_also_output"]: outputs.append(constant) inputs = [dummy_input] if parameters["has_unread_input"]: unread_input = tf.placeholder( dtype=parameters["dtype"], name="unread_input", shape=parameters["input_shape"]) inputs.append(unread_input) return inputs, outputs def build_inputs(parameters, sess, inputs, outputs): dummy_input = np.zeros( parameters["input_shape"], dtype=TF_TYPE_INFO[parameters["dtype"]][0]) return [dummy_input], sess.run(outputs, feed_dict={inputs[0]: dummy_input}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) def make_binary_op_tests(options, binary_operator, expected_tf_failures=0): """Make a set of tests to do binary ops with and without broadcast.""" test_parameters = [ # Avoid creating all combinations to keep the test size small. { "dtype": [tf.float32, tf.int32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[1, 3, 4, 3]], "activation": [True], }, { "dtype": [tf.float32], "input_shape_1": [[5]], "input_shape_2": [[5]], "activation": [False, True], }, { "dtype": [tf.float32, tf.int32, tf.int64], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[3]], "activation": [True, False], }, { "dtype": [tf.float32, tf.int32], "input_shape_1": [[3]], "input_shape_2": [[1, 3, 4, 3]], "activation": [True, False], }, { "dtype": [tf.float32], "input_shape_1": [[]], "input_shape_2": [[]], "activation": [False], }, { "dtype": [tf.float32], "input_shape_1": [[0]], "input_shape_2": [[1]], "activation": [False], } ] def build_graph(parameters): """Builds the graph given the current parameters.""" input1 = tf.placeholder( dtype=parameters["dtype"], name="input1", shape=parameters["input_shape_1"]) input2 = tf.placeholder( dtype=parameters["dtype"], name="input2", shape=parameters["input_shape_2"]) out = binary_operator(input1, input2) if parameters["activation"]: out = tf.nn.relu(out) return [input1, input2], [out] def build_inputs(parameters, sess, inputs, outputs): """Builds operand inputs for op.""" input1 = create_tensor_data(parameters["dtype"], parameters["input_shape_1"]) input2 = create_tensor_data(parameters["dtype"], parameters["input_shape_2"]) return [input1, input2], sess.run( outputs, feed_dict={ inputs[0]: input1, inputs[1]: input2 }) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=expected_tf_failures) def make_reduce_tests(reduce_op, min_value=-10, max_value=10, boolean_tensor_only=False): """Make a set of tests to do reduce operation. Args: reduce_op: TensorFlow reduce operation to test, i.e. `tf.reduce_mean`. min_value: min value for created tensor data. max_value: max value for created tensor data. boolean_tensor_only: If true, will only generate tensor with boolean value. Returns: a function representing the true generator with `reduce_op_in` curried. """ def f(options): """Actual function that generates examples.""" test_parameters = [ { "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[3, 3, 2, 4]], "axis": [ 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0], [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1], [-1, 0], [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3] ], "const_axis": [True, False], "keepdims": [True, False], }, { "input_dtype": [tf.float32], "input_shape": [[1, 8, 8, 3]], "axis": [ 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2, 3], [3, 2, 1, 0], [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2, -3, -4, [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2], [2, 2, 3], [-3, -3, -4], [-3, 2, 1] ], "const_axis": [True, False], "keepdims": [True, False], }, { "input_dtype": [tf.float32], "input_shape": [[], [1, 8, 8, 3], [3, 2, 4]], "axis": [[]], # shape is: [0] "const_axis": [False], "keepdims": [True, False], }, { "input_dtype": [tf.float32], "input_shape": [[], [1, 8, 8, 3], [3, 2, 4]], "axis": [None], # shape is: [] "const_axis": [True], "keepdims": [True, False], } ] def build_graph(parameters): """Build the mean op testing graph.""" dtype = parameters["input_dtype"] if boolean_tensor_only: dtype = tf.bool input_tensor = tf.placeholder( dtype=dtype, name="input", shape=parameters["input_shape"]) # Get axis as either a placeholder or constants. if parameters["const_axis"]: axis = parameters["axis"] input_tensors = [input_tensor] else: if isinstance(parameters["axis"], list): shape = [len(parameters["axis"])] else: shape = [] # shape for None or integers. axis = tf.placeholder(dtype=tf.int32, name="axis", shape=shape) input_tensors = [input_tensor, axis] out = reduce_op( input_tensor, axis=axis, keepdims=parameters["keepdims"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): dtype = parameters["input_dtype"] if boolean_tensor_only: dtype = tf.bool values = [ create_tensor_data( dtype, parameters["input_shape"], min_value=min_value, max_value=max_value) ] if not parameters["const_axis"]: values.append(np.array(parameters["axis"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) return f @register_make_test_function() def make_mean_tests(options): """Make a set of tests to do mean.""" return make_reduce_tests(tf.reduce_mean)(options) @register_make_test_function() def make_sum_tests(options): """Make a set of tests to do sum.""" return make_reduce_tests(tf.reduce_sum)(options) @register_make_test_function() def make_reduce_prod_tests(options): """Make a set of tests to do prod.""" # set min max value to be -2, 2 to avoid overflow. return make_reduce_tests(tf.reduce_prod, -2, 2)(options) @register_make_test_function() def make_reduce_max_tests(options): """Make a set of tests to do max.""" return make_reduce_tests(tf.reduce_max)(options) @register_make_test_function() def make_reduce_min_tests(options): """Make a set of tests to do min.""" return make_reduce_tests(tf.reduce_min)(options) @register_make_test_function() def make_reduce_any_tests(options): """Make a set of tests to do any.""" return make_reduce_tests(tf.reduce_any, boolean_tensor_only=True)(options) @register_make_test_function() def make_exp_tests(options): """Make a set of tests to do exp.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the exp op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.exp(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_cos_tests(options): """Make a set of tests to do cos.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the cos op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.cos(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"], min_value=-np.pi, max_value=np.pi) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_log_softmax_tests(options): """Make a set of tests to do log_softmax.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[1, 100], [4, 2], [5, 224]], }] def build_graph(parameters): """Build the log_softmax op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.log_softmax(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data( parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_maximum_tests(options): """Make a set of tests to do maximum.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the maximum op testing graph.""" input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.maximum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=8) @register_make_test_function() def make_minimum_tests(options): """Make a set of tests to do minimum.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the minimum op testing graph.""" input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.minimum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=8) def make_binary_op_tests_func(binary_operator): """Return a function that does a test on a binary operator.""" return lambda options: make_binary_op_tests(options, binary_operator) @register_make_test_function() def make_add_tests(options): make_binary_op_tests(options, tf.add) @register_make_test_function() def make_add_n_tests(options): """Make a set of tests for AddN op.""" test_parameters = [ { "dtype": [tf.float32, tf.int32], "input_shape": [[2, 5, 3, 1]], "num_inputs": [2, 3, 4, 5], }, { "dtype": [tf.float32, tf.int32], "input_shape": [[5]], "num_inputs": [2, 3, 4, 5], }, { "dtype": [tf.float32, tf.int32], "input_shape": [[]], "num_inputs": [2, 3, 4, 5], }, ] def build_graph(parameters): """Builds the graph given the current parameters.""" input_tensors = [] for i in range(parameters["num_inputs"]): input_tensors.append( tf.placeholder( dtype=parameters["dtype"], name="input_{}".format(i), shape=parameters["input_shape"])) out = tf.add_n(input_tensors) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): """Builds operand inputs for op.""" input_data = [] for i in range(parameters["num_inputs"]): input_data.append( create_tensor_data(parameters["dtype"], parameters["input_shape"])) return input_data, sess.run( outputs, feed_dict={i: d for i, d in zip(inputs, input_data)}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_div_tests(options): make_binary_op_tests(options, tf.div) @register_make_test_function() def make_sub_tests(options): make_binary_op_tests(options, tf.subtract) @register_make_test_function() def make_mul_tests(options): make_binary_op_tests(options, tf.multiply) @register_make_test_function() def make_pow_tests(options): make_binary_op_tests(options, tf.pow, expected_tf_failures=7) @register_make_test_function() def make_floor_div_tests(options): make_binary_op_tests(options, tf.floor_div) @register_make_test_function() def make_floor_mod_tests(options): make_binary_op_tests(options, tf.floormod) @register_make_test_function() def make_squared_difference_tests(options): make_binary_op_tests(options, tf.squared_difference) @register_make_test_function() def make_gather_tests(options): """Make a set of tests to do gather.""" test_parameters = [ { "params_dtype": [tf.float32, tf.int32, tf.int64], "params_shape": [[10], [1, 2, 20]], "indices_dtype": [tf.int32, tf.int64], "indices_shape": [[3], [5]], "axis": [-1, 0, 1], }, { # TODO(b/123895910): add Nd support for strings. "params_dtype": [tf.string], "params_shape": [[8]], "indices_dtype": [tf.int32], "indices_shape": [[3]], "axis": [0], } ] def build_graph(parameters): """Build the gather op testing graph.""" params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) indices = tf.placeholder( dtype=parameters["indices_dtype"], name="indices", shape=parameters["indices_shape"]) axis = min(len(parameters["params_shape"]), parameters["axis"]) out = tf.gather(params, indices, axis=axis) return [params, indices], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) indices = create_tensor_data(parameters["indices_dtype"], parameters["indices_shape"], 0, parameters["params_shape"][0] - 1) return [params, indices], sess.run( outputs, feed_dict=dict(zip(inputs, [params, indices]))) # Note that TF can't execute with index=1 and params_shape=[10]. make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=12) @register_make_test_function() def make_gather_nd_tests(options): """Make a set of tests to do gather_nd.""" test_parameters = [ { "params_dtype": [tf.float32, tf.int32, tf.int64], "params_shape": [[5, 1]], "indices_dtype": [tf.int32, tf.int64], "indices_shape": [[1, 1]], }, { "params_dtype": [tf.float32, tf.int32, tf.int64], "params_shape": [[5, 5]], "indices_dtype": [tf.int32, tf.int64], "indices_shape": [[2, 1], [2, 2]], }, { "params_dtype": [tf.float32, tf.int32, tf.int64], "params_shape": [[5, 5, 10]], "indices_dtype": [tf.int32, tf.int64], "indices_shape": [[3, 1], [2, 2], [2, 3], [2, 1, 3]], }, ] def build_graph(parameters): """Build the gather_nd op testing graph.""" params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) indices = tf.placeholder( dtype=parameters["indices_dtype"], name="indices", shape=parameters["indices_shape"]) out = tf.gather_nd(params, indices) return [params, indices], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) indices = create_tensor_data(parameters["indices_dtype"], parameters["indices_shape"], 0, parameters["params_shape"][0] - 1) return [params, indices], sess.run( outputs, feed_dict=dict(zip(inputs, [params, indices]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_gather_with_constant_tests(options): """Make a set of test which feed a constant to gather toco.""" test_parameters = [{ "input_shape": [[3]], "reference_shape": [[2]], }, { "input_shape": [[2, 3]], "reference_shape": [[2, 3]], }] def build_graph(parameters): """Build a graph where the inputs to Gather are constants.""" reference = tf.placeholder( dtype=tf.int32, shape=parameters["reference_shape"]) gather_input = tf.constant( create_tensor_data(tf.int32, parameters["input_shape"])) gather_indices = tf.constant([0, 1], tf.int32) out = tf.equal(reference, tf.gather(gather_input, gather_indices)) return [reference], [out] def build_inputs(parameters, sess, inputs, outputs): reference_values = np.zeros(parameters["reference_shape"], dtype=np.int32) return [reference_values], sess.run( outputs, feed_dict={inputs[0]: reference_values}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_embedding_lookup_tests(options): """Make a set of tests to do gather.""" test_parameters = [ { "params_dtype": [tf.float32], "params_shape": [[10], [10, 10]], "ids_dtype": [tf.int32], "ids_shape": [[3], [5]], }, ] def build_graph(parameters): """Build the gather op testing graph.""" params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) ids = tf.placeholder( dtype=parameters["ids_dtype"], name="ids", shape=parameters["ids_shape"]) out = tf.nn.embedding_lookup(params, ids) return [params, ids], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) ids = create_tensor_data(parameters["ids_dtype"], parameters["ids_shape"], 0, parameters["params_shape"][0] - 1) return [params, ids], sess.run( outputs, feed_dict=dict(zip(inputs, [params, ids]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_global_batch_norm_tests(options): """Make a set of tests to do batch_norm_with_global_normalization.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2], [3, 4, 5, 4]], "epsilon": [0.1, 0.0001], "scale_after": [True, False], }] def build_graph(parameters): """Build the global batch norm testing graph.""" input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) x_norm = tf.nn.batch_norm_with_global_normalization( x, mean, variance, scale, offset, parameters["epsilon"], parameters["scale_after"]) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_fused_batch_norm_tests(options): """Make a set of tests to do fused_batch_norm.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2]], "epsilon": [0.001, 0.1], }] def build_graph(parameters): """Build the testing graph for fused batch normalization.""" input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) [x_norm, _, _] = tf.nn.fused_batch_norm( x, scale, offset, mean, variance, parameters["epsilon"], data_format="NHWC", is_training=False) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_conv_tests(options): """Make a set of tests to do convolution.""" test_parameters = [ { "input_shape": [[1, 3, 4, 3], [4, 6, 6, 1]], "filter_shape": [[1, 1], [2, 3], [3, 3]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], "channel_multiplier": [1, 2], "fully_quantize": [False], }, # TODO(b/134702301): The fully_quantize param is just ignored by the MLIR # testing path now, resulting in duplicate tests. Either ignore these # tests or handle it properly in the mlir_convert() function. { "input_shape": [[1, 3, 4, 3], [4, 6, 6, 1]], "filter_shape": [[1, 1], [2, 3], [3, 3]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True], "channel_multiplier": [1, 2], "fully_quantize": [True], } ] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_shape"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data( np.float32, filter_shape, min_value=-10, max_value=10) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) input_tensors = [input_tensor, filter_input] out = tf.nn.conv2d( input_tensor, filter_input, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, filter_shape = get_tensor_shapes(parameters) values = [ create_tensor_data(np.float32, input_shape, min_value=-1, max_value=1) ] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, filter_shape)) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=60) # Note: This is a regression test for a bug (b/122651451) that Toco incorrectly # erases the reduction indices array while it's shared with other ops. @register_make_test_function() def make_l2norm_shared_epsilon_tests(options): """Regression test for a bug (b/122651451).""" # Chose a set of parameters test_parameters = [{ "input_shape": [[5, 7]], "dim": [1], "epsilon": [1e-8], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) epsilon = tf.constant(parameters["epsilon"]) out1 = tf.nn.l2_normalize(input_tensor, parameters["dim"], epsilon=epsilon) out2 = tf.nn.l2_normalize(input_tensor, parameters["dim"], epsilon=epsilon) out = out1 + out2 return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) # Note: This is a regression test for a bug (b/112436267) that Toco incorrectly # fuses weights when multiple Conv2D/FULLY_CONNECTED ops share the same constant # weight tensor. @register_make_test_function() def make_conv_with_shared_weights_tests(options): """Make a test where 2 Conv ops shared the same constant weight tensor.""" test_parameters = [{ "input_shape": [[1, 10, 10, 3]], "filter_shape": [[3, 3]], "strides": [[1, 1, 1, 1]], "dilations": [[1, 1, 1, 1]], "padding": ["SAME"], "data_format": ["NHWC"], "channel_multiplier": [1], }] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_shape"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) input_tensors = [input_tensor] # Construct a constant weights tensor which will be used by both Conv2D. filter_tensor = tf.constant( create_tensor_data(np.float32, filter_shape), dtype=tf.float32) # Ensure that FuseBinaryIntoFollowingAffine works with an input which # is shared by multiple affine ops. conv_input = input_tensor + 0.1 # Construct 2 Conv2D operations which use exactly the same input and # weights. result1 = tf.nn.conv2d( conv_input, filter_tensor, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) result2 = tf.nn.conv2d( conv_input, filter_tensor, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) # Add MUL ops after Conv2D ops. These MUL ops should be fused into the # weights of Conv2D. result1 = result1 * 2 result2 = result2 * 3 # Add the 2 results up. out = result1 + result2 return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, unused_filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) # Note: This is a regression test for a bug (b/112303004) that Toco incorrectly # transforms Conv into DepthwiseConv when two Conv ops share the same constant # weight tensor. @register_make_test_function() def make_conv_to_depthwiseconv_with_shared_weights_tests(options): """Make a test where 2 Conv ops shared the same constant weight tensor.""" test_parameters = [{ "input_shape": [[1, 10, 10, 1]], "filter_shape": [[3, 3]], "strides": [[1, 1, 1, 1]], "dilations": [[1, 1, 1, 1]], "padding": ["SAME"], "data_format": ["NHWC"], "channel_multiplier": [3], }] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_shape"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Construct a constant weights tensor which will be used by both Conv2D. filter_tensor = tf.constant( create_tensor_data(np.float32, filter_shape), dtype=tf.float32) input_tensors = [input_tensor] # Construct 2 Conv2D operations which use exactly the same input and # weights. result1 = tf.nn.conv2d( input_tensor, filter_tensor, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) result2 = tf.nn.conv2d( input_tensor, filter_tensor, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) # Add the 2 results up. out = result1 + result2 return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, unused_filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_depthwiseconv_tests(options): """Make a set of tests to do convolution.""" # Tensorflow only supports equal strides test_parameters = [ { "input_shape": [[1, 3, 4, 3], [1, 10, 10, 3]], "filter_size": [[1, 1], [1, 2], [3, 3]], "strides": [[1, 1, 1, 1], [1, 3, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "channel_multiplier": [1, 2], "rate": [[1, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], "constant_filter": [True, False], }, { "input_shape": [[1, 3, 4, 3]], "filter_size": [[1, 1]], "strides": [[1, 1, 2, 1]], # TF needs [1, x, x, 1] "dilations": [[1, 1, 1, 1], [1, 2, 2, 1]], "channel_multiplier": [2], "rate": [[2, 2]], # Only [1, 1] is supported "padding": ["SAME"], "data_format": ["NHWC"], "constant_filter": [True, False], } ] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_size"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a depthwise conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, filter_shape) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) input_tensors = [input_tensor, filter_input] out = tf.nn.depthwise_conv2d( input_tensor, filter_input, strides=parameters["strides"], rate=parameters["rate"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, filter_shape)) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=4) @register_make_test_function() def make_split_tests(options): """Make a set of tests to do tf.split.""" test_parameters = [{ "input_shape": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]], "num_or_size_splits": [1, 2, 3, 4, 5], "axis": [0, 1, 2, 3, -4, -3, -2, -1], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.split( input_tensor, parameters["num_or_size_splits"], parameters["axis"]) return [input_tensor], [out[0]] def build_inputs(parameters, sess, inputs, outputs): values = [create_tensor_data(np.float32, parameters["input_shape"])] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=112) @register_make_test_function() def make_splitv_tests(options): """Make a set of tests to do tf.split_v.""" test_parameters = [{ "input_shape": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]], "size_splits": [[2, 2], [1, 3], [4, 2], [5, 3], [-1, 1], [-1, 2], [-1, 4]], "axis": [0, 1, 2, 3, -4, -3, -2, -1], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.split(input_tensor, parameters["size_splits"], parameters["axis"]) return [input_tensor], [out[0]] def build_inputs(parameters, sess, inputs, outputs): values = [create_tensor_data(np.float32, parameters["input_shape"])] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=158) @register_make_test_function() def make_concat_tests(options): """Make a set of tests to do concatenation.""" test_parameters = [{ "base_shape": [[1, 3, 4, 3], [3, 4]], "num_tensors": [1, 2, 3, 4, 5, 6], "axis": [0, 1, 2, 3, -3, -2, -1], "type": [tf.float32, tf.uint8, tf.int32, tf.int64], }] def get_shape(parameters, delta): """Return a tweaked version of 'base_shape'.""" axis = parameters["axis"] shape = parameters["base_shape"][:] if axis < 0: axis += len(shape) if axis < len(shape): shape[axis] += delta return shape def build_graph(parameters): all_tensors = [] for n in range(0, parameters["num_tensors"]): input_tensor = tf.placeholder(dtype=parameters["type"], name=("input%d" % n), shape=get_shape(parameters, n)) all_tensors.append(input_tensor) out = tf.concat(all_tensors, parameters["axis"]) return all_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): all_values = [] for n in range(0, parameters["num_tensors"]): input_values = create_tensor_data( parameters["type"], get_shape(parameters, n)) all_values.append(input_values) return all_values, sess.run( outputs, feed_dict=dict(zip(inputs, all_values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=60) @register_make_test_function() def make_fully_connected_tests(options): """Make a set of tests to do fully_connected.""" test_parameters = [{ "shape1": [[3, 3]], "shape2": [[3, 3]], "transpose_a": [True, False], "transpose_b": [True, False], "constant_filter": [True, False], }, { "shape1": [[4, 4], [1, 4], [4]], "shape2": [[4, 4], [4, 1], [4]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }, { "shape1": [[40, 37]], "shape2": [[37, 40]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }, { "shape1": [[40, 37]], "shape2": [[40, 37]], "transpose_a": [False], "transpose_b": [True], "constant_filter": [True, False], }, { "shape1": [[5, 3]], "shape2": [[5, 3]], "transpose_a": [True], "transpose_b": [False], "constant_filter": [True, False], }] def build_graph(parameters): """Build a matmul graph given `parameters`.""" input_tensor1 = tf.placeholder(dtype=tf.float32, name="input1", shape=parameters["shape1"]) # Get input_tensor2 either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: input_tensor2 = create_tensor_data(np.float32, parameters["shape2"]) input_tensors = [input_tensor1] else: input_tensor2 = tf.placeholder( dtype=tf.float32, name="input2", shape=parameters["shape2"]) input_tensors = [input_tensor1, input_tensor2] out = tf.matmul(input_tensor1, input_tensor2, transpose_a=parameters["transpose_a"], transpose_b=parameters["transpose_b"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input_values1) or 2 # tensors (input_values1, input_values2) based on whether the second input # is a constant or variable input. values = [create_tensor_data(np.float32, shape=parameters["shape1"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["shape2"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=10) @register_make_test_function() def make_l2norm_tests(options): """Make a set of tests to do l2norm.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], "dim": [0, 1, 2, 3, [2, 3], -2], "epsilon": [None, 1e-12, 1e-3], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) if parameters["epsilon"]: out = tf.nn.l2_normalize( input_tensor, parameters["dim"], epsilon=parameters["epsilon"]) else: out = tf.nn.l2_normalize(input_tensor, parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=9) @register_make_test_function() def make_local_response_norm_tests(options): """Make a set of tests to do local_response_norm.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]], "depth_radius": [None, 0, 1, 3, 5], "bias": [None, 0.3, -0.1], "alpha": [None, 2, -3], "beta": [None, 0.25, 2], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.local_response_normalization( input_tensor, depth_radius=parameters["depth_radius"], bias=parameters["bias"], alpha=parameters["alpha"], beta=parameters["beta"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_pad_tests(options): """Make a set of tests to do pad.""" # TODO(nupurgarg): Add test for tf.uint8. test_parameters = [ # 4D: { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 1, 2, 1], [2, 1, 1, 1]], "paddings": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0], [0, 0], [2, 3]]], "constant_paddings": [True, False], }, # 2D: { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2]], "paddings": [[[0, 1], [2, 3]]], "constant_paddings": [True, False], }, # 1D: { "dtype": [tf.int32], "input_shape": [[1]], "paddings": [[[1, 2]]], "constant_paddings": [False], }, ] def build_graph(parameters): """Build a pad graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get paddings as either a placeholder or constants. if parameters["constant_paddings"]: paddings = parameters["paddings"] input_tensors = [input_tensor] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="padding", shape=shape) input_tensors = [input_tensor, paddings] out = tf.pad(input_tensor, paddings=paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_padv2_tests(options): """Make a set of tests to do padv2.""" # TODO(nupurgarg): Add test for tf.uint8. test_parameters = [ # 4D: { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 1, 2, 1], [2, 1, 1, 1]], "paddings": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0], [0, 0], [2, 3]]], "constant_paddings": [True, False], "constant_values": [0, 2], }, # 2D: { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2]], "paddings": [[[0, 1], [2, 3]]], "constant_paddings": [True, False], "constant_values": [0, 2], }, # 1D: { "dtype": [tf.int32], "input_shape": [[1]], "paddings": [[[0, 1]]], "constant_paddings": [False], "constant_values": [0, 2], }, ] def build_graph(parameters): """Build a pad graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get paddings as either a placeholder or constants. if parameters["constant_paddings"]: paddings = parameters["paddings"] input_tensors = [input_tensor] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="padding", shape=shape) input_tensors = [input_tensor, paddings] out = tf.pad(input_tensor, paddings=paddings, constant_values=parameters["constant_values"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_reshape_tests(options): """Make a set of tests to do reshape.""" # All shapes below are suitable for tensors with 420 elements. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]], "output_shape": [[15, 28], [420], [1, -1, 5, 7], [-1]], "constant_shape": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1]], "output_shape": [[]], "constant_shape": [True, False], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get shape as either a placeholder or constants. if parameters["constant_shape"]: output_shape = parameters["output_shape"] input_tensors = [input_tensor] else: # The shape of the shape tensor. shape_tensor_shape = [len(parameters["output_shape"])] output_shape = tf.placeholder( dtype=tf.int32, name="output_shape", shape=shape_tensor_shape) input_tensors = [input_tensor, output_shape] out = tf.reshape(input_tensor, shape=output_shape) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_shape"]: values.append(np.array(parameters["output_shape"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_shape_tests(options): """Make a set of tests to do shape.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[1, 4]], "new_shape": [[1, 4], [4, 1], [2, 2]], "out_type": [tf.int32, tf.int64], }] def build_graph(parameters): """Build the shape op testing graph.""" # Note that we intentionally leave out the shape from the input placeholder # to prevent the Shape operation from being optimized out during conversion. # TODO(haoliang): Test shape op directly after we have better support for # dynamic input. Currently we need to introduce a Reshape op to prevent # shape being constant-folded. input_value = tf.placeholder( dtype=parameters["input_dtype"], shape=parameters["input_shape"], name="input") shape_of_new_shape = [len(parameters["new_shape"])] new_shape = tf.placeholder( dtype=tf.int32, shape=shape_of_new_shape, name="new_shape") reshaped = tf.reshape(input_value, shape=new_shape) out = tf.shape(reshaped, out_type=parameters["out_type"]) return [input_value, new_shape], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) new_shape = np.array(parameters["new_shape"]) return [input_value, new_shape], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value, new_shape]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_rank_tests(options): """Make a set of tests to do rank.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[], [0], [1, 1, 1, 3], [2, 3, 4, 5], [5, 5], [10]], }] def build_graph(parameters): """Build the rank op testing graph.""" input_value = tf.placeholder(dtype=parameters["input_dtype"], name="input") out = tf.rank(input_value) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_one_hot_tests(options): """Make a set of tests to do one_hot.""" test_parameters = [{ "indices_type": [tf.int32, tf.int64], "indices_shape": [[3], [4, 4], [1, 5], [5, 1]], "axis": [0, 1], "dtype": [tf.int32, tf.int64, tf.float32], "provide_optional_inputs": [True, False], }] def build_graph(parameters): indices = tf.placeholder( dtype=parameters["indices_type"], name="indices", shape=parameters["indices_shape"]) depth = tf.placeholder(dtype=tf.int32, name="depth", shape=()) if not parameters["provide_optional_inputs"]: out = tf.one_hot(indices=indices, depth=depth) return [indices, depth], [out] on_value = tf.placeholder( dtype=parameters["dtype"], name="on_value", shape=()) off_value = tf.placeholder( dtype=parameters["dtype"], name="off_value", shape=()) out = tf.one_hot( indices=indices, depth=depth, on_value=on_value, off_value=off_value, axis=parameters["axis"], dtype=parameters["dtype"]) return [indices, depth, on_value, off_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = [ create_tensor_data( parameters["indices_type"], shape=parameters["indices_shape"], min_value=-1, max_value=10), create_tensor_data(tf.int32, shape=None, min_value=1, max_value=10), ] if parameters["provide_optional_inputs"]: input_values.append( create_tensor_data( parameters["dtype"], shape=None, min_value=1, max_value=10)) input_values.append( create_tensor_data( parameters["dtype"], shape=None, min_value=-1, max_value=0)) return input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_resize_bilinear_tests(options): """Make a set of tests to do resize_bilinear.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [1, 10, 2, 1]], "size": [[1, 1], [4, 3], [2, 2], [5, 6]], "align_corners": [None, True, False], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.image.resize_bilinear(input_tensor, size=parameters["size"], align_corners=parameters["align_corners"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_resize_nearest_neighbor_tests(options): """Make a set of tests to do resize_nearest_neighbor.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [1, 10, 2, 1]], "size": [[1, 1], [4, 3], [2, 2], [5, 6]], "align_corners": [False], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.image.resize_nearest_neighbor( input_tensor, size=parameters["size"], align_corners=parameters["align_corners"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_sigmoid_tests(options): """Make a set of tests to do sigmoid.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.sigmoid(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_softmax_tests(options): """Make a set of tests to do softmax.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [2, 3]], "dim": [-1, 0], }, { "dtype": [tf.float32], "input_shape": [[4, 7]], "dim": [-1, 1], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.softmax(input_tensor, dim=parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_space_to_depth_tests(options): """Make a set of tests to do space_to_depth.""" test_parameters = [{ "dtype": [tf.float32, tf.int32, tf.uint8, tf.int64], "input_shape": [[2, 12, 24, 1]], "block_size": [2, 3, 4], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.space_to_depth(input_tensor, block_size=parameters["block_size"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_depth_to_space_tests(options): """Make a set of tests to do depth_to_space.""" test_parameters = [{ "dtype": [tf.float32, tf.int32, tf.uint8, tf.int64], "input_shape": [[2, 3, 4, 16]], "block_size": [2, 4], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.depth_to_space(input_tensor, block_size=parameters["block_size"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_space_to_batch_nd_tests(options): """Make a set of tests to do space_to_batch_nd.""" # TODO(nupurgarg): Add test for uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2, 2, 3], [2, 2, 4, 1]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, { "dtype": [tf.float32], "input_shape": [[2, 3, 7, 3]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[1, 4, 4, 4, 1, 1]], "block_shape": [[2, 2, 2]], "paddings": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, ] def build_graph(parameters): """Build a space_to_batch graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get paddings either as a const or as a placeholder (tensor). if parameters["constant_paddings"]: paddings = parameters["paddings"] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="paddings", shape=shape) input_tensors.append(paddings) out = tf.space_to_batch_nd(input_tensor, block_shape, paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=56) @register_make_test_function() def make_batch_to_space_nd_tests(options): """Make a set of tests to do batch_to_space_nd.""" test_parameters = [ { "dtype": [tf.float32, tf.int64, tf.int32], "input_shape": [[12, 3, 3, 1]], "block_shape": [[1, 4], [2, 2], [3, 4]], "crops": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, # Single batch (no-op) { "dtype": [tf.float32], "input_shape": [[1, 3, 3, 1]], "block_shape": [[1, 1]], "crops": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True], "constant_crops": [True], }, # Non-4D use case: 1 batch dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[8, 2, 2, 2, 1, 1]], "block_shape": [[2, 2, 2]], "crops": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, ] def build_graph(parameters): """Build a batch_to_space graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get crops either as a const or as a placeholder (tensor). if parameters["constant_crops"]: crops = parameters["crops"] else: shape = [len(parameters["crops"]), 2] crops = tf.placeholder(dtype=tf.int32, name="crops", shape=shape) input_tensors.append(crops) out = tf.batch_to_space_nd(input_tensor, block_shape, crops) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_crops"]: values.append(np.array(parameters["crops"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_transpose_tests(options): """Make a set of tests to do transpose.""" # TODO(nupurgarg): Add test for uint8. test_parameters = [{ "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[2, 2, 3]], "perm": [[0, 1, 2], [0, 2, 1]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4]], "perm": [[0, 1, 2, 3], [3, 0, 1, 2]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4, 5]], "perm": [[4, 3, 2, 1, 0]], "constant_perm": [True, False], }] def build_graph(parameters): """Build a transpose graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_perm"]: perm = parameters["perm"] input_tensors = [input_tensor] else: shape = [len(parameters["perm"]), 2] perm = tf.placeholder(dtype=tf.int32, name="perm", shape=shape) input_tensors = [input_tensor, perm] out = tf.transpose(input_tensor, perm=perm) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_perm"]: values.append(np.array(parameters["perm"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=9) @register_make_test_function() def make_squeeze_tests(options): """Make a set of tests to do squeeze.""" test_parameters = [{ "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 2, 1, 3, 1, 4, 1, 1]], "axis": [ None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2], [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6], [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5] ], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1]], "axis": [None, [], [0], [-1]], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 1, 1, 1, 1]], "axis": [None, [], [0], [3, 0], [-2, 0, 3, 2]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.squeeze(input_tensor, axis=parameters["axis"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=12) @register_make_test_function() def make_squeeze_transpose_tests(options): """Make a set of tests to do squeeze followed by transpose.""" test_parameters = [{ "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 4, 10, 1]], "axis": [[-1], [3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.squeeze(input_tensor, axis=parameters["axis"]) out = tf.transpose(out, perm=[1, 2]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=0) def _make_strided_slice_tests(options, test_parameters, expected_tf_failures=0): """Utility function to make strided_slice_tests based on parameters.""" def build_graph(parameters): """Build graph for stride_slice test.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_indices"]: begin = parameters["begin"] end = parameters["end"] strides = parameters["strides"] tensors = [input_tensor] else: begin = tf.placeholder( dtype=parameters["index_type"], name="begin", shape=[len(parameters["input_shape"])]) end = tf.placeholder( dtype=parameters["index_type"], name="end", shape=[len(parameters["input_shape"])]) strides = ( tf.placeholder( dtype=parameters["index_type"], name="strides", shape=[len(parameters["input_shape"])]) if parameters["strides"] is not None else None) tensors = [input_tensor, begin, end] if strides is not None: tensors.append(strides) out = tf.strided_slice( input_tensor, begin, end, strides, begin_mask=parameters["begin_mask"], end_mask=parameters["end_mask"]) return tensors, [out] def build_inputs(parameters, sess, inputs, outputs): """Build inputs for stride_slice test.""" input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) index_type = TF_TYPE_INFO[parameters["index_type"]][0] values = [input_values] if not parameters["constant_indices"]: begin_values = np.array(parameters["begin"]).astype(index_type) end_values = np.array(parameters["end"]).astype(index_type) stride_values = ( np.array(parameters["strides"]).astype(index_type) if parameters["strides"] is not None else None) values.append(begin_values) values.append(end_values) if stride_values is not None: values.append(stride_values) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=expected_tf_failures) @register_make_test_function() def make_strided_slice_tests(options): """Make a set of tests to do strided_slice.""" # TODO(soroosh): add test/support for uint8. test_parameters = [ # 4-D (basic cases with const/non-const indices). { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "strides": [None, [2, 1, 3, 1]], "begin": [[0, 0, 0, 0]], "end": [[12, 2, 2, 5]], "begin_mask": [None], "end_mask": [None], "shrink_axis_mask": [None], "constant_indices": [False, True], }, # 4-D with non-trivial begin & end. { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "begin": [[0, 0, 0, 0], [1, 0, 1, 0]], "end": [[8, 2, 2, 3], [12, 2, 2, 5]], "strides": [None, [2, 1, 3, 1]], "begin_mask": [None, 8], "end_mask": [None, 3], "shrink_axis_mask": [None, 15, -1], "constant_indices": [True], }, # Begin, end, strides dim are different from input shape { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "begin": [[0]], "end": [[1]], "strides": [None, [1]], "begin_mask": [0], "end_mask": [0], "shrink_axis_mask": [1], "constant_indices": [True], }, # 2-D { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, 0]], "end": [[2, 2]], "strides": [None, [2, 2]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False, True], }, # Negative strides { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, -1]], "end": [[2, -3]], "strides": [[1, -1]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False], }, ] _make_strided_slice_tests(options, test_parameters, expected_tf_failures=2) @register_make_test_function() def make_strided_slice_1d_exhaustive_tests(options): """Make a set of exhaustive tests for 1D strided_slice.""" test_parameters = [ # 1-D Exhaustive { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[3]], "begin": [[-2], [-1], [0], [1], [2]], "end": [[-2], [-1], [0], [1], [2]], "strides": [[-2], [-1], [1], [2]], "begin_mask": [0, 1], "end_mask": [0, 1], "shrink_axis_mask": [0], "constant_indices": [False], }, ] _make_strided_slice_tests(options, test_parameters) # TODO(b/137615945): Expand the test coverage of this one and remove the old # ones. @register_make_test_function() def make_strided_slice_np_style_tests(options): """Make a set of tests to test strided_slice in np style.""" test_parameters = [ { "dtype": [tf.float32], "shape": [[12, 7], [33, 1]], "spec": [[slice(3, 7, 2), slice(None)], [tf.newaxis, slice(3, 7, 1), tf.newaxis, slice(None)], [slice(1, 5, 1), slice(None)]], }, # 1-D case { "dtype": [tf.float32], "shape": [[44]], "spec": [[slice(3, 7, 2)], [tf.newaxis, slice(None)]], }, # Shrink mask. { "dtype": [tf.float32], "shape": [[21, 15, 7]], "spec": [[slice(3, 7, 2), slice(None), 2]], }, # Ellipsis. { "dtype": [tf.float32], "shape": [[21, 15, 7]], "spec": [[slice(3, 7, 2), Ellipsis]], }, # All combinations. { "dtype": [tf.float32], "shape": [[21, 15, 7]], "spec": [[tf.newaxis, slice(3, 7, 2), slice(None), Ellipsis]], }, ] def build_strided_slice_spec(parameters): """Build strided_slice spec. Args: parameters: Test configurations. Returns: strided_slice spec, e.g., [2:3, :] or [tf.newaxis, :, tf.newaxis]. """ def build_graph(parameters): """Build a simple graph with np style strided_slice.""" input_value = tf.placeholder( dtype=parameters["dtype"], shape=parameters["shape"]) out = input_value.__getitem__(parameters["spec"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) # For verifying https://github.com/tensorflow/tensorflow/issues/23599 # TODO(chaomei): refactor the test to cover more cases, like negative stride, # negative array index etc. @register_make_test_function() def make_resolve_constant_strided_slice_tests(options): """Make a set of tests to show strided_slice yields incorrect results.""" test_parameters = [{ "unused_iteration_counter": [1], }] def build_graph(parameters): """Build the strided_slice op testing graph.""" del parameters input_values = tf.placeholder(dtype=tf.float32, shape=[4, 2]) data = tf.constant([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]], tf.float32) return [input_values], [input_values + data[:, :2]] def build_inputs(parameters, sess, inputs, outputs): del parameters input_values = np.zeros([4, 2], dtype=np.float32) return [input_values], sess.run( outputs, feed_dict={inputs[0]: input_values}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_lstm_tests(options): """Make a set of tests to do basic Lstm cell.""" test_parameters = [ { "dtype": [tf.float32], "num_batchs": [1], "time_step_size": [1], "input_vec_size": [3], "num_cells": [4], "split_tflite_lstm_inputs": [False], }, ] def build_graph(parameters): """Build a simple graph with BasicLSTMCell.""" num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] num_cells = parameters["num_cells"] inputs_after_split = [] for i in xrange(time_step_size): one_timestamp_input = tf.placeholder( dtype=parameters["dtype"], name="split_{}".format(i), shape=[num_batchs, input_vec_size]) inputs_after_split.append(one_timestamp_input) # Currently lstm identifier has a few limitations: only supports # forget_bias == 0, inner state activation == tanh. # TODO(zhixianyan): Add another test with forget_bias == 1. # TODO(zhixianyan): Add another test with relu as activation. lstm_cell = tf.nn.rnn_cell.BasicLSTMCell( num_cells, forget_bias=0.0, state_is_tuple=True) cell_outputs, _ = rnn.static_rnn( lstm_cell, inputs_after_split, dtype=tf.float32) out = cell_outputs[-1] return inputs_after_split, [out] def build_inputs(parameters, sess, inputs, outputs): """Feed inputs, assign variables, and freeze graph.""" with tf.variable_scope("", reuse=True): kernel = tf.get_variable("rnn/basic_lstm_cell/kernel") bias = tf.get_variable("rnn/basic_lstm_cell/bias") kernel_values = create_tensor_data( parameters["dtype"], [kernel.shape[0], kernel.shape[1]], -1, 1) bias_values = create_tensor_data(parameters["dtype"], [bias.shape[0]], 0, 1) sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values))) num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] input_values = [] for _ in xrange(time_step_size): tensor_data = create_tensor_data(parameters["dtype"], [num_batchs, input_vec_size], 0, 1) input_values.append(tensor_data) out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values))) return input_values, out # TODO(zhixianyan): Automatically generate rnn_states for lstm cell. extra_toco_options = ExtraTocoOptions() extra_toco_options.rnn_states = ( "{state_array:rnn/BasicLSTMCellZeroState/zeros," "back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4}," "{state_array:rnn/BasicLSTMCellZeroState/zeros_1," "back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}") make_zip_of_tests( options, test_parameters, build_graph, build_inputs, extra_toco_options, use_frozen_graph=True) def make_l2_pool(input_tensor, ksize, strides, padding, data_format): """Given an input perform a sequence of TensorFlow ops to produce l2pool.""" return tf.sqrt(tf.nn.avg_pool( tf.square(input_tensor), ksize=ksize, strides=strides, padding=padding, data_format=data_format)) @register_make_test_function() def make_topk_tests(options): """Make a set of tests to do topk.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[10], [5, 20]], "input_k": [None, 1, 3], }] def build_graph(parameters): """Build the topk op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) if parameters["input_k"] is not None: k = tf.placeholder(dtype=tf.int32, name="input_k", shape=[]) inputs = [input_value, k] else: k = tf.constant(3, name="k") inputs = [input_value] out = tf.nn.top_k(input_value, k) return inputs, [out[1]] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) if parameters["input_k"] is not None: k = np.array(parameters["input_k"], dtype=np.int32) return [input_value, k], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value, k]))) else: return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_arg_min_max_tests(options): """Make a set of tests to do arg_max.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[], [1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]], "output_type": [tf.int32, tf.int64], "is_arg_max": [True], }] def build_graph(parameters): """Build the topk op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) axis = random.randint(0, max(len(parameters["input_shape"]) - 1, 0)) if parameters["is_arg_max"]: out = tf.arg_max(input_value, axis, output_type=parameters["output_type"]) else: out = tf.arg_min(input_value, axis, output_type=parameters["output_type"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=4) @register_make_test_function() def make_equal_tests(options): """Make a set of tests to do equal.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([], []), ([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the equal op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.equal(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=3) @register_make_test_function() def make_not_equal_tests(options): """Make a set of tests to do not equal.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the not euqal op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.not_equal(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=3) @register_make_test_function() def make_greater_tests(options): """Make a set of tests to do greater.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the greater op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.greater(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=3) @register_make_test_function() def make_greater_equal_tests(options): """Make a set of tests to do greater_equal.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the greater_equal op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.greater_equal(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=3) @register_make_test_function() def make_less_tests(options): """Make a set of tests to do less.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the less op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.less(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=3) @register_make_test_function() def make_less_equal_tests(options): """Make a set of tests to do less_equal.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the less_equal op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.less_equal(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=3) @register_make_test_function() def make_floor_tests(options): """Make a set of tests to do floor.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]], }] def build_graph(parameters): """Build the floor op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape"]) out = tf.floor(input_value) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run(outputs, feed_dict={inputs[0]: input_value}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_ceil_tests(options): """Make a set of tests to do ceil.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]], }] def build_graph(parameters): """Build the ceil op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape"]) out = tf.ceil(input_value) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict={inputs[0]: input_value}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_round_tests(options): """Build the round op testing graph.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]], }] def build_graph(parameters): """Build the round op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape"]) out = tf.round(input_value) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run(outputs, feed_dict={inputs[0]: input_value}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_neg_tests(options): """Make a set of tests to do neg.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [5], []], }] def build_graph(parameters): """Build the neg op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.negative(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [values], sess.run(outputs, feed_dict=dict(zip(inputs, [values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_zeros_like_tests(options): """Make a set of tests to do zeros_like.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]], }] def build_graph(parameters): """Build the zeros_like op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) zeros = tf.zeros_like(input_tensor) # This maximum node is so that toco can perform the constants-propagation # through the above zeros_like, which it can't do if the output of the # zeros_like as an output of the whole graphs (graph outputs can't be # constants). If toco does not perform such constants-propagation then # the resulting tflite graph retains the zeros_like as a Fill op, which # is unsupported by TFLite, even as a custom op. out = tf.maximum(zeros, input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [values], sess.run(outputs, feed_dict=dict(zip(inputs, [values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_cast_tests(options): """Generate examples for cast.""" test_parameters = [{ "input_dtype": [tf.int32], "output_dtype": [tf.float32], "input_shape": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]], }] def build_graph(parameters): """Build the cast testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.cast(input_value, parameters["output_dtype"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) def _make_elementwise_tests(op): """Make a set of tests to do element-wise operations.""" def f(options): """Actual function that generates examples.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]], }] def build_graph(parameters): """Build the unary op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape"]) out = op(input_value) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict={inputs[0]: input_value}) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) return f @register_make_test_function() def make_sin_tests(options): """Make a set of tests to do sin.""" return _make_elementwise_tests(tf.sin)(options) @register_make_test_function() def make_log_tests(options): """Make a set of tests to do log.""" return _make_elementwise_tests(tf.log)(options) @register_make_test_function() def make_sqrt_tests(options): """Make a set of tests to do sqrt.""" return _make_elementwise_tests(tf.sqrt)(options) @register_make_test_function() def make_rsqrt_tests(options): """Make a set of tests to do 1/sqrt.""" return _make_elementwise_tests(tf.rsqrt)(options) @register_make_test_function() def make_square_tests(options): """Make a set of tests to do square.""" return _make_elementwise_tests(tf.square)(options) @register_make_test_function() def make_where_tests(options): """Make a set of tests to do where.""" test_parameters = [ { "input_dtype": [tf.float32, tf.int32], "input_shape_set": [([1, 2, 3, 4], [1, 2, 3, 4]),], "use_where_v2": [False, True], }, { "input_dtype": [tf.float32, tf.int32], "input_shape_set": [([1, 2, 3, 4], [1, 2, 3, 1]),], "use_where_v2": [True], }, ] def build_graph(parameters): """Build the where op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_set"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input3", shape=parameters["input_shape_set"][1]) less = tf.less(input_value1, input_value2) where = tf.where_v2 if parameters["use_where_v2"] else tf.where out = where(less, input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_set"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_set"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_slice_tests(options): """Make a set of tests to do slice.""" # TODO(renjieliu): add test/support for uint8. test_parameters = [ # 4-D { "dtype": [tf.float32, tf.int32, tf.int64, tf.string], "index_type": [tf.int32, tf.int64], "input_shape": [[12, 2, 2, 5]], "begin": [[0, 0, 0, 0], [1, 0, 1, 0]], "size": [[8, 2, 2, 3], [11, 2, 1, 5]], }, # 2-D { "dtype": [tf.float32, tf.int32, tf.int64, tf.string], "index_type": [tf.int32, tf.int64], "input_shape": [[2, 3]], "begin": [[0, 0], [1, 0]], "size": [[2, 3], [2, 2]], }, # 4-D with size -1 { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[4, 4, 4, 4]], "begin": [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], "size": [[-1, 1, 1, 1], [1, -1, 1, 1], [1, 1, -1, 1], [1, 1, 1, -1]], }, # last dimension out of index { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[4, 4, 4]], "begin": [[3, 3, 4]], "size": [[-1, -1, -1]], }, ] def build_graph(parameters): """Build graph for slice test.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) begin = tf.placeholder( dtype=parameters["index_type"], name="begin", shape=[len(parameters["input_shape"])]) size = tf.placeholder( dtype=parameters["index_type"], name="size", shape=[len(parameters["input_shape"])]) tensors = [input_tensor, begin, size] out = tf.slice(input_tensor, begin, size) return tensors, [out] def build_inputs(parameters, sess, inputs, outputs): """Build inputs for slice test.""" input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) index_type = TF_TYPE_INFO[parameters["index_type"]][0] begin_values = np.array(parameters["begin"]).astype(index_type) size_values = np.array(parameters["size"]).astype(index_type) values = [input_values, begin_values, size_values] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=24) @register_make_test_function() def make_conv2d_transpose_tests(options): """Make a set of tests to do transpose_conv.""" test_parameters = [{ "input_shape": [[1, 50, 54, 3]], "filter_shape": [[1, 1, 8, 3], [1, 2, 8, 3], [1, 3, 8, 3], [1, 4, 8, 3]], "output_shape": [[1, 100, 108, 8]], "dynamic_output_shape": [True, False], }, { "input_shape": [[1, 16, 1, 512]], "filter_shape": [[4, 1, 512, 512]], "output_shape": [[1, 32, 1, 512]], "dynamic_output_shape": [True, False], }, { "input_shape": [[1, 128, 128, 1]], "filter_shape": [[4, 4, 1, 1]], "output_shape": [[1, 256, 256, 1]], "dynamic_output_shape": [True, False], }] def build_graph(parameters): """Build a transpose_conv graph given `parameters`.""" input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) filter_tensor = tf.placeholder( dtype=tf.float32, name="filter", shape=parameters["filter_shape"]) input_tensors = [input_tensor, filter_tensor] if parameters["dynamic_output_shape"]: output_shape = tf.placeholder(dtype=tf.int32, shape=[4]) input_tensors.append(output_shape) else: output_shape = parameters["output_shape"] out = tf.nn.conv2d_transpose( input_tensor, filter_tensor, output_shape=output_shape, padding="SAME", strides=(1, 2, 2, 1)) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(np.float32, parameters["input_shape"]), create_tensor_data(np.float32, parameters["filter_shape"]) ] if parameters["dynamic_output_shape"]: values.append(np.array(parameters["output_shape"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) # Since compute output_shape is fairly complicated for # tf.nn.conv2d_transpose input_sizes argument, so we here first perform a # "conv2d" operation to get the output, then we use the output to feed in # tf.nn.conv2d_backprop_input. # This test will depend on the "conv2d" operation's correctness. @register_make_test_function() def make_transpose_conv_tests(options): """Make a set of tests to do transpose_conv.""" # Tensorflow only supports equal strides test_parameters = [{ "input_shape": [[1, 3, 4, 1], [1, 10, 10, 3], [3, 20, 20, 1]], "filter_size": [[1, 1], [1, 2], [3, 3]], "strides": [[1, 1, 1, 1], [1, 3, 3, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], "channel_multiplier": [1, 2], }] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_size"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a transpose_conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) conv_outputs = tf.nn.conv2d( input_tensor, filter_input, strides=parameters["strides"], padding=parameters["padding"], data_format=parameters["data_format"]) out = tf.nn.conv2d_backprop_input( input_shape, filter_input, conv_outputs, strides=parameters["strides"], padding=parameters["padding"], data_format=parameters["data_format"]) input_tensors = [input_tensor, filter_input] return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): input_shape, filter_shape = get_tensor_shapes(parameters) values = [ create_tensor_data(np.float32, input_shape), create_tensor_data(np.float32, filter_shape) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_tile_tests(options): """Make a set of tests to do tile.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.bool], "input_shape": [[3, 2, 1], [2, 2, 2]], "multiplier_dtype": [tf.int32, tf.int64], "multiplier_shape": [[3]] }] def build_graph(parameters): """Build the tile op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], shape=parameters["input_shape"], name="input") multiplier_value = tf.placeholder( dtype=parameters["multiplier_dtype"], shape=parameters["multiplier_shape"], name="multiplier") out = tf.tile(input_value, multiplier_value) return [input_value, multiplier_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) multipliers_value = create_tensor_data( parameters["multiplier_dtype"], parameters["multiplier_shape"], min_value=0) return [input_value, multipliers_value], sess.run( outputs, feed_dict={ inputs[0]: input_value, inputs[1]: multipliers_value }) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_expand_dims_tests(options): """Make a set of tests to do expand_dims.""" test_parameters = [{ "input_type": [tf.float32, tf.int32], "input_shape": [[5, 4]], "axis_value": [0, 1, 2, -1, -2, -3], "constant_axis": [True, False], }] def build_graph(parameters): """Build the where op testing graph.""" inputs = [] input_value = tf.placeholder( dtype=parameters["input_type"], name="input", shape=parameters["input_shape"]) inputs.append(input_value) if parameters["constant_axis"]: axis_value = tf.constant( parameters["axis_value"], dtype=tf.int32, shape=[1]) else: axis_value = tf.placeholder(dtype=tf.int32, name="axis", shape=[1]) inputs.append(axis_value) out = tf.expand_dims(input_value, axis=axis_value) return inputs, [out] def build_inputs(parameters, sess, inputs, outputs): input_values = [] input_values.append( create_tensor_data(parameters["input_type"], parameters["input_shape"])) if not parameters["constant_axis"]: input_values.append(np.array([parameters["axis_value"]], dtype=np.int32)) return input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_sparse_to_dense_tests(options): """Make a set of tests to do sparse to dense.""" test_parameters = [{ "value_dtype": [tf.float32, tf.int32, tf.int64], "index_dtype": [tf.int32, tf.int64], "value_count": [1, 3, 6, 8], "dense_shape": [[15], [3, 10], [4, 4, 4, 4], [7, 10, 9]], "default_value": [0, -1], "value_is_scalar": [True, False], }] # Return a single value for 1-D dense shape, but a tuple for other shapes. def generate_index(dense_shape): if len(dense_shape) == 1: return np.random.randint(dense_shape[0]) else: index = [] for shape in dense_shape: index.append(np.random.randint(shape)) return tuple(index) def build_graph(parameters): """Build the sparse_to_dense op testing graph.""" dense_shape = parameters["dense_shape"] # Special handle for value_is_scalar case. # value_count must be 1. if parameters["value_is_scalar"] and parameters["value_count"] == 1: value = tf.placeholder( name="value", dtype=parameters["value_dtype"], shape=()) else: value = tf.placeholder( name="value", dtype=parameters["value_dtype"], shape=[parameters["value_count"]]) indices = set() while len(indices) < parameters["value_count"]: indices.add(generate_index(dense_shape)) indices = tf.constant(tuple(indices), dtype=parameters["index_dtype"]) # TODO(renjieliu): Add test for validate_indices case. out = tf.sparse_to_dense( indices, dense_shape, value, parameters["default_value"], validate_indices=False) return [value], [out] def build_inputs(parameters, sess, inputs, outputs): if parameters["value_is_scalar"] and parameters["value_count"] == 1: input_value = create_scalar_data(parameters["value_dtype"]) else: input_value = create_tensor_data(parameters["value_dtype"], [parameters["value_count"]]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_pack_tests(options): """Make a set of tests to do stack.""" test_parameters = [ # Avoid creating all combinations to keep the test size small. { "dtype": [tf.float32], "base_shape": [[3, 4, 3], [3, 4], [5]], "num_tensors": [1, 2, 3, 4, 5, 6], "axis": [0, 1, 2, 3], "additional_shape": [1, 2, 3], }, { "dtype": [tf.int32], "base_shape": [[3, 4, 3], [3, 4], [5]], "num_tensors": [6], "axis": [0, 1, 2, 3], "additional_shape": [1, 2, 3], }, { "dtype": [tf.int64], "base_shape": [[3, 4, 3], [3, 4], [5]], "num_tensors": [5], "axis": [0, 1, 2, 3], "additional_shape": [1, 2, 3], } ] def get_shape(parameters): """Return a tweaked version of 'base_shape'.""" axis = parameters["axis"] shape = parameters["base_shape"][:] if axis < len(shape): shape[axis] += parameters["additional_shape"] return shape def build_graph(parameters): all_tensors = [] for n in range(0, parameters["num_tensors"]): input_tensor = tf.placeholder( dtype=parameters["dtype"], name=("input%d" % n), shape=get_shape(parameters)) all_tensors.append(input_tensor) out = tf.stack(all_tensors, parameters["axis"]) return all_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): all_values = [] for _ in range(0, parameters["num_tensors"]): input_values = create_tensor_data(np.float32, get_shape(parameters)) all_values.append(input_values) return all_values, sess.run( outputs, feed_dict=dict(zip(inputs, all_values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=72) @register_make_test_function() def make_unpack_tests(options): """Make a set of tests to do unstack.""" test_parameters = [{ "base_shape": [[3, 4, 3], [3, 4], [5, 6, 7, 8]], "axis": [0, 1, 2, 3], }] def get_valid_axis(parameters): """Return a tweaked version of 'axis'.""" axis = parameters["axis"] shape = parameters["base_shape"][:] while axis > len(shape) - 1: axis -= 1 return axis def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name=("input"), shape=parameters["base_shape"]) outs = tf.unstack(input_tensor, axis=get_valid_axis(parameters)) return [input_tensor], [outs[0]] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(np.float32, shape=parameters["base_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_range_tests(options): """Make a set of tests to do range.""" test_parameters = [{ "dtype": [tf.int32, tf.float32], "offset": [10, 100, 1000], "delta": [1, 2, 3, 4, -1, -2, -3, -4], }] def build_graph(parameters): """Build the range op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name=("start"), shape=[]) if parameters["delta"] < 0: offset = parameters["offset"] * -1 else: offset = parameters["offset"] delta = parameters["delta"] limit_tensor = input_tensor + offset delta_tensor = tf.constant(delta, dtype=parameters["dtype"]) out = tf.range(input_tensor, limit_tensor, delta_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_scalar_data(parameters["dtype"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_fill_tests(options): """Make a set of tests to do fill.""" test_parameters = [{ "dims_dtype": [tf.int32, tf.int64], "dims_shape": [[], [1], [3], [3, 3]], "value_dtype": [tf.int32, tf.int64, tf.float32], }] def build_graph(parameters): """Build the fill op testing graph.""" input1 = tf.placeholder( dtype=parameters["dims_dtype"], name="dims", shape=parameters["dims_shape"]) input2 = tf.placeholder( dtype=parameters["value_dtype"], name="value", shape=[]) out = tf.fill(input1, input2) return [input1, input2], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = create_tensor_data(parameters["dims_dtype"], parameters["dims_shape"], 1) input2 = create_scalar_data(parameters["value_dtype"]) return [input1, input2], sess.run( outputs, feed_dict=dict(zip(inputs, [input1, input2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=12) def _make_logical_tests(op): """Make a set of tests to do logical operations.""" def logical(options, expected_tf_failures=0): """Generate examples.""" test_parameters = [{ "input_shape_pair": [([], []), ([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the logical testing graph.""" input_value1 = tf.placeholder( dtype=tf.bool, name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=tf.bool, name="input2", shape=parameters["input_shape_pair"][1]) out = op(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(tf.bool, parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(tf.bool, parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, expected_tf_failures=expected_tf_failures) return logical @register_make_test_function() def make_logical_or_tests(options): """Make a set of tests to do logical_or.""" return _make_logical_tests(tf.logical_or)(options, expected_tf_failures=1) @register_make_test_function() def make_logical_and_tests(options): """Make a set of tests to do logical_and.""" return _make_logical_tests(tf.logical_and)(options, expected_tf_failures=1) @register_make_test_function() def make_logical_xor_tests(options): """Make a set of tests to do logical_xor. Test logical_not as well. """ return _make_logical_tests(tf.logical_xor)(options, expected_tf_failures=1) @register_make_test_function() def make_mirror_pad_tests(options): """Make a set of tests to do mirror_pad.""" test_parameters = [ { "input_shape": [[2, 3]], "padding_matrix": [[[1, 1], [2, 1]]], "mode": ["REFLECT"], "type": ["const"] }, { "input_shape": [[2, 3]], "padding_matrix": [[[1, 1], [1, 1]]], "mode": ["REFLECT"], "type": ["const"] }, { "input_shape": [[2, 3]], "padding_matrix": [[[1, 1], [2, 1]]], "mode": ["SYMMETRIC"], "type": ["placeholder"] }, { "input_shape": [[2, 3]], "padding_matrix": [[[1, 1], [2, 1]]], "mode": ["REFLECT"], "type": ["placeholder"] }, { "input_shape": [[3]], "padding_matrix": [[[0, 2]]], "mode": ["SYMMETRIC"], "type": ["placeholder"] }, { "input_shape": [[3]], "padding_matrix": [[[0, 2]]], "mode": ["SYMMETRIC"], "type": ["const"] }, { "input_shape": [[3]], "padding_matrix": [[[0, 2]]], "mode": ["REFLECT"], "type": ["const"] }, { "input_shape": [[3, 2, 4, 5]], "padding_matrix": [[[1, 1], [2, 2], [1, 1], [1, 1]]], "mode": ["SYMMETRIC"], "type": ["placeholder"] }, ] def build_graph(parameters): """Build the graph for the test case.""" input_tensor = tf.placeholder( dtype=tf.int32, name="input", shape=parameters["input_shape"]) if parameters["type"] != "const": padding_matrix = tf.placeholder( dtype=tf.int32, name="padding", shape=[len(parameters["input_shape"]), 2]) input_tensors = [input_tensor, padding_matrix] else: padding_matrix = tf.constant(np.array(parameters["padding_matrix"])) input_tensors = [input_tensor] output = tf.pad( input_tensor, paddings=padding_matrix, mode=parameters["mode"]) return input_tensors, [output] def build_inputs(parameters, sess, inputs, outputs): input_values = [create_tensor_data(tf.int32, parameters["input_shape"])] if parameters["type"] != "const": input_values.append(np.array(parameters["padding_matrix"])) return input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_unroll_batch_matmul_tests(options): """Make a set of tests to test unroll_batch_matmul.""" # The test cases below requires broadcasting support (BatchMatMulV2 semantic), # whis isn't supported as of this change. broadcast_shape_params = [ # Simple broadcast. [(1, 2, 3), (3, 5), False, False], # Empty batch broadcast. [(2, 5, 3), (3, 7), False, False], # Single batch with non-empty batch broadcast. [(1, 5, 3), (4, 3, 7), False, False], # Broadcast both operands [(3, 1, 5, 3), (1, 4, 3, 7), False, False], ] test_parameters = [{ "dtype": [tf.float32], "shape": [ [(2, 2, 3), (2, 3, 2), False, False], [(2, 2, 3), (2, 3, 2), True, True], [(2, 2, 3), (2, 2, 3), False, True], [(2, 2, 3), (2, 2, 3), True, False], [(4, 2, 2, 3), (4, 2, 3, 2), False, False], [(4, 2, 2, 3), (4, 2, 3, 2), True, True], [(4, 2, 2, 3), (4, 2, 2, 3), False, True], [(4, 2, 2, 3), (4, 2, 2, 3), True, False] ] + broadcast_shape_params, # TODO(b/130887442): Improve the forward compatibility tests for every # ops. "forward_compatibility_test": [False, True], }] def build_graph(parameters): """Build the batch_matmul op testing graph.""" def _build_graph(): input_tensor1 = tf.placeholder( dtype=parameters["dtype"], shape=parameters["shape"][0]) input_tensor2 = tf.placeholder( dtype=parameters["dtype"], shape=parameters["shape"][1]) # Should be unrolled and replaced with fully_connected ops in the end. out = tf.matmul( input_tensor1, input_tensor2, transpose_a=parameters["shape"][2], transpose_b=parameters["shape"][3]) return [input_tensor1, input_tensor2], [out] if parameters["forward_compatibility_test"]: # This is hardcoded to the date after MatMulV2 is activated. # TODO(b/130887442): Improve the forward compatibility tests for every # ops, and remove the hardcoded date. with tf.compat.forward_compatibility_horizon(2019, 4, 26): return _build_graph() else: return _build_graph() def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data( parameters["dtype"], shape=parameters["shape"][0]) input_value2 = create_tensor_data( parameters["dtype"], shape=parameters["shape"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_placeholder_with_default_tests(options): """Make a set of tests to test placeholder_with_default.""" test_parameters = [{ "dtype": [tf.float32, tf.int32, tf.int64], }] def build_graph(parameters): """Build the placeholder_with_default testing graph.""" const_node = tf.constant( [1, 2, 2, 0], shape=[2, 2], dtype=parameters["dtype"]) input_tensor = tf.placeholder_with_default( const_node, shape=[2, 2], name="input") out = tf.equal(input_tensor, const_node, name="output") return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): numpy_type = TF_TYPE_INFO[parameters["dtype"]][0] input_value = np.array([[1, 0], [2, 1]], numpy_type) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_unique_tests(options): """Make a set of tests for Unique op.""" test_parameters = [ { "input_shape": [[1]], "index_type": [tf.int32, tf.int64, None], "input_values": [3] }, { "input_shape": [[5]], "index_type": [tf.int32, tf.int64], "input_values": [[3, 2, 1, 2, 3]] }, { "input_shape": [[7]], "index_type": [tf.int32, tf.int64], "input_values": [[1, 1, 1, 1, 1, 1, 1]] }, { "input_shape": [[5]], "index_type": [tf.int32, tf.int64], "input_values": [[3, 2, 1, 0, -1]] }] def build_graph(parameters): """Build the graph for the test case.""" input_tensor = tf.placeholder( dtype=tf.int32, name="input", shape=parameters["input_shape"]) if parameters["index_type"] is None: output = tf.unique(input_tensor) else: output = tf.unique(input_tensor, parameters["index_type"]) return [input_tensor], output def build_inputs(parameters, sess, inputs, outputs): input_values = [create_tensor_data(tf.int32, parameters["input_shape"])] return input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_reverse_v2_tests(options): """Make a set of tests to do reverse_v2.""" test_parameters = [{ "base_shape": [[3, 4, 3], [3, 4], [5, 6, 7, 8]], "axis": [0, 1, 2, 3], }] def get_valid_axis(parameters): """Return a tweaked version of 'axis'.""" axis = parameters["axis"] shape = parameters["base_shape"][:] while axis > len(shape) - 1: axis -= 1 return axis def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name=("input"), shape=parameters["base_shape"]) outs = tf.reverse(input_tensor, axis=[get_valid_axis(parameters)]) return [input_tensor], [outs] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(np.float32, shape=parameters["base_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_reverse_sequence_tests(options): """Make a set of tests to do reverse_sequence.""" test_parameters = [ { "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[8, 4, 5, 5, 6], [4, 4, 3, 5]], "seq_lengths": [[2, 2, 2, 2], [2, 1, 1, 0]], "seq_axis": [0, 3], "batch_axis": [1] }, { "input_dtype": [tf.float32], "input_shape": [[2, 4, 5, 5, 6]], "seq_lengths": [[2, 1]], "seq_axis": [2], "batch_axis": [0] }, { "input_dtype": [tf.float32], "input_shape": [[4, 2]], "seq_lengths": [[3, 1]], "seq_axis": [0], "batch_axis": [1] }] def build_graph(parameters): input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) outs = tf.reverse_sequence( input_value, seq_lengths=parameters["seq_lengths"], batch_axis=parameters["batch_axis"], seq_axis=parameters["seq_axis"]) return [input_value], [outs] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_matrix_diag_tests(options): """Make a set of tests for tf.linalg.diag op.""" test_parameters = [ { "input_shape": [[3], [2, 3], [3, 4, 5], [2, 4, 6, 8]], "input_dtype": [tf.int32, tf.float32], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) outs = tf.matrix_diag(input_tensor) return [input_tensor], [outs] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_matrix_set_diag_tests(options): """Make a set of tests for tf.linalg.set_diag op.""" test_parameters = [ { "input_diag_shapes": [([3, 3], [3]), ([2, 3], [2]), ([2, 4, 4], [2, 4]), ([3, 4, 5, 6], [3, 4, 5])], "input_dtype": [tf.int32, tf.float32, tf.uint8], }, ] def build_graph(parameters): input_shape = parameters["input_diag_shapes"][0] diag_shape = parameters["input_diag_shapes"][1] input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=input_shape) diag_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="diagonal", shape=diag_shape) outs = tf.matrix_set_diag(input_tensor, diag_tensor) return [input_tensor, diag_tensor], [outs] def build_inputs(parameters, sess, inputs, outputs): input_shape = parameters["input_diag_shapes"][0] diag_shape = parameters["input_diag_shapes"][1] input_values = create_tensor_data(parameters["input_dtype"], input_shape) diag_values = create_tensor_data(parameters["input_dtype"], diag_shape) return [input_values, diag_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values, diag_values]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function() def make_eye_tests(options): """Make a set of tests for tf.eye op.""" test_parameters = [{ "num_rows_shape": [[]], "num_cols_shape": [[]], "batch_shape": [[3], [2, 4], [4, 5, 6], None], "use_num_cols": [True, False], "dtype": [tf.float32, tf.int32], }] def build_graph(parameters): input_tensor0 = tf.placeholder( dtype=tf.int32, name="num_rows", shape=parameters["num_rows_shape"]) input_tensor1 = tf.placeholder( dtype=tf.int32, name="num_columns", shape=parameters["num_cols_shape"]) if parameters["use_num_cols"]: outs = tf.eye( num_rows=input_tensor0, num_columns=input_tensor1, batch_shape=parameters["batch_shape"], dtype=parameters["dtype"]) return [input_tensor0, input_tensor1], [outs] else: outs = tf.eye(num_rows=input_tensor0, dtype=parameters["dtype"]) return [input_tensor0], [outs] def build_inputs(parameters, sess, inputs, outputs): input_value0 = create_scalar_data(dtype=np.int32, min_value=1) input_value1 = create_scalar_data(dtype=np.int32, min_value=1) if parameters["use_num_cols"]: return [input_value0, input_value1], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value0, input_value1]))) else: return [input_value0], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value0]))) make_zip_of_tests(options, test_parameters, build_graph, build_inputs) @register_make_test_function(name="make_unidirectional_sequence_lstm_tests") @test_util.enable_control_flow_v2 def make_unidirectional_sequence_lstm_tests(options): """Make a set of tests to do unidirectional_sequence_lstm.""" test_parameters = [{ "batch_size": [2, 4, 6], "seq_length": [1, 3], "units": [4, 5], "use_peepholes": [False, True], "is_dynamic_rnn": [False, True] }] def build_graph(parameters): input_values = [] if parameters["is_dynamic_rnn"]: shape = [ parameters["seq_length"], parameters["batch_size"], parameters["units"] ] input_value = tf.placeholder(dtype=tf.float32, name="input", shape=shape) input_values.append(input_value) lstm_cell = tf.lite.experimental.nn.TFLiteLSTMCell( parameters["units"], use_peepholes=parameters["use_peepholes"]) outs, _ = tf.lite.experimental.nn.dynamic_rnn( lstm_cell, input_value, dtype=tf.float32, time_major=True) outs = tf.unstack(outs, axis=1) else: shape = [parameters["batch_size"], parameters["units"]] for i in range(parameters["seq_length"]): input_value = tf.placeholder( dtype=tf.float32, name=("input_%d" % i), shape=shape) input_values.append(input_value) lstm_cell = tf.lite.experimental.nn.TFLiteLSTMCell( parameters["units"], use_peepholes=parameters["use_peepholes"]) outs, _ = tf.nn.static_rnn(lstm_cell, input_values, dtype=tf.float32) real_output = tf.zeros([1], dtype=tf.float32) + outs[-1] return input_values, [real_output] def build_inputs(parameters, sess, inputs, outputs): input_values = [] if parameters["is_dynamic_rnn"]: shape = [ parameters["seq_length"], parameters["batch_size"], parameters["units"] ] input_value = create_tensor_data(tf.float32, shape) input_values.append(input_value) else: shape = [parameters["batch_size"], parameters["units"]] for i in range(parameters["seq_length"]): input_value = create_tensor_data(tf.float32, shape) input_values.append(input_value) init = tf.global_variables_initializer() sess.run(init) # Tflite fused kernel takes input as [time, batch, input]. # For static unidirectional sequence lstm, the input is an array sized of # time, and pack the array together, however, for time = 1, the input is # not packed. tflite_input_values = input_values if not parameters["is_dynamic_rnn"] and parameters["seq_length"] == 1: tflite_input_values = [ input_values[0].reshape((1, parameters["batch_size"], parameters["units"])) ] return tflite_input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, use_frozen_graph=True) @register_make_test_function(name="make_unidirectional_sequence_rnn_tests") @test_util.enable_control_flow_v2 def make_unidirectional_sequence_rnn_tests(options): """Make a set of tests to do unidirectional_sequence_rnn.""" test_parameters = [{ "batch_size": [2, 4, 6], "seq_length": [1, 3], "units": [4, 5], "is_dynamic_rnn": [False, True] }] def build_graph(parameters): input_values = [] if parameters["is_dynamic_rnn"]: shape = [ parameters["seq_length"], parameters["batch_size"], parameters["units"] ] input_value = tf.placeholder(dtype=tf.float32, name="input", shape=shape) input_values.append(input_value) rnn_cell = tf.lite.experimental.nn.TfLiteRNNCell(parameters["units"]) outs, _ = tf.lite.experimental.nn.dynamic_rnn( rnn_cell, input_value, dtype=tf.float32, time_major=True) outs = tf.unstack(outs, axis=1) else: shape = [parameters["batch_size"], parameters["units"]] for i in range(parameters["seq_length"]): input_value = tf.placeholder( dtype=tf.float32, name=("input_%d" % i), shape=shape) input_values.append(input_value) rnn_cell = tf.lite.experimental.nn.TfLiteRNNCell(parameters["units"]) outs, _ = tf.nn.static_rnn(rnn_cell, input_values, dtype=tf.float32) real_output = tf.zeros([1], dtype=tf.float32) + outs[-1] return input_values, [real_output] def build_inputs(parameters, sess, inputs, outputs): input_values = [] if parameters["is_dynamic_rnn"]: shape = [ parameters["seq_length"], parameters["batch_size"], parameters["units"] ] input_value = create_tensor_data(tf.float32, shape) input_values.append(input_value) else: shape = [parameters["batch_size"], parameters["units"]] for i in range(parameters["seq_length"]): input_value = create_tensor_data(tf.float32, shape) input_values.append(input_value) init = tf.global_variables_initializer() sess.run(init) # Tflite fused kernel takes input as [time, batch, input]. # For static unidirectional sequence rnn, the input is an array sized of # time, and pack the array together, however, for time = 1, the input is # not packed. tflite_input_values = input_values if not parameters["is_dynamic_rnn"] and parameters["seq_length"] == 1: tflite_input_values = [ input_values[0].reshape((1, parameters["batch_size"], parameters["units"])) ] return tflite_input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, use_frozen_graph=True) @register_make_test_function() def make_unfused_gru_tests(options): """Make a set of tests for unfused gru op.""" test_parameters = [{ "units": [2, 5], "batch_size": [1, 2], "time": [3], }] def build_graph(parameters): inputs = [ tf.placeholder(tf.float32, [parameters["batch_size"], parameters["units"]]) for _ in range(parameters["time"]) ] cell_fw = tf.nn.rnn_cell.GRUCell(parameters["units"]) cell_bw = tf.nn.rnn_cell.GRUCell(parameters["units"]) outputs, _, _ = tf.nn.static_bidirectional_rnn( cell_fw, cell_bw, inputs, dtype=tf.float32) return inputs, outputs def build_inputs(parameters, sess, inputs, outputs): input_values = [ create_tensor_data(tf.float32, [parameters["batch_size"], parameters["units"]]) for _ in range(parameters["time"]) ] init = tf.global_variables_initializer() sess.run(init) return input_values, sess.run( outputs, feed_dict=dict(zip(inputs, input_values))) make_zip_of_tests( options, test_parameters, build_graph, build_inputs, use_frozen_graph=True) @register_make_test_function() def make_rfft2d_tests(options): """Make a set of tests to do rfft2d.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[8, 8], [3, 8, 8]], "fft_length": [ None, [4, 4], [4, 8], [8, 4], [8, 8], [8, 16], [16, 8], [16, 16] ] }] def build_graph(parameters): input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) outs = tf.signal.rfft2d(input_value, fft_length=parameters["fft_length"]) return [input_value], [outs] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) extra_toco_options = ExtraTocoOptions() extra_toco_options.allow_custom_ops = True make_zip_of_tests(options, test_parameters, build_graph, build_inputs, extra_toco_options) def _prepare_dir(options): def mkdir_if_not_exist(x): if not os.path.isdir(x): os.mkdir(x) if not os.path.isdir(x): raise RuntimeError("Failed to create dir %r" % x) opstest_path = os.path.join(options.output_path) mkdir_if_not_exist(opstest_path) def generate_examples(options): """Generate examples for a test set. Args: options: Options containing information to generate examples. """ _prepare_dir(options) out = options.zip_to_output # Some zip filenames contain a postfix identifying the conversion mode. The # list of valid conversion modes is defined in # generated_test_conversion_modes() in build_def.bzl. if options.multi_gen_state: test_name = options.multi_gen_state.test_name else: # Remove suffixes to extract the test name from the output name. test_name = re.sub( r"(_(|toco-flex|forward-compat))?\.zip$", "", out, count=1) test_function_name = "make_%s_tests" % test_name if test_function_name not in _MAKE_TEST_FUNCTIONS_MAP: raise RuntimeError("Can't find a test function to create %r. Tried %r" % (out, test_function_name)) test_function = _MAKE_TEST_FUNCTIONS_MAP[test_function_name] if options.make_forward_compat_test: future_date = datetime.date.today() + datetime.timedelta(days=30) with tf.compat.forward_compatibility_horizon(future_date.year, future_date.month, future_date.day): test_function(options) else: test_function(options) def generate_multi_set_examples(options, test_sets): """Generate examples for test sets. Args: options: Options containing information to generate examples. test_sets: List of the name of test sets to generate examples. """ _prepare_dir(options) multi_gen_state = MultiGenState() options.multi_gen_state = multi_gen_state zip_path = os.path.join(options.output_path, options.zip_to_output) with zipfile.PyZipFile(zip_path, "w") as archive: multi_gen_state.archive = archive for test_name in test_sets: # Some generation function can change the value of the options object. # To keep the original options for each run, we use shallow copy. new_options = copy.copy(options) # Remove suffix and set test_name to run proper test generation function. multi_gen_state.test_name = re.sub( r"(_(|toco-flex|forward-compat))?$", "", test_name, count=1) # Set label base path to write test data files with proper path. multi_gen_state.label_base_path = os.path.join( os.path.dirname(zip_path), test_name + ".zip") generate_examples(new_options) archive.writestr("manifest.txt", "".join(multi_gen_state.zip_manifest), zipfile.ZIP_DEFLATED)
from django.db import models from django.utils import timezone # Create your models here. STRFORMAT = "%Y-%m-%dT%H:%M:%S.%f%Z" class Permission(models.Model): name = models.CharField(max_length=128, unique=True) create_time = models.DateTimeField(auto_now_add=timezone.now()) update_time = models.DateTimeField(auto_now=timezone.now()) is_delete = models.BooleanField(default=False) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) create_time = models.DateTimeField(auto_now_add=timezone.now()) update_time = models.DateTimeField(auto_now=timezone.now()) is_delete = models.BooleanField(default=False) permission = models.ManyToManyField(Permission) def __str__(self): return self.name class UserInfo(models.Model): create_time = models.DateTimeField(auto_now_add=timezone.now()) update_time = models.DateTimeField(auto_now=timezone.now()) is_delete = models.BooleanField(default=False) nick_name = models.CharField(max_length=128, blank=True, default="") gender = models.CharField(max_length=1, default='s', choices=( ('male', 'm'), ('female', 'f'), ('secret', 's'))) intruduction = models.CharField(max_length=256, blank=True, default="") class User(models.Model): username = models.CharField(unique=True, max_length=128) password = models.CharField(max_length=64) create_time = models.DateTimeField(auto_now_add=timezone.now()) update_time = models.DateTimeField(auto_now=timezone.now()) is_delete = models.BooleanField(default=False) email = models.EmailField() user_info = models.OneToOneField(UserInfo, on_delete=models.CASCADE) group = models.ManyToManyField(Group) permission = models.ManyToManyField(Permission)
# -*- coding: utf-8 -*- """ :authors: python273 :license: Apache License, Version 2.0, see LICENSE file :copyright: (c) 2019 python273 """ import requests from .vk_api import VkApi, VkApiMethod STORY_ALLOWED_LINK_TEXTS = { 'to_store', 'vote', 'more', 'book', 'order', 'enroll', 'fill', 'signup', 'buy', 'ticket', 'write', 'open', 'learn_more', 'view', 'go_to', 'contact', 'watch', 'play', 'install', 'read' } class VkUpload(object): """ Загрузка файлов через API (https://vk.com/dev/upload_files) :param vk: объект :class:`VkApi` или :class:`VkApiMethod` """ __slots__ = ('vk', 'http') def __init__(self, vk): if not isinstance(vk, (VkApi, VkApiMethod)): raise TypeError( 'The arg should be VkApi or VkApiMethod instance' ) if isinstance(vk, VkApiMethod): self.vk = vk else: self.vk = vk.get_api() self.http = requests.Session() self.http.headers.pop('user-agent') def photo(self, photos, album_id, latitude=None, longitude=None, caption=None, description=None, group_id=None): """ Загрузка изображений в альбом пользователя :param photos: путь к изображению(ям) или file-like объект(ы) :type photos: str or list :param album_id: идентификатор альбома :param latitude: географическая широта, заданная в градусах (от -90 до 90) :param longitude: географическая долгота, заданная в градусах (от -180 до 180) :param caption: текст описания изображения :param description: текст описания альбома :param group_id: идентификатор сообщества (если загрузка идет в группу) """ values = {'album_id': album_id} if group_id: values['group_id'] = group_id url = self.vk.photos.getUploadServer(**values)['upload_url'] with FilesOpener(photos) as photo_files: response = self.http.post(url, files=photo_files).json() if 'album_id' not in response: response['album_id'] = response['aid'] response.update({ 'latitude': latitude, 'longitude': longitude, 'caption': caption, 'description': description }) values.update(response) return self.vk.photos.save(**values) def photo_messages(self, photos, peer_id=None): """ Загрузка изображений в сообщения :param photos: путь к изображению(ям) или file-like объект(ы) :type photos: str or list :param peer_id: peer_id беседы :type peer_id: int """ url = self.vk.photos.getMessagesUploadServer(peer_id=peer_id)['upload_url'] with FilesOpener(photos) as photo_files: response = self.http.post(url, files=photo_files) return self.vk.photos.saveMessagesPhoto(**response.json()) def photo_group_widget(self, photo, image_type): """ Загрузка изображений в коллекцию сообщества для виджетов приложений сообществ :param photo: путь к изображению или file-like объект :type photo: str :param image_type: тип изображиения в зависимости от выбранного виджета (https://vk.com/dev/appWidgets.getGroupImageUploadServer) :type image_type: str """ url = self.vk.appWidgets.getGroupImageUploadServer(image_type=image_type)['upload_url'] with FilesOpener(photo, key_format='file') as photo_files: response = self.http.post(url, files=photo_files) return self.vk.appWidgets.saveGroupImage(**response.json()) def photo_profile(self, photo, owner_id=None, crop_x=None, crop_y=None, crop_width=None): """ Загрузка изображения профиля :param photo: путь к изображению или file-like объект :param owner_id: идентификатор сообщества или текущего пользователя. По умолчанию загрузка идет в профиль текущего пользователя. При отрицательном значении загрузка идет в группу. :param crop_x: координата X верхнего правого угла миниатюры. :param crop_y: координата Y верхнего правого угла миниатюры. :param crop_width: сторона квадрата миниатюры. При передаче всех crop_* для фотографии также будет подготовлена квадратная миниатюра. """ values = {} if owner_id: values['owner_id'] = owner_id crop_params = {} if crop_x is not None and crop_y is not None and crop_width is not None: crop_params['_square_crop'] = '{},{},{}'.format( crop_x, crop_y, crop_width ) response = self.vk.photos.getOwnerPhotoUploadServer(**values) url = response['upload_url'] with FilesOpener(photo, key_format='file') as photo_files: response = self.http.post( url, data=crop_params, files=photo_files ) return self.vk.photos.saveOwnerPhoto(**response.json()) def photo_chat(self, photo, chat_id): """ Загрузка и смена обложки в беседе :param photo: путь к изображению или file-like объект :param chat_id: ID беседы """ values = {'chat_id': chat_id} url = self.vk.photos.getChatUploadServer(**values)['upload_url'] with FilesOpener(photo, key_format='file') as photo_file: response = self.http.post(url, files=photo_file) return self.vk.messages.setChatPhoto( file=response.json()['response'] ) def photo_wall(self, photos, user_id=None, group_id=None, caption=None): """ Загрузка изображений на стену пользователя или в группу :param photos: путь к изображению(ям) или file-like объект(ы) :type photos: str or list :param user_id: идентификатор пользователя :param group_id: идентификатор сообщества (если загрузка идет в группу) :param caption: текст описания фотографии. """ values = {} if user_id: values['user_id'] = user_id elif group_id: values['group_id'] = group_id if caption: values['caption'] = caption response = self.vk.photos.getWallUploadServer(**values) url = response['upload_url'] with FilesOpener(photos) as photos_files: response = self.http.post(url, files=photos_files) values.update(response.json()) return self.vk.photos.saveWallPhoto(**values) def photo_market(self, photo, group_id, main_photo=False, crop_x=None, crop_y=None, crop_width=None): """ Загрузка изображений для товаров в магазине :param photo: путь к изображению(ям) или file-like объект(ы) :type photo: str or list :param group_id: идентификатор сообщества, для которого необходимо загрузить фотографию товара :type group_id: int :param main_photo: является ли фотография обложкой товара :type main_photo: bool :param crop_x: координата x для обрезки фотографии (верхний правый угол) :type crop_x: int :param crop_y: координата y для обрезки фотографии (верхний правый угол) :type crop_y: int :param crop_width: ширина фотографии после обрезки в px :type crop_width: int """ if group_id < 0: group_id = abs(group_id) values = { 'main_photo': main_photo, 'group_id': group_id, } if crop_x is not None: values['crop_x'] = crop_x if crop_y is not None: values['crop_y'] = crop_y if crop_width is not None: values['crop_width'] = crop_width response = self.vk.photos.getMarketUploadServer(**values) url = response['upload_url'] with FilesOpener(photo) as photos_files: response = self.http.post(url, files=photos_files) values.update(response.json()) return self.vk.photos.saveMarketPhoto(**values) def photo_market_album(self, photo, group_id): """ Загрузка фотографии для подборки товаров :param photo: путь к изображению(ям) или file-like объект(ы) :type photo: str or list :param group_id: идентификатор сообщества, для которого необходимо загрузить фотографию для подборки товаров :type group_id: int """ if group_id < 0: group_id = abs(group_id) values = { 'group_id': group_id, } response = self.vk.photos.getMarketAlbumUploadServer(**values) url = response['upload_url'] with FilesOpener(photo) as photos_files: response = self.http.post(url, files=photos_files) values.update(response.json()) return self.vk.photos.saveMarketAlbumPhoto(**values) def audio(self, audio, artist, title): """ Загрузка аудио :param audio: путь к аудиофайлу или file-like объект :param artist: исполнитель :param title: название """ url = self.vk.audio.getUploadServer()['upload_url'] with FilesOpener(audio, key_format='file') as f: response = self.http.post(url, files=f).json() response.update({ 'artist': artist, 'title': title }) return self.vk.audio.save(**response) def video(self, video_file=None, link=None, name=None, description=None, is_private=None, wallpost=None, group_id=None, album_id=None, privacy_view=None, privacy_comment=None, no_comments=None, repeat=None): """ Загрузка видео :param video_file: путь к видеофайлу или file-like объект. :type video_file: object or str :param link: url для встраивания видео с внешнего сайта, например, с Youtube. :type link: str :param name: название видеофайла :type name: str :param description: описание видеофайла :type description: str :param is_private: указывается 1, если видео загружается для отправки личным сообщением. После загрузки с этим параметром видеозапись не будет отображаться в списке видеозаписей пользователя и не будет доступна другим пользователям по ее идентификатору. :type is_private: bool :param wallpost: требуется ли после сохранения опубликовать запись с видео на стене. :type wallpost: bool :param group_id: идентификатор сообщества, в которое будет сохранен видеофайл. По умолчанию файл сохраняется на страницу текущего пользователя. :type group_id: int :param album_id: идентификатор альбома, в который будет загружен видеофайл. :type album_id: int :param privacy_view: настройки приватности просмотра видеозаписи в специальном формате. (https://vk.com/dev/objects/privacy) Приватность доступна для видеозаписей, которые пользователь загрузил в профиль. (список слов, разделенных через запятую) :param privacy_comment: настройки приватности комментирования видеозаписи в специальном формате. (https://vk.com/dev/objects/privacy) :param no_comments: 1 — закрыть комментарии (для видео из сообществ). :type no_comments: bool :param repeat: зацикливание воспроизведения видеозаписи. Флаг. :type repeat: bool """ if not link and not video_file: raise ValueError('Either link or video_file param is required') if link and video_file: raise ValueError('Both params link and video_file aren\'t allowed') values = { 'name': name, 'description': description, 'is_private': is_private, 'wallpost': wallpost, 'link': link, 'group_id': group_id, 'album_id': album_id, 'privacy_view': privacy_view, 'privacy_comment': privacy_comment, 'no_comments': no_comments, 'repeat': repeat } response = self.vk.video.save(**values) url = response.pop('upload_url') with FilesOpener(video_file or [], 'video_file') as f: response.update(self.http.post( url, files=f or None ).json()) return response def document(self, doc, title=None, tags=None, group_id=None, to_wall=False, message_peer_id=None, doc_type=None): """ Загрузка документа :param doc: путь к документу или file-like объект :param title: название документа :param tags: метки для поиска :param group_id: идентификатор сообщества (если загрузка идет в группу) """ values = { 'group_id': group_id, 'peer_id': message_peer_id, 'type': doc_type } if to_wall: method = self.vk.docs.getWallUploadServer elif message_peer_id: method = self.vk.docs.getMessagesUploadServer else: method = self.vk.docs.getUploadServer url = method(**values)['upload_url'] with FilesOpener(doc, 'file') as files: response = self.http.post(url, files=files).json() response.update({ 'title': title, 'tags': tags }) return self.vk.docs.save(**response) def document_wall(self, doc, title=None, tags=None, group_id=None): """ Загрузка документа в папку Отправленные, для последующей отправки документа на стену или личным сообщением. :param doc: путь к документу или file-like объект :param title: название документа :param tags: метки для поиска :param group_id: идентификатор сообщества (если загрузка идет в группу) """ return self.document(doc, title, tags, group_id, to_wall=True) def document_message(self, doc, title=None, tags=None, peer_id=None): """ Загрузка документа для отправки личным сообщением. :param doc: путь к документу или file-like объект :param title: название документа :param tags: метки для поиска :param peer_id: peer_id беседы """ return self.document(doc, title, tags, message_peer_id=peer_id) def audio_message(self, audio, peer_id=None, group_id=None): """ Загрузка аудио-сообщения. :param audio: путь к аудиофайлу или file-like объект :param peer_id: идентификатор диалога :param group_id: для токена группы, можно передавать ID группы, вместо peer_id """ return self.document( audio, doc_type='audio_message', message_peer_id=peer_id, group_id=group_id, to_wall=group_id is not None ) def graffiti(self, image, peer_id=None, group_id=None): """ Загрузка граффити :param image: путь к png изображению или file-like объект. :param peer_id: идентификатор диалога (только для авторизации пользователя) :param group_id: для токена группы, нужно передавать ID группы, вместо peer_id """ return self.document( image, doc_type='graffiti', message_peer_id=peer_id, group_id=group_id, to_wall=group_id is not None ) def photo_cover(self, photo, group_id, crop_x=None, crop_y=None, crop_x2=None, crop_y2=None): """ Загрузка изображения профиля :param photo: путь к изображению или file-like объект :param group_id: идентификатор сообщества :param crop_x: координата X верхнего левого угла для обрезки изображения :param crop_y: координата Y верхнего левого угла для обрезки изображения :param crop_x2: коорд. X нижнего правого угла для обрезки изображения :param crop_y2: коорд. Y нижнего правого угла для обрезки изображения """ values = { 'group_id': group_id, 'crop_x': crop_x, 'crop_y': crop_y, 'crop_x2': crop_x2, 'crop_y2': crop_y2 } url = self.vk.photos.getOwnerCoverPhotoUploadServer(**values)['upload_url'] with FilesOpener(photo, key_format='file') as photo_files: response = self.http.post(url, files=photo_files) return self.vk.photos.saveOwnerCoverPhoto( **response.json() ) def story(self, file, file_type, add_to_news=True, user_ids=None, reply_to_story=None, link_text=None, link_url=None, group_id=None): """ Загрузка истории :param file: путь к изображению, гифке или видео или file-like объект :param file_type: тип истории (photo или video) :param add_to_news: размещать ли историю в новостях :param user_ids: идентификаторы пользователей, которые будут видеть историю :param reply_to_story: идентификатор истории, в ответ на которую создается новая :param link_text: текст ссылки для перехода из истории :param link_url: адрес ссылки для перехода из истории :param group_id: идентификатор сообщества, в которое должна быть загружена история """ if user_ids is None: user_ids = [] if file_type == 'photo': method = self.vk.stories.getPhotoUploadServer elif file_type == 'video': method = self.vk.stories.getVideoUploadServer else: raise ValueError('type should be either photo or video') if not add_to_news and not user_ids: raise ValueError( 'add_to_news and/or user_ids param is required' ) if (link_text or link_url) and not group_id: raise ValueError('Link params available only for communities') if (not link_text) != (not link_url): raise ValueError( 'Either both link_text and link_url or neither one are required' ) if link_text and link_text not in STORY_ALLOWED_LINK_TEXTS: raise ValueError('Invalid link_text') if link_url and not link_url.startswith('https://vk.com'): raise ValueError( 'Only internal https://vk.com links are allowed for link_url' ) if link_url and len(link_url) > 2048: raise ValueError('link_url is too long. Max length - 2048') values = { 'add_to_news': int(add_to_news), 'user_ids': ','.join(map(str, user_ids)), 'reply_to_story': reply_to_story, 'link_text': link_text, 'link_url': link_url, 'group_id': group_id } url = method(**values)['upload_url'] with FilesOpener(file, key_format='file') as files: return self.http.post(url, files=files) class FilesOpener(object): def __init__(self, paths, key_format='file{}'): if not isinstance(paths, list): paths = [paths] self.paths = paths self.key_format = key_format self.opened_files = [] def __enter__(self): return self.open_files() def __exit__(self, type, value, traceback): self.close_files() def open_files(self): self.close_files() files = [] for x, file in enumerate(self.paths): if hasattr(file, 'read'): f = file if hasattr(file, 'name'): filename = file.name else: filename = '.jpg' else: filename = file f = open(filename, 'rb') self.opened_files.append(f) ext = filename.split('.')[-1] files.append( (self.key_format.format(x), ('file{}.{}'.format(x, ext), f)) ) return files def close_files(self): for f in self.opened_files: f.close() self.opened_files = []
# source: https://github.com/hellbell/ADNet/blob/3a7955587b5d395401ebc94a5ab067759340680d/utils/init_params.m #parameter settings show_visualization = 0 record_video = 0 GT_anno_interval = 1 # ============================ # NETWORK PARAMETERS # ============================ opts = { 'imgSize' : [112, 112, 3], # 'train_dbs' : ['vot15', 'vot14', 'vot13'], 'train_dbs' : ['vot13'], 'test_db' : 'otb', #'test_db' : 'test/vid', 'train': { 'weightDecay' : 0.0005, 'momentum' : 0.9, 'learningRate' : 10e-5, 'conserveMemory' : True, 'gt_skip' : 1, 'rl_num_batches' : 5, 'RL_steps' : 10 }, #in ADNet.py (train), the minibatch_size is not the num below, instead, it's fixed in the code. 'minibatch_size' : 32, #'numEpoch' : 30, 'numEpoch' : 2, 'numInnerEpoch' : 3, 'continueTrain' : False, 'samplePerFrame_large' : 40, 'samplePerFrame_small' : 10, 'inputSize' : [112, 112, 3], 'stopIou' : 0.93, 'meta':{ 'inputSize' : [112, 112, 3] }, 'use_finetune' : True, 'scale_factor' : 1.05, # test 'finetune_iters' : 20, 'finetune_iters_online' : 10, 'finetune_interval' : 30, 'posThre_init' : 0.7, 'negThre_init' : 0.3, 'posThre_online' : 0.7, 'negThre_online' : 0.5, 'nPos_init' : 200, 'nNeg_init' : 150, 'nPos_online' : 30, 'nNeg_online' : 15, 'finetune_scale_factor' : 3.0, 'redet_scale_factor' : 3.0, 'finetune_trans' : 0.10, 'redet_samples' : 256, 'successThre' : 0.5, 'failedThre' : 0.5, 'nFrames_long' : 100, # long-term period (in matlab code, for positive samples... while current implementation just with history for now...) 'nFrames_short' : 20, # short-term period (for negative samples) #'nPos_train' : 150, #'nNeg_train' : 50, 'nPos_train': 9, 'nNeg_train': 3, 'posThre_train' : 0.5, 'negThre_train' : 0.3, 'random_perturb' : { 'x' : 0.15, 'y' : 0.15, 'w' : 0.03, 'h' : 0.03 }, 'action_move' : { 'x' : 0.03, 'y' : 0.03, 'w' : 0.03, 'h' : 0.03, 'deltas' : [ [-1, 0, 0, 0], # left [-2, 0, 0, 0], # left x2 [+1, 0, 0, 0], # right [+2, 0, 0, 0], # right x2 [0, -1, 0, 0], # up [0, -2, 0, 0], # up x2 [0, +1, 0, 0], # down [0, +2, 0, 0], # down x2 [0, 0, 0, 0], # stop [0, 0, -1, -1], # smaller [0, 0, +1, +1] # bigger ] }, 'num_actions' : 11, 'stop_action' : 8, 'num_show_actions' : 20, 'num_action_step_max' : 20, 'num_action_history' : 10, 'visualize' : True, 'printscreen' : True, 'means' : [104, 117, 123] # https://github.com/amdegroot/ssd.pytorch/blob/8dd38657a3b1df98df26cf18be9671647905c2a0/data/config.py }
#!/usr/bin/env python # # trace Trace a function and print a trace message based on its # parameters, with an optional filter. # # USAGE: trace [-h] [-p PID] [-v] [-Z STRING_SIZE] [-S] [-M MAX_EVENTS] [-o] # probe [probe ...] # # Licensed under the Apache License, Version 2.0 (the "License") # Copyright (C) 2016 Sasha Goldshtein. from bcc import BPF, Tracepoint, Perf, ProcUtils, USDTReader from time import sleep, strftime import argparse import re import ctypes as ct import os import traceback import sys class Time(object): # BPF timestamps come from the monotonic clock. To be able to filter # and compare them from Python, we need to invoke clock_gettime. # Adapted from http://stackoverflow.com/a/1205762 CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h> class timespec(ct.Structure): _fields_ = [ ('tv_sec', ct.c_long), ('tv_nsec', ct.c_long) ] librt = ct.CDLL('librt.so.1', use_errno=True) clock_gettime = librt.clock_gettime clock_gettime.argtypes = [ct.c_int, ct.POINTER(timespec)] @staticmethod def monotonic_time(): t = Time.timespec() if Time.clock_gettime( Time.CLOCK_MONOTONIC_RAW, ct.pointer(t)) != 0: errno_ = ct.get_errno() raise OSError(errno_, os.strerror(errno_)) return t.tv_sec * 1e9 + t.tv_nsec class Probe(object): probe_count = 0 max_events = None event_count = 0 first_ts = 0 use_localtime = True pid = -1 @classmethod def configure(cls, args): cls.max_events = args.max_events cls.use_localtime = not args.offset cls.first_ts = Time.monotonic_time() cls.pid = args.pid or -1 def __init__(self, probe, string_size): self.raw_probe = probe self.string_size = string_size Probe.probe_count += 1 self._parse_probe() self.probe_num = Probe.probe_count self.probe_name = "probe_%s_%d" % \ (self._display_function(), self.probe_num) def __str__(self): return "%s:%s:%s FLT=%s ACT=%s/%s" % (self.probe_type, self.library, self._display_function(), self.filter, self.types, self.values) def is_default_action(self): return self.python_format == "" def _bail(self, error): raise ValueError("error in probe '%s': %s" % (self.raw_probe, error)) def _parse_probe(self): text = self.raw_probe # Everything until the first space is the probe specifier first_space = text.find(' ') spec = text[:first_space] if first_space >= 0 else text self._parse_spec(spec) if first_space >= 0: text = text[first_space:].lstrip() else: text = "" # If we now have a (, wait for the balanced closing ) and that # will be the predicate self.filter = None if len(text) > 0 and text[0] == "(": balance = 1 for i in range(1, len(text)): if text[i] == "(": balance += 1 if text[i] == ")": balance -= 1 if balance == 0: self._parse_filter(text[:i+1]) text = text[i+1:] break if self.filter is None: self._bail("unmatched end of predicate") if self.filter is None: self.filter = "1" # The remainder of the text is the printf action self._parse_action(text.lstrip()) def _parse_spec(self, spec): parts = spec.split(":") # Two special cases: 'func' means 'p::func', 'lib:func' means # 'p:lib:func'. Other combinations need to provide an empty # value between delimiters, e.g. 'r::func' for a kretprobe on # the function func. if len(parts) == 1: parts = ["p", "", parts[0]] elif len(parts) == 2: parts = ["p", parts[0], parts[1]] if len(parts[0]) == 0: self.probe_type = "p" elif parts[0] in ["p", "r", "t", "u"]: self.probe_type = parts[0] else: self._bail("probe type must be '', 'p', 't', 'r', " + "or 'u', but got '%s'" % parts[0]) if self.probe_type == "t": self.tp_category = parts[1] self.tp_event = parts[2] self.tp = Tracepoint.enable_tracepoint( self.tp_category, self.tp_event) self.library = "" # kernel self.function = "perf_trace_%s" % self.tp_event elif self.probe_type == "u": self.library = parts[1] self.usdt_name = parts[2] self.function = "" # no function, just address # We will discover the USDT provider by matching on # the USDT name in the specified library self._find_usdt_probe() self._enable_usdt_probe() else: self.library = parts[1] self.function = parts[2] def _enable_usdt_probe(self): if self.usdt.need_enable(): if Probe.pid == -1: self._bail("probe needs pid to enable") self.usdt.enable(Probe.pid) def _disable_usdt_probe(self): if self.probe_type == "u" and self.usdt.need_enable(): self.usdt.disable(Probe.pid) def close(self): self._disable_usdt_probe() def _find_usdt_probe(self): reader = USDTReader(bin_path=self.library) for probe in reader.probes: if probe.name == self.usdt_name: self.usdt = probe return self._bail("unrecognized USDT probe %s" % self.usdt_name) def _parse_filter(self, filt): self.filter = self._replace_args(filt) def _parse_types(self, fmt): for match in re.finditer( r'[^%]%(s|u|d|llu|lld|hu|hd|x|llx|c)', fmt): self.types.append(match.group(1)) fmt = re.sub(r'([^%]%)(u|d|llu|lld|hu|hd)', r'\1d', fmt) fmt = re.sub(r'([^%]%)(x|llx)', r'\1x', fmt) self.python_format = fmt.strip('"') def _parse_action(self, action): self.values = [] self.types = [] self.python_format = "" if len(action) == 0: return action = action.strip() match = re.search(r'(\".*\"),?(.*)', action) if match is None: self._bail("expected format string in \"s") self.raw_format = match.group(1) self._parse_types(self.raw_format) for part in match.group(2).split(','): part = self._replace_args(part) if len(part) > 0: self.values.append(part) aliases = { "retval": "PT_REGS_RC(ctx)", "arg1": "PT_REGS_PARM1(ctx)", "arg2": "PT_REGS_PARM2(ctx)", "arg3": "PT_REGS_PARM3(ctx)", "arg4": "PT_REGS_PARM4(ctx)", "arg5": "PT_REGS_PARM5(ctx)", "arg6": "PT_REGS_PARM6(ctx)", "$uid": "(unsigned)(bpf_get_current_uid_gid() & 0xffffffff)", "$gid": "(unsigned)(bpf_get_current_uid_gid() >> 32)", "$pid": "(unsigned)(bpf_get_current_pid_tgid() & 0xffffffff)", "$tgid": "(unsigned)(bpf_get_current_pid_tgid() >> 32)", "$cpu": "bpf_get_smp_processor_id()" } def _replace_args(self, expr): for alias, replacement in Probe.aliases.items(): # For USDT probes, we replace argN values with the # actual arguments for that probe. if alias.startswith("arg") and self.probe_type == "u": continue expr = expr.replace(alias, replacement) return expr p_type = { "u": ct.c_uint, "d": ct.c_int, "llu": ct.c_ulonglong, "lld": ct.c_longlong, "hu": ct.c_ushort, "hd": ct.c_short, "x": ct.c_uint, "llx": ct.c_ulonglong, "c": ct.c_ubyte } def _generate_python_field_decl(self, idx, fields): field_type = self.types[idx] if field_type == "s": ptype = ct.c_char * self.string_size else: ptype = Probe.p_type[field_type] fields.append(("v%d" % idx, ptype)) def _generate_python_data_decl(self): self.python_struct_name = "%s_%d_Data" % \ (self._display_function(), self.probe_num) fields = [ ("timestamp_ns", ct.c_ulonglong), ("pid", ct.c_uint), ("comm", ct.c_char * 16) # TASK_COMM_LEN ] for i in range(0, len(self.types)): self._generate_python_field_decl(i, fields) return type(self.python_struct_name, (ct.Structure,), dict(_fields_=fields)) c_type = { "u": "unsigned int", "d": "int", "llu": "unsigned long long", "lld": "long long", "hu": "unsigned short", "hd": "short", "x": "unsigned int", "llx": "unsigned long long", "c": "char" } fmt_types = c_type.keys() def _generate_field_decl(self, idx): field_type = self.types[idx] if field_type == "s": return "char v%d[%d];\n" % (idx, self.string_size) if field_type in Probe.fmt_types: return "%s v%d;\n" % (Probe.c_type[field_type], idx) self._bail("unrecognized format specifier %s" % field_type) def _generate_data_decl(self): # The BPF program will populate values into the struct # according to the format string, and the Python program will # construct the final display string. self.events_name = "%s_events" % self.probe_name self.struct_name = "%s_data_t" % self.probe_name data_fields = "" for i, field_type in enumerate(self.types): data_fields += " " + \ self._generate_field_decl(i) text = """ struct %s { u64 timestamp_ns; u32 pid; char comm[TASK_COMM_LEN]; %s }; BPF_PERF_OUTPUT(%s); """ return text % (self.struct_name, data_fields, self.events_name) def _generate_field_assign(self, idx): field_type = self.types[idx] expr = self.values[idx] if field_type == "s": return """ if (%s != 0) { bpf_probe_read(&__data.v%d, sizeof(__data.v%d), (void *)%s); } """ % (expr, idx, idx, expr) if field_type in Probe.fmt_types: return " __data.v%d = (%s)%s;\n" % \ (idx, Probe.c_type[field_type], expr) self._bail("unrecognized field type %s" % field_type) def generate_program(self, include_self): data_decl = self._generate_data_decl() # kprobes don't have built-in pid filters, so we have to add # it to the function body: if len(self.library) == 0 and Probe.pid != -1: pid_filter = """ u32 __pid = bpf_get_current_pid_tgid(); if (__pid != %d) { return 0; } """ % Probe.pid elif not include_self: pid_filter = """ u32 __pid = bpf_get_current_pid_tgid(); if (__pid == %d) { return 0; } """ % os.getpid() else: pid_filter = "" prefix = "" qualifier = "" signature = "struct pt_regs *ctx" if self.probe_type == "t": data_decl += self.tp.generate_struct() prefix = self.tp.generate_get_struct() elif self.probe_type == "u": signature += ", int __loc_id" prefix = self.usdt.generate_usdt_cases( pid=Probe.pid if Probe.pid != -1 else None) qualifier = "static inline" data_fields = "" for i, expr in enumerate(self.values): data_fields += self._generate_field_assign(i) text = """ %s int %s(%s) { %s %s if (!(%s)) return 0; struct %s __data = {0}; __data.timestamp_ns = bpf_ktime_get_ns(); __data.pid = bpf_get_current_pid_tgid(); bpf_get_current_comm(&__data.comm, sizeof(__data.comm)); %s %s.perf_submit(ctx, &__data, sizeof(__data)); return 0; } """ text = text % (qualifier, self.probe_name, signature, pid_filter, prefix, self.filter, self.struct_name, data_fields, self.events_name) if self.probe_type == "u": self.usdt_thunk_names = [] text += self.usdt.generate_usdt_thunks( self.probe_name, self.usdt_thunk_names) return data_decl + "\n" + text @classmethod def _time_off_str(cls, timestamp_ns): return "%.6f" % (1e-9 * (timestamp_ns - cls.first_ts)) def _display_function(self): if self.probe_type == 'p' or self.probe_type == 'r': return self.function elif self.probe_type == 'u': return self.usdt_name else: # self.probe_type == 't' return self.tp_event def print_event(self, cpu, data, size): # Cast as the generated structure type and display # according to the format string in the probe. event = ct.cast(data, ct.POINTER(self.python_struct)).contents values = map(lambda i: getattr(event, "v%d" % i), range(0, len(self.values))) msg = self.python_format % tuple(values) time = strftime("%H:%M:%S") if Probe.use_localtime else \ Probe._time_off_str(event.timestamp_ns) print("%-8s %-6d %-12s %-16s %s" % \ (time[:8], event.pid, event.comm[:12], self._display_function(), msg)) Probe.event_count += 1 if Probe.max_events is not None and \ Probe.event_count >= Probe.max_events: exit() def attach(self, bpf, verbose): if len(self.library) == 0: self._attach_k(bpf) else: self._attach_u(bpf) self.python_struct = self._generate_python_data_decl() bpf[self.events_name].open_perf_buffer(self.print_event) def _attach_k(self, bpf): if self.probe_type == "r": bpf.attach_kretprobe(event=self.function, fn_name=self.probe_name) elif self.probe_type == "p" or self.probe_type == "t": bpf.attach_kprobe(event=self.function, fn_name=self.probe_name) def _attach_u(self, bpf): libpath = BPF.find_library(self.library) if libpath is None: # This might be an executable (e.g. 'bash') libpath = ProcUtils.which(self.library) if libpath is None or len(libpath) == 0: self._bail("unable to find library %s" % self.library) if self.probe_type == "u": for i, location in enumerate(self.usdt.locations): bpf.attach_uprobe(name=libpath, addr=location.address, fn_name=self.usdt_thunk_names[i], pid=Probe.pid) elif self.probe_type == "r": bpf.attach_uretprobe(name=libpath, sym=self.function, fn_name=self.probe_name, pid=Probe.pid) else: bpf.attach_uprobe(name=libpath, sym=self.function, fn_name=self.probe_name, pid=Probe.pid) class Tool(object): examples = """ EXAMPLES: trace do_sys_open Trace the open syscall and print a default trace message when entered trace 'do_sys_open "%s", arg2' Trace the open syscall and print the filename being opened trace 'sys_read (arg3 > 20000) "read %d bytes", arg3' Trace the read syscall and print a message for reads >20000 bytes trace 'r::do_sys_return "%llx", retval' Trace the return from the open syscall and print the return value trace 'c:open (arg2 == 42) "%s %d", arg1, arg2' Trace the open() call from libc only if the flags (arg2) argument is 42 trace 'c:malloc "size = %d", arg1' Trace malloc calls and print the size being allocated trace 'p:c:write (arg1 == 1) "writing %d bytes to STDOUT", arg3' Trace the write() call from libc to monitor writes to STDOUT trace 'r::__kmalloc (retval == 0) "kmalloc failed!" Trace returns from __kmalloc which returned a null pointer trace 'r:c:malloc (retval) "allocated = %p", retval Trace returns from malloc and print non-NULL allocated buffers trace 't:block:block_rq_complete "sectors=%d", tp.nr_sector' Trace the block_rq_complete kernel tracepoint and print # of tx sectors trace 'u:pthread:pthread_create (arg4 != 0)' Trace the USDT probe pthread_create when its 4th argument is non-zero """ def __init__(self): parser = argparse.ArgumentParser(description= "Attach to functions and print trace messages.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=Tool.examples) parser.add_argument("-p", "--pid", type=int, help="id of the process to trace (optional)") parser.add_argument("-v", "--verbose", action="store_true", help="print resulting BPF program code before executing") parser.add_argument("-Z", "--string-size", type=int, default=80, help="maximum size to read from strings") parser.add_argument("-S", "--include-self", action="store_true", help="do not filter trace's own pid from the trace") parser.add_argument("-M", "--max-events", type=int, help="number of events to print before quitting") parser.add_argument("-o", "--offset", action="store_true", help="use relative time from first traced message") parser.add_argument(metavar="probe", dest="probes", nargs="+", help="probe specifier (see examples)") self.args = parser.parse_args() def _create_probes(self): Probe.configure(self.args) self.probes = [] for probe_spec in self.args.probes: self.probes.append(Probe( probe_spec, self.args.string_size)) def _generate_program(self): self.program = """ #include <linux/ptrace.h> #include <linux/sched.h> /* For TASK_COMM_LEN */ """ self.program += BPF.generate_auto_includes( map(lambda p: p.raw_probe, self.probes)) self.program += Tracepoint.generate_decl() self.program += Tracepoint.generate_entry_probe() for probe in self.probes: self.program += probe.generate_program( self.args.include_self) if self.args.verbose: print(self.program) def _attach_probes(self): self.bpf = BPF(text=self.program) Tracepoint.attach(self.bpf) for probe in self.probes: if self.args.verbose: print(probe) probe.attach(self.bpf, self.args.verbose) def _main_loop(self): all_probes_trivial = all(map(Probe.is_default_action, self.probes)) # Print header print("%-8s %-6s %-12s %-16s %s" % \ ("TIME", "PID", "COMM", "FUNC", "-" if not all_probes_trivial else "")) while True: self.bpf.kprobe_poll() def _close_probes(self): for probe in self.probes: probe.close() if self.args.verbose: print("closed probe: " + str(probe)) def run(self): try: self._create_probes() self._generate_program() self._attach_probes() self._main_loop() except: if self.args.verbose: traceback.print_exc() elif sys.exc_info()[0] is not SystemExit: print(sys.exc_info()[1]) self._close_probes() if __name__ == "__main__": Tool().run()
from django.apps import AppConfig class StockDicOpinionConfig(AppConfig): name = 'stock_dic_opinion'
def c2f(tempC): return 1.8 * tempC + 32 def f2c(tempF): return (tempF - 32) / 1.8 def uzmiIzbor(): print("Izaberite 1 da konvertujete *C u F") print("Izaberite 2 da konvertujete *F u C") print("Izaberite 0 da ugasite program") return int(input("Izaberite sta zelite: ")) def c2fKonverzija(): tempC = float(input("Unesite temperaturu u *C: ")) tempF = c2f(tempC) print("Ta temperatura u *F je " + str(tempF)) def f2cKonverzija(): tempF = float(input("Unesite temperaturu u *F: ")) tempC = f2c(tempF) print("Ta temperatura u *C je " + str(tempC)) while True: izbor = uzmiIzbor() if izbor == 1: c2fKonverzija() elif izbor == 2: f2cKonverzija() elif izbor == 0: print("Kraj programa") break
import os import time import collections from datetime import datetime from enum import Enum import xml.etree.ElementTree as etxml from PIL import Image import pkgutil egl = pkgutil.get_loader('eglRenderer') import numpy as np import pybullet as p import pybullet_data import gym ###################################################################################################################################################### #### Drone models enumeration ######################################################################################################################## ###################################################################################################################################################### class DroneModel(Enum): CF2X = 0 # Bitcraze Craziflie 2.0 in the X configuration CF2P = 1 # Bitcraze Craziflie 2.0 in the + configuration HB = 2 # Generic quadrotor (with AscTec Hummingbird inertial properties) MAMBO = 3 # Parrot Mambo quadrotor CERLAB = 4 # CERLAB TBS drone #### String representation of DroneModel ########################################################### def __str__(self): return self.name ###################################################################################################################################################### #### Physics implementations enumeration ############################################################################################################# ###################################################################################################################################################### class Physics(Enum): PYB = 0 # Base PyBullet physics update DYN = 1 # Update with an explicit model of the dynamics PYB_GND = 2 # PyBullet physics update with ground effect PYB_DRAG = 3 # PyBullet physics update with drag PYB_DW = 4 # PyBullet physics update with downwash PYB_GND_DRAG_DW = 5 # PyBullet physics update with ground effect, drag, and downwash PYB_WIND = 6 # PyBullet physics update with drag and wind PYB_TETHER = 7 # PyBullet physics update with tether #### String representation of Physics ############################################################## def __str__(self): return self.name ###################################################################################################################################################### #### Camera capture image type enumeration ########################################################################################################### ###################################################################################################################################################### class ImageType(Enum): RGB = 0 # Red, green, blue (and alpha) DEP = 1 # Depth SEG = 2 # Segmentation by object id BW = 3 # Black and white ###################################################################################################################################################### #### Base multi-drone environment class ############################################################################################################## ###################################################################################################################################################### class BaseAviary(gym.Env): metadata = {'render.modes': ['human']} #################################################################################################### #### Initialize the environment #################################################################### #################################################################################################### #### Arguments ##################################################################################### #### - drone_model (DroneModel) desired drone type (associated to an .urdf file) ########### #### - num_drones (int) desired number of drones in the aviary ##################### #### - neighbourhood_radius (float) used to compute the drones' adjacency matrix, in meters #### #### - initial_xyzs ((3,1) array) initial XYZ position of the drones ######################### #### - initial_rpys ((3,1) array) initial orientations of the drones (radians) ############### #### - physics (Physics) desired implementation of physics/dynamics ################# #### - freq (int) the frequency (Hz) at which the physics engine advances #### #### - aggregate_phy_steps (int) number of physics updates within one call of .step() ####### #### - gui (bool) whether to use PyBullet's GUI ############################## #### - record (bool) whether to save a video of the simulation ################## #### - obstacles (bool) whether to add obstacles to the simulation ################# #### - user_debug_gui (bool) whether to draw the drones' axes and the GUI sliders ####### #################################################################################################### def __init__(self, drone_model: DroneModel=DroneModel.CF2X, num_drones: int=1, neighbourhood_radius: float=np.inf, initial_xyzs=None, initial_rpys=None, physics: Physics=Physics.PYB, freq: int=240, aggregate_phy_steps: int=1, gui=False, record=False, obstacles=False, maxWindSpeed=8.0, user_debug_gui=True): #### Constants ##################################################################################### self.G = 9.8; self.RAD2DEG = 180/np.pi; self.DEG2RAD = np.pi/180 self.SIM_FREQ = freq; self.TIMESTEP = 1./self.SIM_FREQ; self.AGGR_PHY_STEPS = aggregate_phy_steps #### Parameters #################################################################################### self.NUM_DRONES = num_drones; self.NEIGHBOURHOOD_RADIUS = neighbourhood_radius self.N_ACTIONS = 4 self.INIT_X_BOUND = 0.0 self.INIT_Y_BOUND = 0.0 self.INIT_Z_BOUND = 0.0 self.INIT_R_BOUND = 0.0 self.INIT_P_BOUND = 0.0 self.INIT_YAW_BOUND = 0 #### Tether Parameters ############################################################################# self.last_tether_force_mag = 0.0 self.tether_force_mag = 0.0 self.TETHER_MIN_LENGTH = None self.MAX_TETHER_FORCE = None #### Options ####################################################################################### self.DRONE_MODEL = drone_model; self.GUI = gui; self.RECORD = record; self.PHYSICS = physics self.OBSTACLES = obstacles; self.USER_DEBUG = user_debug_gui if self.DRONE_MODEL==DroneModel.CF2X: self.URDF = "cf2x.urdf" elif self.DRONE_MODEL==DroneModel.CF2P: self.URDF = "cf2p.urdf" elif self.DRONE_MODEL==DroneModel.HB: self.URDF = "hb.urdf" elif self.DRONE_MODEL==DroneModel.MAMBO: self.URDF = "mambo.urdf" elif self.DRONE_MODEL==DroneModel.CERLAB: self.URDF = "cerlab.urdf" #### Load the drone properties from the .urdf file ################################################# self.M, self.L, self.THRUST2WEIGHT_RATIO, self.J, self.J_INV, self.KF, self.KM, self.COLLISION_H, self.COLLISION_R, self.COLLISION_Z_OFFSET, self.MAX_SPEED_KMH, self.GND_EFF_COEFF, self.PROP_RADIUS, self.DRAG_COEFF, self.DW_COEFF_1, self.DW_COEFF_2, self.DW_COEFF_3 = self._parseURDFParameters() print("[INFO] BaseAviary.__init__() loaded parameters from the drone's .urdf:\n[INFO] m {:f}, L {:f},\n[INFO] ixx {:f}, iyy {:f}, izz {:f},\n[INFO] kf {:f}, km {:f},\n[INFO] t2w {:f}, max_speed_kmh {:f},\n[INFO] gnd_eff_coeff {:f}, prop_radius {:f},\n[INFO] drag_xy_coeff {:f}, drag_z_coeff {:f},\n[INFO] dw_coeff_1 {:f}, dw_coeff_2 {:f}, dw_coeff_3 {:f}".format( self.M, self.L, self.J[0,0], self.J[1,1], self.J[2,2], self.KF, self.KM, self.THRUST2WEIGHT_RATIO, self.MAX_SPEED_KMH, self.GND_EFF_COEFF, self.PROP_RADIUS, self.DRAG_COEFF[0], self.DRAG_COEFF[2], self.DW_COEFF_1, self.DW_COEFF_2, self.DW_COEFF_3) ) #### Compute constants ############################################################################# self.GRAVITY = self.G*self.M; self.HOVER_RPM = np.sqrt(self.GRAVITY/(4*self.KF)) self.MAX_RPM = np.sqrt((self.THRUST2WEIGHT_RATIO*self.GRAVITY)/(4*self.KF)); self.MAX_THRUST = (4*self.KF*self.MAX_RPM**2) self.MAX_XY_TORQUE = (self.L*self.KF*self.MAX_RPM**2); self.MAX_Z_TORQUE = (2*self.KM*self.MAX_RPM**2) self.GND_EFF_H_CLIP = 0.25 * self.PROP_RADIUS * np.sqrt( (15 * self.MAX_RPM**2 * self.KF * self.GND_EFF_COEFF) / self.MAX_THRUST ) self.MAXWINDSPEED = maxWindSpeed #### Connect to PyBullet ########################################################################### if self.GUI: #### With debug GUI ################################################################################ self.CLIENT = p.connect(p.GUI) # p.connect(p.GUI, options="--opengl2") for i in [p.COV_ENABLE_RGB_BUFFER_PREVIEW, p.COV_ENABLE_DEPTH_BUFFER_PREVIEW, p.COV_ENABLE_SEGMENTATION_MARK_PREVIEW]: p.configureDebugVisualizer(i, 0, physicsClientId=self.CLIENT) p.resetDebugVisualizerCamera(cameraDistance=3, cameraYaw=-30, cameraPitch=-30, cameraTargetPosition=[0,0,0], physicsClientId=self.CLIENT) ret = p.getDebugVisualizerCamera(physicsClientId=self.CLIENT); #print("viewMatrix", ret[2]); print("projectionMatrix", ret[3]) if self.USER_DEBUG: #### Add input sliders to the GUI ################################################################## self.SLIDERS = -1*np.ones(self.N_ACTIONS) for i in range(4): self.SLIDERS[i] = p.addUserDebugParameter("Propeller "+str(i)+" RPM", 0, self.MAX_RPM, self.HOVER_RPM, physicsClientId=self.CLIENT) if self.N_ACTIONS == 5: self.SLIDERS[4] = p.addUserDebugParameter("Tether Force", 0, self.MAX_TETHER_FORCE, 0, physicsClientId=self.CLIENT) self.INPUT_SWITCH = p.addUserDebugParameter("Use GUI RPM", 9999, -1, 0, physicsClientId=self.CLIENT) else: #### Without debug GUI ############################################################################# self.CLIENT = p.connect(p.DIRECT) p.setAdditionalSearchPath(pybullet_data.getDataPath()); plugin = p.loadPlugin(egl.get_filename(), "_eglRendererPlugin"); print("plugin=", plugin) if self.RECORD: #### Set the camera parameters to save frames in DIRECT mode ####################################### self.VID_WIDTH=int(640); self.VID_HEIGHT=int(480); self.FRAME_PER_SEC = 24; self.CAPTURE_FREQ = int(self.SIM_FREQ/self.FRAME_PER_SEC) self.CAM_VIEW = p.computeViewMatrixFromYawPitchRoll(distance=3, yaw=-30, pitch=-30, roll=0, cameraTargetPosition=[0,0,0], upAxisIndex=2, physicsClientId=self.CLIENT) self.CAM_PRO = p.computeProjectionMatrixFOV(fov=60.0, aspect=self.VID_WIDTH/self.VID_HEIGHT, nearVal=0.1, farVal=1000.0) #### Set initial poses ############################################################################# self._setInitialPoses(initial_xyzs, initial_rpys) #### Create action and observation spaces ########################################################## self.action_space = self._actionSpace() self.observation_space = self._observationSpace() #### Housekeeping ################################################################################## self._housekeeping() #### Update and store the drones kinematic information ############################################# self._updateAndStoreKinematicInformation() #### Start video recording ######################################################################### self._startVideoRecording() #################################################################################################### #### Reset the environment ######################################################################### #################################################################################################### #### Returns ####################################################################################### #### - obs (..) initial observation, see _computeObs() in the child class ## #################################################################################################### def reset(self): p.resetSimulation(physicsClientId=self.CLIENT) #### Housekeeping ################################################################################## self._housekeeping() #### Update and store the drones kinematic information ############################################# self._updateAndStoreKinematicInformation() #### Start video recording ######################################################################### self._startVideoRecording() #### Return the initial observation ################################################################ return self._computeObs() #################################################################################################### #### Advance the environment by one simulation step ################################################ #################################################################################################### #### Arguments ##################################################################################### #### - action (..) to motors' speed, see _preprocessAction() in the child class #################################################################################################### #### Returns ####################################################################################### #### - obs (..) observation, see _computeObs() in the child class ########## #### - reward (..) reward value, see _computeReward() in the child class ###### #### - done (..) whether the current episode is over, see computeDone() ##### #### - info (Dict) currently unused, see _computeInfo() in the child class #### #################################################################################################### def step(self, action): #### Save a video frame in PNG format if RECORD=True and GUI=False ################################# if self.RECORD and not self.GUI and self.step_counter%self.CAPTURE_FREQ==0: [w, h, rgb, dep, seg] = p.getCameraImage(width=self.VID_WIDTH, height=self.VID_HEIGHT, shadow=1, viewMatrix=self.CAM_VIEW, projectionMatrix=self.CAM_PRO, renderer=p.ER_TINY_RENDERER, flags=p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX, physicsClientId=self.CLIENT) (Image.fromarray(np.reshape(rgb, (h, w, 4)), 'RGBA')).save(self.IMG_PATH+"frame_"+str(self.FRAME_NUM)+".png") #### Save the depth or segmentation view instead ################################################### # dep = ((dep-np.min(dep)) * 255 / (np.max(dep)-np.min(dep))).astype('uint8'); (Image.fromarray(np.reshape(dep, (h, w)))).save(self.IMG_PATH+"frame_"+str(self.FRAME_NUM)+".png") # seg = ((seg-np.min(seg)) * 255 / (np.max(seg)-np.min(seg))).astype('uint8'); (Image.fromarray(np.reshape(seg, (h, w)))).save(self.IMG_PATH+"frame_"+str(self.FRAME_NUM)+".png") self.FRAME_NUM += 1 #### Read the GUI's input parameters ############################################################### if self.GUI and self.USER_DEBUG: current_input_switch = p.readUserDebugParameter(self.INPUT_SWITCH, physicsClientId=self.CLIENT) if current_input_switch>self.last_input_switch: self.last_input_switch = current_input_switch self.USE_GUI_RPM = True if self.USE_GUI_RPM==False else False if self.USE_GUI_RPM: for i in range(self.N_ACTIONS): self.gui_input[i] = p.readUserDebugParameter(int(self.SLIDERS[i]), physicsClientId=self.CLIENT) clipped_action = np.tile(self.gui_input,(self.NUM_DRONES,1)) if self.step_counter%(self.SIM_FREQ/2)==0: self.GUI_INPUT_TEXT = [ p.addUserDebugText("Using GUI RPM", textPosition=[0,0,0], textColorRGB=[1,0,0], lifeTime=1, textSize=2, parentObjectUniqueId=self.DRONE_IDS[i], parentLinkIndex=-1, replaceItemUniqueId=int(self.GUI_INPUT_TEXT[i]), physicsClientId=self.CLIENT) for i in range(self.NUM_DRONES) ] #### Save, preprocess, and clip the action to the maximum RPM ###################################### else: clipped_action = self._actionSaveAndPreprocess(action) #### Repeat for as many as the aggregate physics steps/dynamics updates ############################ for _ in range(self.AGGR_PHY_STEPS): #### Re-update and store the drones kinematic info to use DYN or compute the aerodynamics effects ## if self.AGGR_PHY_STEPS>1 and self.PHYSICS in [Physics.DYN, Physics.PYB_GND, Physics.PYB_DRAG, Physics.PYB_WIND, Physics.PYB_TETHER, Physics.PYB_DW, Physics.PYB_GND_DRAG_DW]: self._updateAndStoreKinematicInformation() #### Step the simulation using the desired physics update ########################################## for i in range (self.NUM_DRONES): if self.PHYSICS==Physics.PYB: self._physics(clipped_action[i,:], i) elif self.PHYSICS==Physics.DYN: self._dynamics(clipped_action[i,:], i) elif self.PHYSICS==Physics.PYB_GND: self._physics(clipped_action[i,:], i); self._groundEffect(clipped_action[i,:], i) elif self.PHYSICS==Physics.PYB_DRAG: self._physics(clipped_action[i,:], i); self._drag(self.last_clipped_action[i,:], i) elif self.PHYSICS==Physics.PYB_DW: self._physics(clipped_action[i,:], i); self._downwash(i) elif self.PHYSICS==Physics.PYB_GND_DRAG_DW: self._physics(clipped_action[i,:], i); self._groundEffect(clipped_action[i,:], i); self._drag(self.last_clipped_action[i,:], i); self._downwash(i) elif self.PHYSICS==Physics.PYB_WIND: self._physics(clipped_action[i,:], i); self._dragWithWind(self.last_clipped_action[i,:], i) elif self.PHYSICS==Physics.PYB_TETHER: self._physics(clipped_action[i,0:self.N_ACTIONS-1], i); self._simpleTetherForce(clipped_action[i,self.N_ACTIONS-1], i) # TODO: ask ryan about this line. why _dragWithWind above? #### Let PyBullet compute the new state, unless using Physics.DYN ################################## if self.PHYSICS!=Physics.DYN: p.stepSimulation(physicsClientId=self.CLIENT) #### Save the last applied action to compute drag in the next step ################################# if self.PHYSICS in [Physics.PYB_DRAG, Physics.PYB_GND_DRAG_DW, Physics.PYB_WIND, Physics.PYB_TETHER]: self.last_clipped_action = clipped_action #### Update and store the drones kinematic information ############################################# self._updateAndStoreKinematicInformation() #### Prepare the return values ##################################################################### obs = self._computeObs() reward = self._computeReward(obs) done = self._computeDone(obs) info = self._computeInfo(obs) #### Advance the step counter ###################################################################### self.step_counter = self.step_counter + (1 * self.AGGR_PHY_STEPS) return obs, reward, done, info #################################################################################################### #### Print a textual output of the environment ##################################################### #################################################################################################### def render(self, mode='human', close=False): if self.first_render_call and not self.GUI: print("[WARNING] BaseAviary.render() is implemented as text-only, re-initialize the environment using Aviary(gui=True) to use PyBullet's graphical interface") self.first_render_call = False print("\n[INFO] BaseAviary.render() ——— it {:04d}".format(self.step_counter), "——— wall-clock time {:.1f}s,".format(time.time()-self.RESET_TIME), "simulation time {:.1f}s@{:d}Hz ({:.2f}x)".format(self.step_counter*self.TIMESTEP, self.SIM_FREQ, (self.step_counter*self.TIMESTEP)/(time.time()-self.RESET_TIME))) for i in range (self.NUM_DRONES): print("[INFO] BaseAviary.render() ——— drone {:d}".format(i), "——— x {:+06.2f}, y {:+06.2f}, z {:+06.2f}".format(self.pos[i,0], self.pos[i,1], self.pos[i,2]), "——— velocity {:+06.2f}, {:+06.2f}, {:+06.2f}".format(self.vel[i,0], self.vel[i,1], self.vel[i,2]), "——— roll {:+06.2f}, pitch {:+06.2f}, yaw {:+06.2f}".format(self.rpy[i,0]*self.RAD2DEG, self.rpy[i,1]*self.RAD2DEG, self.rpy[i,2]*self.RAD2DEG), "——— angular velocities {:+06.2f}, {:+06.2f}, {:+06.2f} ——— ".format(self.ang_v[i,0]*self.RAD2DEG, self.ang_v[i,1]*self.RAD2DEG, self.ang_v[i,2]*self.RAD2DEG)) #################################################################################################### #### Close the environment ######################################################################### #################################################################################################### def close(self): if self.RECORD and self.GUI: p.stopStateLogging(self.VIDEO_ID, physicsClientId=self.CLIENT) p.disconnect(physicsClientId=self.CLIENT) #################################################################################################### #### Return the PyBullet Client Id ################################################################# #################################################################################################### def getPyBulletClient(self): return self.CLIENT #################################################################################################### #### Return the Drone Id ########################################################################### #################################################################################################### def getDroneIds(self): return self.DRONE_IDS #################################################################################################### #### Housekeeping of variables and PyBullet's parameters/objects in the reset() function ########### #################################################################################################### def _housekeeping(self): #### Initialize/reset counters and zero-valued variables ########################################### self.RESET_TIME = time.time(); self.step_counter = 0; self.first_render_call = True self.X_AX = -1*np.ones(self.NUM_DRONES); self.Y_AX = -1*np.ones(self.NUM_DRONES); self.Z_AX = -1*np.ones(self.NUM_DRONES); self.TEHTER_AX = -1*np.ones(self.NUM_DRONES) self.GUI_INPUT_TEXT = -1*np.ones(self.NUM_DRONES); self.USE_GUI_RPM=False; self.last_input_switch = 0 self.last_action = -1*np.ones((self.NUM_DRONES,self.N_ACTIONS)) self.last_clipped_action = np.zeros((self.NUM_DRONES,self.N_ACTIONS)); self.gui_input = np.zeros(self.N_ACTIONS) self.no_pybullet_dyn_accs = np.zeros((self.NUM_DRONES,3)) #### Initialize the drones kinemaatic information ################################################## self.pos = np.zeros((self.NUM_DRONES,3)); self.quat = np.zeros((self.NUM_DRONES,4)); self.rpy = np.zeros((self.NUM_DRONES,3)) self.vel = np.zeros((self.NUM_DRONES,3)); self.ang_v = np.zeros((self.NUM_DRONES,3)) #### Set PyBullet's parameters ##################################################################### p.setGravity(0, 0, -self.G, physicsClientId=self.CLIENT) p.setRealTimeSimulation(0, physicsClientId=self.CLIENT) p.setTimeStep(self.TIMESTEP, physicsClientId=self.CLIENT) p.setAdditionalSearchPath(pybullet_data.getDataPath(), physicsClientId=self.CLIENT) #### Load ground plane, drone and obstacles models ################################################# self.PLANE_ID = p.loadURDF("plane.urdf", physicsClientId=self.CLIENT) self.DRONE_IDS = np.array([p.loadURDF(os.path.dirname(os.path.abspath(__file__))+"/../assets/"+self.URDF, self.INIT_XYZS[i,:], p.getQuaternionFromEuler(self.INIT_RPYS[i,:]), physicsClientId=self.CLIENT) for i in range(self.NUM_DRONES)]) for i in range(self.NUM_DRONES): #### Show the frame of reference of the drone, note thet it can severly slow down the GUI ########## if self.GUI and self.USER_DEBUG: self._showDroneLocalAxes(i) #### Disable collisions between drones' and the ground plane, e.g., to start a drone at [0,0,0] #### # p.setCollisionFilterPair(bodyUniqueIdA=self.PLANE_ID, bodyUniqueIdB=self.DRONE_IDS[i], linkIndexA=-1, linkIndexB=-1, enableCollision=0, physicsClientId=self.CLIENT) if self.OBSTACLES: self._addObstacles() #################################################################################################### #### Update and store the drones kinemaatic information ############################################ #################################################################################################### def _updateAndStoreKinematicInformation(self): for i in range (self.NUM_DRONES): self.pos[i], self.quat[i] = p.getBasePositionAndOrientation(self.DRONE_IDS[i], physicsClientId=self.CLIENT) self.rpy[i] = p.getEulerFromQuaternion(self.quat[i]) self.vel[i], self.ang_v[i] = p.getBaseVelocity(self.DRONE_IDS[i], physicsClientId=self.CLIENT) #################################################################################################### #### Start saving the video output as .mp4, if GUI is True, or .png, otherwise #################### #################################################################################################### def _startVideoRecording(self): if self.RECORD and self.GUI: self.VIDEO_ID = p.startStateLogging(loggingType=p.STATE_LOGGING_VIDEO_MP4, fileName=os.path.dirname(os.path.abspath(__file__))+"/../../files/video-"+datetime.now().strftime("%m.%d.%Y_%H.%M.%S")+".mp4", physicsClientId=self.CLIENT) if self.RECORD and not self.GUI: self.FRAME_NUM = 0; self.IMG_PATH = os.path.dirname(os.path.abspath(__file__))+"/../../files/video-"+datetime.now().strftime("%m.%d.%Y_%H.%M.%S")+"/"; os.makedirs(os.path.dirname(self.IMG_PATH), exist_ok=True) #################################################################################################### #### Return the state vector of the nth drone ###################################################### #################################################################################################### #### Arguments ##################################################################################### #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### #### Returns ####################################################################################### #### - state ((20,) array) the state vector of the nth drone ########################## #################################################################################################### def _getDroneStateVector(self, nth_drone): state = np.hstack([self.pos[nth_drone,:], self.quat[nth_drone,:], self.rpy[nth_drone,:], self.vel[nth_drone,:], self.ang_v[nth_drone,:], self.last_action[nth_drone,:]]) return state.reshape(20,) #################################################################################################### #### Return camera captures from the nth drone POV ################################################# #################################################################################################### #### Arguments ##################################################################################### #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #### - segmentation (bool) whehter to compute the compute the segmentation mask ####### #################################################################################################### #### Returns ####################################################################################### #### - rgb ((h,w,4) array) RBG(A) image captured from the nth_drone's POV ############# #### - dep ((h,w) array) depth image captured from the nth_drone's POV ############## #### - seg ((h,w) array) segmentation image captured from the nth_drone's POV ####### #################################################################################################### def _getDroneImages(self, nth_drone, segmentation: bool=True): if self.IMG_RES is None: print("[ERROR] in BaseAviary._getDroneImages(), remember to set self.IMG_RES to np.array([width, height])"); exit() rot_mat = np.array(p.getMatrixFromQuaternion(self.quat[nth_drone,:])).reshape(3,3) #### Set target point and camera view and projection matrices ###################################### target = np.dot(rot_mat,np.array([1000,0,0])) + np.array(self.pos[nth_drone,:]) DRONE_CAM_VIEW = p.computeViewMatrix(cameraEyePosition=self.pos[nth_drone,:]+np.array([0,0,self.L]), cameraTargetPosition=target, cameraUpVector=[0,0,1], physicsClientId=self.CLIENT) DRONE_CAM_PRO = p.computeProjectionMatrixFOV(fov=60.0, aspect=1.0, nearVal=self.L, farVal=1000.0) SEG_FLAG = p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX if segmentation else p.ER_NO_SEGMENTATION_MASK [w, h, rgb, dep, seg] = p.getCameraImage(width=self.IMG_RES[0], height=self.IMG_RES[1], shadow=1, viewMatrix=DRONE_CAM_VIEW, projectionMatrix=DRONE_CAM_PRO, flags=SEG_FLAG, physicsClientId=self.CLIENT) rgb = np.reshape(rgb, (h, w, 4)); dep = np.reshape(dep, (h, w)); seg = np.reshape(seg, (h, w)) return rgb, dep, seg #################################################################################################### #### Save an image returned by _getDroneImages() as a PNG file ##################################### #################################################################################################### #### Arguments ##################################################################################### #### - img_type (ImageType) image type: RGBA, depth, segmentation, b&w (from RGB) ###### #### - img_input ((h,w,?) array) matrix with 1 (depth/seg) or 4 (RGBA) channels ############# #### - path (str) where to save the images as PNGs ########################### #### - frame_num (int) number to append to the frame's filename ################### #################################################################################################### def _exportImage(self, img_type: ImageType, img_input, path: str, frame_num: int=0): if img_type==ImageType.RGB: (Image.fromarray(img_input.astype('uint8'), 'RGBA')).save(path+"frame_"+str(frame_num)+".png") elif img_type==ImageType.DEP: temp = ((img_input-np.min(img_input)) * 255 / (np.max(img_input)-np.min(img_input))).astype('uint8') elif img_type==ImageType.SEG: temp = ((img_input-np.min(img_input)) * 255 / (np.max(img_input)-np.min(img_input))).astype('uint8') elif img_type==ImageType.BW: temp = (np.sum(img_input[:,:,0:2], axis=2) / 3).astype('uint8') else: print("[ERROR] in BaseAviary._exportImage(), unknown ImageType"); exit() if img_type!=ImageType.RGB: (Image.fromarray(temp)).save(path+"frame_"+str(frame_num)+".png") #################################################################################################### #### Compute the adjacency matrix of a multi-drone system using NEIGHBOURHOOD_RADIUS ################## #################################################################################################### #### Returns ####################################################################################### #### - adj_mat ((NUM_DRONES,NUM_DRONES) array) adj_mat[i,j]=1 if i,j are neighbors, 0 otherwise # #################################################################################################### def _getAdjacencyMatrix(self): adjacency_mat = np.identity(self.NUM_DRONES) for i in range(self.NUM_DRONES-1): for j in range(self.NUM_DRONES-i-1): if np.linalg.norm(self.pos[i,:]-self.pos[j+i+1,:])<self.NEIGHBOURHOOD_RADIUS: adjacency_mat[i,j+i+1] = adjacency_mat[j+i+1,i] = 1 return adjacency_mat #################################################################################################### #### Base PyBullet physics implementation ########################################################## #################################################################################################### #### Arguments ##################################################################################### #### - rpm ((4,1) array) RPM values of the 4 motors ################################# #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _physics(self, rpm, nth_drone): forces = np.array(rpm**2)*self.KF torques = np.array(rpm**2)*self.KM z_torque = (-torques[0] + torques[1] - torques[2] + torques[3]) for i in range(4): p.applyExternalForce(self.DRONE_IDS[nth_drone], i, forceObj=[0,0,forces[i]], posObj=[0,0,0], flags=p.LINK_FRAME, physicsClientId=self.CLIENT) p.applyExternalTorque(self.DRONE_IDS[nth_drone], 4, torqueObj=[0,0,z_torque], flags=p.LINK_FRAME, physicsClientId=self.CLIENT) #################################################################################################### #### PyBullet implementation of ground effect, from (Shi et al., 2019) ############################# #################################################################################################### #### Arguments ##################################################################################### #### - rpm ((4,1) array) RPM values of the 4 motors ################################# #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _groundEffect(self, rpm, nth_drone): #### Kinematic information of all links (propellers and center of mass) ############################ link_states = np.array(p.getLinkStates(self.DRONE_IDS[nth_drone], linkIndices=[0,1,2,3,4], computeLinkVelocity=1, computeForwardKinematics=1, physicsClientId=self.CLIENT)) #### Simple, per-propeller ground effects ########################################################## prop_heights = np.array([link_states[0,0][2], link_states[1,0][2], link_states[2,0][2], link_states[3,0][2]]) prop_heights = np.clip(prop_heights, self.GND_EFF_H_CLIP, np.inf) gnd_effects = np.array(rpm**2) * self.KF * self.GND_EFF_COEFF * (self.PROP_RADIUS/(4 * prop_heights))**2 if np.abs(self.rpy[nth_drone,0])<np.pi/2 and np.abs(self.rpy[nth_drone,1])<np.pi/2: for i in range(4): p.applyExternalForce(self.DRONE_IDS[nth_drone], i, forceObj=[0,0,gnd_effects[i]], posObj=[0,0,0], flags=p.LINK_FRAME, physicsClientId=self.CLIENT) #### TODO: a more realistic model would account for the drone's attitude and its z-axis velocity in the world frame #################################################################################################### #### PyBullet implementation of drag, from (Forster, 2015) ######################################### #################################################################################################### #### Arguments ##################################################################################### #### - rpm ((4,1) array) RPM values of the 4 motors ################################# #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _drag(self, rpm, nth_drone): #### Rotation matrix of the base ################################################################### base_rot = np.array(p.getMatrixFromQuaternion(self.quat[nth_drone,:])).reshape(3,3) #### Simple draft model applied to the base/center of mass ######################################### drag_factors = -1 * self.DRAG_COEFF * np.sum(np.array(2*np.pi*rpm/60)) drag = np.dot(base_rot, drag_factors*np.array(self.vel[nth_drone,:])) p.applyExternalForce(self.DRONE_IDS[nth_drone], 4, forceObj=drag, posObj=[0,0,0], flags=p.LINK_FRAME, physicsClientId=self.CLIENT) #################################################################################################### #### PyBullet implementation of drag with Wind, from (Forster, 2015) ############################### #################################################################################################### #### Arguments ##################################################################################### #### - rpm ((4,1) array) RPM values of the 4 motors ################################# #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _dragWithWind(self, rpm, nth_drone): #### Rotation matrix of the base ################################################################### base_rot = np.array(p.getMatrixFromQuaternion(self.quat[nth_drone,:])).reshape(3,3) #### Simple draft model applied to the base/center of mass ######################################### drag_factors = -1 * self.DRAG_COEFF * np.sum(np.array(2*np.pi*rpm/60)) velocityInWind = np.array(self.vel[nth_drone,:]) - self.wind[:] drag = np.dot(base_rot, drag_factors*velocityInWind) p.applyExternalForce(self.DRONE_IDS[nth_drone], 4, forceObj=drag, posObj=[0,0,0], flags=p.LINK_FRAME, physicsClientId=self.CLIENT) #################################################################################################### #### PyBullet implementation of simple tether ###################################################### #################################################################################################### #### Arguments ##################################################################################### #### - mag (double) force magnitude of tether ################################## #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _simpleTetherForce(self, _mag, nth_drone): self.last_tether_force_mag = self.tether_force_mag self.tether_force_mag = _mag #### Determine if within tether limit ########################################################## if(np.linalg.norm(self.pos[nth_drone,:]) > self.TETHER_MIN_LENGTH): #### Apply force ############################################################################### p.applyExternalForce(self.DRONE_IDS[nth_drone], -1, forceObj=(self.tether_force_mag*-self.pos[nth_drone,:]/np.linalg.norm(self.pos[nth_drone,:],2)).tolist(), posObj=[0,0,0], flags=p.WORLD_FRAME, physicsClientId=self.CLIENT) tether_color = [0.1,1.0,0.1] else: tether_color = [0.8,0.1,0.1] #### GUI elements ############################################################################## if self.GUI: self.TETHER_AX[nth_drone] = p.addUserDebugLine(lineWidth=5, lineFromXYZ=[0,0,0], lineToXYZ=(self.pos[nth_drone,:]).tolist(), lineColorRGB=tether_color, replaceItemUniqueId=int(self.TETHER_AX[nth_drone]), physicsClientId=self.CLIENT) #################################################################################################### #### PyBullet implementation of ground effect, SiQi Zhou's modelling ############################### #################################################################################################### #### Arguments ##################################################################################### #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _downwash(self, nth_drone): for i in range(self.NUM_DRONES): delta_z = self.pos[i,2]-self.pos[nth_drone,2]; delta_xy = np.linalg.norm(np.array(self.pos[i,0:2])-np.array(self.pos[nth_drone,0:2])) if delta_z>0 and delta_xy<10: # Ignore drones more than 10 meters away alpha = self.DW_COEFF_1 * (self.PROP_RADIUS/(4*delta_z))**2; beta = self.DW_COEFF_2 * delta_z + self.DW_COEFF_3 downwash = [0, 0, - alpha * np.exp(-.5*(delta_xy/beta)**2)] p.applyExternalForce(self.DRONE_IDS[nth_drone], 4, forceObj=downwash, posObj=[0,0,0], flags=p.LINK_FRAME, physicsClientId=self.CLIENT) #################################################################################################### #### Explicit dynamics implementation from github.com/utiasDSL/dsl__projects__benchmark ############ #################################################################################################### #### Arguments ##################################################################################### #### - rpm ((4,1) array) RPM values of the 4 motors ################################# #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _dynamics(self, rpm, nth_drone): #### Current state ################################################################################# pos = self.pos[nth_drone,:]; quat = self.quat[nth_drone,:]; rpy = self.rpy[nth_drone,:] vel = self.vel[nth_drone,:]; ang_v = self.ang_v[nth_drone,:] rotation = np.array(p.getMatrixFromQuaternion(quat)).reshape(3,3) #### Compute forces and torques #################################################################### forces = np.array(rpm**2) * self.KF thrust = np.array([0, 0, np.sum(forces)]) thrust_world_frame = np.dot(rotation,thrust) force_world_frame = thrust_world_frame - np.array([0, 0, self.GRAVITY]) z_torques = np.array(rpm**2)*self.KM z_torque = (-z_torques[0] + z_torques[1] - z_torques[2] + z_torques[3]) if self.DRONE_MODEL==DroneModel.CF2X or self.DRONE_MODEL==DroneModel.CERLAB: x_torque = (forces[0] + forces[1] - forces[2] - forces[3]) * (self.L/np.sqrt(2)) y_torque = (- forces[0] + forces[1] + forces[2] - forces[3]) * (self.L/np.sqrt(2)) elif self.DRONE_MODEL==DroneModel.CF2P or self.DRONE_MODEL==DroneModel.HB: x_torque = (forces[1] - forces[3]) * self.L y_torque = (-forces[0] + forces[2]) * self.L torques = np.array([x_torque, y_torque, z_torque]) torques = torques - np.cross(ang_v, np.dot(self.J, ang_v)) ang_vel_deriv = np.dot(self.J_INV, torques) self.no_pybullet_dyn_accs[nth_drone] = force_world_frame / self.M #### Update state ################################################################################## vel = vel + self.TIMESTEP * self.no_pybullet_dyn_accs[nth_drone] ang_v = ang_v + self.TIMESTEP * ang_vel_deriv pos = pos + self.TIMESTEP * vel rpy = rpy + self.TIMESTEP * ang_v #### Set PyBullet's state ########################################################################## p.resetBasePositionAndOrientation(self.DRONE_IDS[nth_drone], pos, p.getQuaternionFromEuler(rpy), physicsClientId=self.CLIENT) p.resetBaseVelocity(self.DRONE_IDS[nth_drone], vel, ang_v, physicsClientId=self.CLIENT) #################################################################################################### #### Denormalize the [-1,1] range to the [0, MAX RPM] range ######################################## #################################################################################################### #### Arguments ##################################################################################### #### - action ((4,1) array) normalized [-1,1] actions applied to the 4 motors ########## #################################################################################################### #### Returns ####################################################################################### #### - rpm ((4,1) array) RPM values to apply to the 4 motors ######################## #################################################################################################### def _normalizedActionToRPM(self, action): if np.any(np.abs(action))>1: print("\n[ERROR] it", self.step_counter, "in BaseAviary._normalizedActionToRPM(), out-of-bound action") return np.where(action <= 0, (action+1)*self.HOVER_RPM, action*self.MAX_RPM) # Non-linear mapping: -1 -> 0, 0 -> HOVER_RPM, 1 -> MAX_RPM #################################################################################################### #### Save an action into self.last_action disambiguating between array and dict inputs ############# #################################################################################################### #### Arguments ##################################################################################### #### - action ((4,1) array or dict) an array or a dict of arrays to be stored in last_action ### #################################################################################################### def _saveLastAction(self, action): if isinstance(action, collections.Mapping): for k, v in action.items(): self.last_action[int(k),:] = v else: self.last_action = np.reshape(action, (self.NUM_DRONES, self.N_ACTIONS)) #################################################################################################### #### Draw the local frame of the nth drone ######################################################### #################################################################################################### #### Arguments ##################################################################################### #### - nth_drone (int) order position of the drone in list self.DRONE_IDS ######### #################################################################################################### def _showDroneLocalAxes(self, nth_drone): if self.GUI: AXIS_LENGTH = 2*self.L self.X_AX[nth_drone] = p.addUserDebugLine(lineFromXYZ=[0,0,0], lineToXYZ=[AXIS_LENGTH,0,0], lineColorRGB=[1,0,0], parentObjectUniqueId=self.DRONE_IDS[nth_drone], parentLinkIndex=-1, replaceItemUniqueId=int(self.X_AX[nth_drone]), physicsClientId=self.CLIENT) self.Y_AX[nth_drone] = p.addUserDebugLine(lineFromXYZ=[0,0,0], lineToXYZ=[0,AXIS_LENGTH,0], lineColorRGB=[0,1,0], parentObjectUniqueId=self.DRONE_IDS[nth_drone], parentLinkIndex=-1, replaceItemUniqueId=int(self.Y_AX[nth_drone]), physicsClientId=self.CLIENT) self.Z_AX[nth_drone] = p.addUserDebugLine(lineFromXYZ=[0,0,0], lineToXYZ=[0,0,AXIS_LENGTH], lineColorRGB=[0,0,1], parentObjectUniqueId=self.DRONE_IDS[nth_drone], parentLinkIndex=-1, replaceItemUniqueId=int(self.Z_AX[nth_drone]), physicsClientId=self.CLIENT) #################################################################################################### #### Add obstacles to the environment from .urdf files ############################################# #################################################################################################### def _addObstacles(self): p.loadURDF("samurai.urdf", physicsClientId=self.CLIENT) p.loadURDF("duck_vhacd.urdf", [-.5,-.5,.05], p.getQuaternionFromEuler([0,0,0]), physicsClientId=self.CLIENT) p.loadURDF("cube_no_rotation.urdf", [-.5,-2.5,.5], p.getQuaternionFromEuler([0,0,0]), physicsClientId=self.CLIENT) p.loadURDF("sphere2.urdf", [0,2,.5], p.getQuaternionFromEuler([0,0,0]), physicsClientId=self.CLIENT) #################################################################################################### #### Load parameters from the .urdf file ########################################################### #################################################################################################### def _parseURDFParameters(self): URDF_TREE = etxml.parse(os.path.dirname(os.path.abspath(__file__))+"/../assets/"+self.URDF).getroot() M = float(URDF_TREE[1][0][1].attrib['value']); L = float(URDF_TREE[0].attrib['arm']); THRUST2WEIGHT_RATIO = float(URDF_TREE[0].attrib['thrust2weight']) IXX = float(URDF_TREE[1][0][2].attrib['ixx']); IYY = float(URDF_TREE[1][0][2].attrib['iyy']); IZZ = float(URDF_TREE[1][0][2].attrib['izz']) J = np.diag([IXX, IYY, IZZ]); J_INV = np.linalg.inv(J); KF = float(URDF_TREE[0].attrib['kf']); KM = float(URDF_TREE[0].attrib['km']) COLLISION_H = float(URDF_TREE[1][2][1][0].attrib['length']); COLLISION_R = float(URDF_TREE[1][2][1][0].attrib['radius']) COLLISION_SHAPE_OFFSETS = [float(s) for s in URDF_TREE[1][2][0].attrib['xyz'].split(' ')]; COLLISION_Z_OFFSET = COLLISION_SHAPE_OFFSETS[2] MAX_SPEED_KMH = float(URDF_TREE[0].attrib['max_speed_kmh']); GND_EFF_COEFF = float(URDF_TREE[0].attrib['gnd_eff_coeff']); PROP_RADIUS = float(URDF_TREE[0].attrib['prop_radius']) DRAG_COEFF_XY = float(URDF_TREE[0].attrib['drag_coeff_xy']); DRAG_COEFF_Z = float(URDF_TREE[0].attrib['drag_coeff_z']); DRAG_COEFF = np.array([DRAG_COEFF_XY, DRAG_COEFF_XY, DRAG_COEFF_Z]) DW_COEFF_1 = float(URDF_TREE[0].attrib['dw_coeff_1']); DW_COEFF_2 = float(URDF_TREE[0].attrib['dw_coeff_2']); DW_COEFF_3 = float(URDF_TREE[0].attrib['dw_coeff_3']) return M, L, THRUST2WEIGHT_RATIO, J, J_INV, KF, KM, COLLISION_H, COLLISION_R, COLLISION_Z_OFFSET, MAX_SPEED_KMH, GND_EFF_COEFF, PROP_RADIUS, DRAG_COEFF, DW_COEFF_1, DW_COEFF_2, DW_COEFF_3 #################################################################################################### #### Set initial xyz and rpy ###################################################################### #################################################################################################### #### Arguments ##################################################################################### #### - initial_xyzs ((3,1) array) initial x, y, and z position of drone in episode ############# #### - initial_rpys ((3,1) array) initial r, p, and y orientations of drone in episode ######### #################################################################################################### def _setInitialPoses(self, initial_xyzs, initial_rpys): if initial_xyzs is None: self.INIT_XYZS = np.vstack([ np.array([x*4*self.L for x in range(self.NUM_DRONES)]), np.array([y*4*self.L for y in range(self.NUM_DRONES)]), np.ones(self.NUM_DRONES) * (self.COLLISION_H/2-self.COLLISION_Z_OFFSET+.1) ]).transpose().reshape(self.NUM_DRONES,3) elif np.array(initial_xyzs).shape==(self.NUM_DRONES,3): self.INIT_XYZS = initial_xyzs else: print("[ERROR] invalid initial_xyzs in BaseAviary.__init__(), try initial_xyzs.reshape(NUM_DRONES,3)") if initial_rpys is None: self.INIT_RPYS = np.zeros((self.NUM_DRONES,3)) elif np.array(initial_rpys).shape==(self.NUM_DRONES,3): self.INIT_RPYS = initial_rpys else: print("[ERROR] invalid initial_rpys in BaseAviary.__init__(), try initial_rpys.reshape(NUM_DRONES,3)") #################################################################################################### #### Save, preprocess, and clip the action to the maximum RPM ###################################### #### Arguments ##################################################################################### #### - action ((N_ACTIONS,1) array) normalized [-1,1] actions taken by drones ################## #################################################################################################### def _actionSaveAndPreprocess(self, action): self._saveLastAction(action) return np.reshape(self._preprocessAction(action), (self.NUM_DRONES, self.N_ACTIONS)) #################################################################################################### #### Return the action space of the environment, to be implemented in a child class ################ #################################################################################################### def _actionSpace(self): raise NotImplementedError #################################################################################################### #### Return the observation space of the environment, to be implemented in a child class ########### #################################################################################################### def _observationSpace(self): raise NotImplementedError #################################################################################################### #### Return the current observation of the environment, to be implemented in a child class ######### #################################################################################################### def _computeObs(self): raise NotImplementedError #################################################################################################### #### Preprocess the action passed to .step() into motors' RPMs, to be implemented in a child class # #################################################################################################### #### Arguments ##################################################################################### #### - action (..) input to the environment's .step() function ################ #################################################################################################### def _preprocessAction(self, action): raise NotImplementedError #################################################################################################### #### Compute the current reward value(s), to be implemented in a child class ####################### #################################################################################################### #### Arguments ##################################################################################### #### - obs (..) the return of _computeObs() ################################ #################################################################################################### def _computeReward(self, obs): raise NotImplementedError #################################################################################################### #### Compute the current done value(s), to be implemented in a child class ######################### #################################################################################################### #### Arguments ##################################################################################### #### - obs (..) the return of _computeObs() ################################ #################################################################################################### def _computeDone(self, obs): raise NotImplementedError #################################################################################################### #### Compute the current info dict(s), to be implemented in a child class ########################## #################################################################################################### #### Arguments ##################################################################################### #### - obs (..) the return of _computeObs() ################################ #################################################################################################### def _computeInfo(self, obs): raise NotImplementedError
#!/usr/bin/env python # # Natural Language Toolkit: TGrep search # # Copyright (C) 2001-2021 NLTK Project # Author: Will Roberts <wildwilhelm@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ ============================================ TGrep search implementation for NLTK trees ============================================ This module supports TGrep2 syntax for matching parts of NLTK Trees. Note that many tgrep operators require the tree passed to be a ``ParentedTree``. External links: - `Tgrep tutorial <http://www.stanford.edu/dept/linguistics/corpora/cas-tut-tgrep.html>`_ - `Tgrep2 manual <http://tedlab.mit.edu/~dr/Tgrep2/tgrep2.pdf>`_ - `Tgrep2 source <http://tedlab.mit.edu/~dr/Tgrep2/>`_ Usage ===== >>> from nltk.tree import ParentedTree >>> from nltk.tgrep import tgrep_nodes, tgrep_positions >>> tree = ParentedTree.fromstring('(S (NP (DT the) (JJ big) (NN dog)) (VP bit) (NP (DT a) (NN cat)))') >>> list(tgrep_nodes('NN', [tree])) [[ParentedTree('NN', ['dog']), ParentedTree('NN', ['cat'])]] >>> list(tgrep_positions('NN', [tree])) [[(0, 2), (2, 1)]] >>> list(tgrep_nodes('DT', [tree])) [[ParentedTree('DT', ['the']), ParentedTree('DT', ['a'])]] >>> list(tgrep_nodes('DT $ JJ', [tree])) [[ParentedTree('DT', ['the'])]] This implementation adds syntax to select nodes based on their NLTK tree position. This syntax is ``N`` plus a Python tuple representing the tree position. For instance, ``N()``, ``N(0,)``, ``N(0,0)`` are valid node selectors. Example: >>> tree = ParentedTree.fromstring('(S (NP (DT the) (JJ big) (NN dog)) (VP bit) (NP (DT a) (NN cat)))') >>> tree[0,0] ParentedTree('DT', ['the']) >>> tree[0,0].treeposition() (0, 0) >>> list(tgrep_nodes('N(0,0)', [tree])) [[ParentedTree('DT', ['the'])]] Caveats: ======== - Link modifiers: "?" and "=" are not implemented. - Tgrep compatibility: Using "@" for "!", "{" for "<", "}" for ">" are not implemented. - The "=" and "~" links are not implemented. Known Issues: ============= - There are some issues with link relations involving leaf nodes (which are represented as bare strings in NLTK trees). For instance, consider the tree:: (S (A x)) The search string ``* !>> S`` should select all nodes which are not dominated in some way by an ``S`` node (i.e., all nodes which are not descendants of an ``S``). Clearly, in this tree, the only node which fulfills this criterion is the top node (since it is not dominated by anything). However, the code here will find both the top node and the leaf node ``x``. This is because we cannot recover the parent of the leaf, since it is stored as a bare string. A possible workaround, when performing this kind of search, would be to filter out all leaf nodes. Implementation notes ==================== This implementation is (somewhat awkwardly) based on lambda functions which are predicates on a node. A predicate is a function which is either True or False; using a predicate function, we can identify sets of nodes with particular properties. A predicate function, could, for instance, return True only if a particular node has a label matching a particular regular expression, and has a daughter node which has no sisters. Because tgrep2 search strings can do things statefully (such as substituting in macros, and binding nodes with node labels), the actual predicate function is declared with three arguments:: pred = lambda n, m, l: return True # some logic here ``n`` is a node in a tree; this argument must always be given ``m`` contains a dictionary, mapping macro names onto predicate functions ``l`` is a dictionary to map node labels onto nodes in the tree ``m`` and ``l`` are declared to default to ``None``, and so need not be specified in a call to a predicate. Predicates which call other predicates must always pass the value of these arguments on. The top-level predicate (constructed by ``_tgrep_exprs_action``) binds the macro definitions to ``m`` and initialises ``l`` to an empty dictionary. """ import functools import re try: import pyparsing except ImportError: print("Warning: nltk.tgrep will not work without the `pyparsing` package") print("installed.") import nltk.tree class TgrepException(Exception): """Tgrep exception type.""" pass def ancestors(node): """ Returns the list of all nodes dominating the given tree node. This method will not work with leaf nodes, since there is no way to recover the parent. """ results = [] try: current = node.parent() except AttributeError: # if node is a leaf, we cannot retrieve its parent return results while current: results.append(current) current = current.parent() return results def unique_ancestors(node): """ Returns the list of all nodes dominating the given node, where there is only a single path of descent. """ results = [] try: current = node.parent() except AttributeError: # if node is a leaf, we cannot retrieve its parent return results while current and len(current) == 1: results.append(current) current = current.parent() return results def _descendants(node): """ Returns the list of all nodes which are descended from the given tree node in some way. """ try: treepos = node.treepositions() except AttributeError: return [] return [node[x] for x in treepos[1:]] def _leftmost_descendants(node): """ Returns the set of all nodes descended in some way through left branches from this node. """ try: treepos = node.treepositions() except AttributeError: return [] return [node[x] for x in treepos[1:] if all(y == 0 for y in x)] def _rightmost_descendants(node): """ Returns the set of all nodes descended in some way through right branches from this node. """ try: rightmost_leaf = max(node.treepositions()) except AttributeError: return [] return [node[rightmost_leaf[:i]] for i in range(1, len(rightmost_leaf) + 1)] def _istree(obj): """Predicate to check whether `obj` is a nltk.tree.Tree.""" return isinstance(obj, nltk.tree.Tree) def _unique_descendants(node): """ Returns the list of all nodes descended from the given node, where there is only a single path of descent. """ results = [] current = node while current and _istree(current) and len(current) == 1: current = current[0] results.append(current) return results def _before(node): """ Returns the set of all nodes that are before the given node. """ try: pos = node.treeposition() tree = node.root() except AttributeError: return [] return [tree[x] for x in tree.treepositions() if x[: len(pos)] < pos[: len(x)]] def _immediately_before(node): """ Returns the set of all nodes that are immediately before the given node. Tree node A immediately precedes node B if the last terminal symbol (word) produced by A immediately precedes the first terminal symbol produced by B. """ try: pos = node.treeposition() tree = node.root() except AttributeError: return [] # go "upwards" from pos until there is a place we can go to the left idx = len(pos) - 1 while 0 <= idx and pos[idx] == 0: idx -= 1 if idx < 0: return [] pos = list(pos[: idx + 1]) pos[-1] -= 1 before = tree[pos] return [before] + _rightmost_descendants(before) def _after(node): """ Returns the set of all nodes that are after the given node. """ try: pos = node.treeposition() tree = node.root() except AttributeError: return [] return [tree[x] for x in tree.treepositions() if x[: len(pos)] > pos[: len(x)]] def _immediately_after(node): """ Returns the set of all nodes that are immediately after the given node. Tree node A immediately follows node B if the first terminal symbol (word) produced by A immediately follows the last terminal symbol produced by B. """ try: pos = node.treeposition() tree = node.root() current = node.parent() except AttributeError: return [] # go "upwards" from pos until there is a place we can go to the # right idx = len(pos) - 1 while 0 <= idx and pos[idx] == len(current) - 1: idx -= 1 current = current.parent() if idx < 0: return [] pos = list(pos[: idx + 1]) pos[-1] += 1 after = tree[pos] return [after] + _leftmost_descendants(after) def _tgrep_node_literal_value(node): """ Gets the string value of a given parse tree node, for comparison using the tgrep node literal predicates. """ return node.label() if _istree(node) else str(node) def _tgrep_macro_use_action(_s, _l, tokens): """ Builds a lambda function which looks up the macro name used. """ assert len(tokens) == 1 assert tokens[0][0] == "@" macro_name = tokens[0][1:] def macro_use(n, m=None, l=None): if m is None or macro_name not in m: raise TgrepException("macro {0} not defined".format(macro_name)) return m[macro_name](n, m, l) return macro_use def _tgrep_node_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node depending on the name of its node. """ if tokens[0] == "'": # strip initial apostrophe (tgrep2 print command) tokens = tokens[1:] if len(tokens) > 1: # disjunctive definition of a node name assert list(set(tokens[1::2])) == ["|"] # recursively call self to interpret each node name definition tokens = [_tgrep_node_action(None, None, [node]) for node in tokens[::2]] # capture tokens and return the disjunction return (lambda t: lambda n, m=None, l=None: any(f(n, m, l) for f in t))(tokens) else: if hasattr(tokens[0], "__call__"): # this is a previously interpreted parenthetical node # definition (lambda function) return tokens[0] elif tokens[0] == "*" or tokens[0] == "__": return lambda n, m=None, l=None: True elif tokens[0].startswith('"'): assert tokens[0].endswith('"') node_lit = tokens[0][1:-1].replace('\\"', '"').replace("\\\\", "\\") return ( lambda s: lambda n, m=None, l=None: _tgrep_node_literal_value(n) == s )(node_lit) elif tokens[0].startswith("/"): assert tokens[0].endswith("/") node_lit = tokens[0][1:-1] return ( lambda r: lambda n, m=None, l=None: r.search( _tgrep_node_literal_value(n) ) )(re.compile(node_lit)) elif tokens[0].startswith("i@"): node_func = _tgrep_node_action(_s, _l, [tokens[0][2:].lower()]) return ( lambda f: lambda n, m=None, l=None: f( _tgrep_node_literal_value(n).lower() ) )(node_func) else: return ( lambda s: lambda n, m=None, l=None: _tgrep_node_literal_value(n) == s )(tokens[0]) def _tgrep_parens_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from a parenthetical notation. """ assert len(tokens) == 3 assert tokens[0] == "(" assert tokens[2] == ")" return tokens[1] def _tgrep_nltk_tree_pos_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node which returns true if the node is located at a specific tree position. """ # recover the tuple from the parsed sting node_tree_position = tuple(int(x) for x in tokens if x.isdigit()) # capture the node's tree position return ( lambda i: lambda n, m=None, l=None: ( hasattr(n, "treeposition") and n.treeposition() == i ) )(node_tree_position) def _tgrep_relation_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node depending on its relation to other nodes in the tree. """ # process negation first if needed negated = False if tokens[0] == "!": negated = True tokens = tokens[1:] if tokens[0] == "[": # process square-bracketed relation expressions assert len(tokens) == 3 assert tokens[2] == "]" retval = tokens[1] else: # process operator-node relation expressions assert len(tokens) == 2 operator, predicate = tokens # A < B A is the parent of (immediately dominates) B. if operator == "<": retval = lambda n, m=None, l=None: ( _istree(n) and any(predicate(x, m, l) for x in n) ) # A > B A is the child of B. elif operator == ">": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and predicate(n.parent(), m, l) ) # A <, B Synonymous with A <1 B. elif operator == "<," or operator == "<1": retval = lambda n, m=None, l=None: ( _istree(n) and bool(list(n)) and predicate(n[0], m, l) ) # A >, B Synonymous with A >1 B. elif operator == ">," or operator == ">1": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and (n is n.parent()[0]) and predicate(n.parent(), m, l) ) # A <N B B is the Nth child of A (the first child is <1). elif operator[0] == "<" and operator[1:].isdigit(): idx = int(operator[1:]) # capture the index parameter retval = ( lambda i: lambda n, m=None, l=None: ( _istree(n) and bool(list(n)) and 0 <= i < len(n) and predicate(n[i], m, l) ) )(idx - 1) # A >N B A is the Nth child of B (the first child is >1). elif operator[0] == ">" and operator[1:].isdigit(): idx = int(operator[1:]) # capture the index parameter retval = ( lambda i: lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and 0 <= i < len(n.parent()) and (n is n.parent()[i]) and predicate(n.parent(), m, l) ) )(idx - 1) # A <' B B is the last child of A (also synonymous with A <-1 B). # A <- B B is the last child of A (synonymous with A <-1 B). elif operator == "<'" or operator == "<-" or operator == "<-1": retval = lambda n, m=None, l=None: ( _istree(n) and bool(list(n)) and predicate(n[-1], m, l) ) # A >' B A is the last child of B (also synonymous with A >-1 B). # A >- B A is the last child of B (synonymous with A >-1 B). elif operator == ">'" or operator == ">-" or operator == ">-1": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and (n is n.parent()[-1]) and predicate(n.parent(), m, l) ) # A <-N B B is the N th-to-last child of A (the last child is <-1). elif operator[:2] == "<-" and operator[2:].isdigit(): idx = -int(operator[2:]) # capture the index parameter retval = ( lambda i: lambda n, m=None, l=None: ( _istree(n) and bool(list(n)) and 0 <= (i + len(n)) < len(n) and predicate(n[i + len(n)], m, l) ) )(idx) # A >-N B A is the N th-to-last child of B (the last child is >-1). elif operator[:2] == ">-" and operator[2:].isdigit(): idx = -int(operator[2:]) # capture the index parameter retval = ( lambda i: lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and 0 <= (i + len(n.parent())) < len(n.parent()) and (n is n.parent()[i + len(n.parent())]) and predicate(n.parent(), m, l) ) )(idx) # A <: B B is the only child of A elif operator == "<:": retval = lambda n, m=None, l=None: ( _istree(n) and len(n) == 1 and predicate(n[0], m, l) ) # A >: B A is the only child of B. elif operator == ">:": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and len(n.parent()) == 1 and predicate(n.parent(), m, l) ) # A << B A dominates B (A is an ancestor of B). elif operator == "<<": retval = lambda n, m=None, l=None: ( _istree(n) and any(predicate(x, m, l) for x in _descendants(n)) ) # A >> B A is dominated by B (A is a descendant of B). elif operator == ">>": retval = lambda n, m=None, l=None: any( predicate(x, m, l) for x in ancestors(n) ) # A <<, B B is a left-most descendant of A. elif operator == "<<," or operator == "<<1": retval = lambda n, m=None, l=None: ( _istree(n) and any(predicate(x, m, l) for x in _leftmost_descendants(n)) ) # A >>, B A is a left-most descendant of B. elif operator == ">>,": retval = lambda n, m=None, l=None: any( (predicate(x, m, l) and n in _leftmost_descendants(x)) for x in ancestors(n) ) # A <<' B B is a right-most descendant of A. elif operator == "<<'": retval = lambda n, m=None, l=None: ( _istree(n) and any(predicate(x, m, l) for x in _rightmost_descendants(n)) ) # A >>' B A is a right-most descendant of B. elif operator == ">>'": retval = lambda n, m=None, l=None: any( (predicate(x, m, l) and n in _rightmost_descendants(x)) for x in ancestors(n) ) # A <<: B There is a single path of descent from A and B is on it. elif operator == "<<:": retval = lambda n, m=None, l=None: ( _istree(n) and any(predicate(x, m, l) for x in _unique_descendants(n)) ) # A >>: B There is a single path of descent from B and A is on it. elif operator == ">>:": retval = lambda n, m=None, l=None: any( predicate(x, m, l) for x in unique_ancestors(n) ) # A . B A immediately precedes B. elif operator == ".": retval = lambda n, m=None, l=None: any( predicate(x, m, l) for x in _immediately_after(n) ) # A , B A immediately follows B. elif operator == ",": retval = lambda n, m=None, l=None: any( predicate(x, m, l) for x in _immediately_before(n) ) # A .. B A precedes B. elif operator == "..": retval = lambda n, m=None, l=None: any( predicate(x, m, l) for x in _after(n) ) # A ,, B A follows B. elif operator == ",,": retval = lambda n, m=None, l=None: any( predicate(x, m, l) for x in _before(n) ) # A $ B A is a sister of B (and A != B). elif operator == "$" or operator == "%": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and bool(n.parent()) and any(predicate(x, m, l) for x in n.parent() if x is not n) ) # A $. B A is a sister of and immediately precedes B. elif operator == "$." or operator == "%.": retval = lambda n, m=None, l=None: ( hasattr(n, "right_sibling") and bool(n.right_sibling()) and predicate(n.right_sibling(), m, l) ) # A $, B A is a sister of and immediately follows B. elif operator == "$," or operator == "%,": retval = lambda n, m=None, l=None: ( hasattr(n, "left_sibling") and bool(n.left_sibling()) and predicate(n.left_sibling(), m, l) ) # A $.. B A is a sister of and precedes B. elif operator == "$.." or operator == "%..": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and hasattr(n, "parent_index") and bool(n.parent()) and any(predicate(x, m, l) for x in n.parent()[n.parent_index() + 1 :]) ) # A $,, B A is a sister of and follows B. elif operator == "$,," or operator == "%,,": retval = lambda n, m=None, l=None: ( hasattr(n, "parent") and hasattr(n, "parent_index") and bool(n.parent()) and any(predicate(x, m, l) for x in n.parent()[: n.parent_index()]) ) else: raise TgrepException( 'cannot interpret tgrep operator "{0}"'.format(operator) ) # now return the built function if negated: return (lambda r: (lambda n, m=None, l=None: not r(n, m, l)))(retval) else: return retval def _tgrep_conjunction_action(_s, _l, tokens, join_char="&"): """ Builds a lambda function representing a predicate on a tree node from the conjunction of several other such lambda functions. This is prototypically called for expressions like (`tgrep_rel_conjunction`):: < NP & < AP < VP where tokens is a list of predicates representing the relations (`< NP`, `< AP`, and `< VP`), possibly with the character `&` included (as in the example here). This is also called for expressions like (`tgrep_node_expr2`):: NP < NN S=s < /NP/=n : s < /VP/=v : n .. v tokens[0] is a tgrep_expr predicate; tokens[1:] are an (optional) list of segmented patterns (`tgrep_expr_labeled`, processed by `_tgrep_segmented_pattern_action`). """ # filter out the ampersand tokens = [x for x in tokens if x != join_char] if len(tokens) == 1: return tokens[0] else: return ( lambda ts: lambda n, m=None, l=None: all( predicate(n, m, l) for predicate in ts ) )(tokens) def _tgrep_segmented_pattern_action(_s, _l, tokens): """ Builds a lambda function representing a segmented pattern. Called for expressions like (`tgrep_expr_labeled`):: =s .. =v < =n This is a segmented pattern, a tgrep2 expression which begins with a node label. The problem is that for segemented_pattern_action (': =v < =s'), the first element (in this case, =v) is specifically selected by virtue of matching a particular node in the tree; to retrieve the node, we need the label, not a lambda function. For node labels inside a tgrep_node_expr, we need a lambda function which returns true if the node visited is the same as =v. We solve this by creating two copies of a node_label_use in the grammar; the label use inside a tgrep_expr_labeled has a separate parse action to the pred use inside a node_expr. See `_tgrep_node_label_use_action` and `_tgrep_node_label_pred_use_action`. """ # tokens[0] is a string containing the node label node_label = tokens[0] # tokens[1:] is an (optional) list of predicates which must all # hold of the bound node reln_preds = tokens[1:] def pattern_segment_pred(n, m=None, l=None): """This predicate function ignores its node argument.""" # look up the bound node using its label if l is None or node_label not in l: raise TgrepException( "node_label ={0} not bound in pattern".format(node_label) ) node = l[node_label] # match the relation predicates against the node return all(pred(node, m, l) for pred in reln_preds) return pattern_segment_pred def _tgrep_node_label_use_action(_s, _l, tokens): """ Returns the node label used to begin a tgrep_expr_labeled. See `_tgrep_segmented_pattern_action`. Called for expressions like (`tgrep_node_label_use`):: =s when they appear as the first element of a `tgrep_expr_labeled` expression (see `_tgrep_segmented_pattern_action`). It returns the node label. """ assert len(tokens) == 1 assert tokens[0].startswith("=") return tokens[0][1:] def _tgrep_node_label_pred_use_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node which describes the use of a previously bound node label. Called for expressions like (`tgrep_node_label_use_pred`):: =s when they appear inside a tgrep_node_expr (for example, inside a relation). The predicate returns true if and only if its node argument is identical the the node looked up in the node label dictionary using the node's label. """ assert len(tokens) == 1 assert tokens[0].startswith("=") node_label = tokens[0][1:] def node_label_use_pred(n, m=None, l=None): # look up the bound node using its label if l is None or node_label not in l: raise TgrepException( "node_label ={0} not bound in pattern".format(node_label) ) node = l[node_label] # truth means the given node is this node return n is node return node_label_use_pred def _tgrep_bind_node_label_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node which can optionally bind a matching node into the tgrep2 string's label_dict. Called for expressions like (`tgrep_node_expr2`):: /NP/ @NP=n """ # tokens[0] is a tgrep_node_expr if len(tokens) == 1: return tokens[0] else: # if present, tokens[1] is the character '=', and tokens[2] is # a tgrep_node_label, a string value containing the node label assert len(tokens) == 3 assert tokens[1] == "=" node_pred = tokens[0] node_label = tokens[2] def node_label_bind_pred(n, m=None, l=None): if node_pred(n, m, l): # bind `n` into the dictionary `l` if l is None: raise TgrepException( "cannot bind node_label {0}: label_dict is None".format( node_label ) ) l[node_label] = n return True else: return False return node_label_bind_pred def _tgrep_rel_disjunction_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from the disjunction of several other such lambda functions. """ # filter out the pipe tokens = [x for x in tokens if x != "|"] if len(tokens) == 1: return tokens[0] elif len(tokens) == 2: return (lambda a, b: lambda n, m=None, l=None: a(n, m, l) or b(n, m, l))( tokens[0], tokens[1] ) def _macro_defn_action(_s, _l, tokens): """ Builds a dictionary structure which defines the given macro. """ assert len(tokens) == 3 assert tokens[0] == "@" return {tokens[1]: tokens[2]} def _tgrep_exprs_action(_s, _l, tokens): """ This is the top-lebel node in a tgrep2 search string; the predicate function it returns binds together all the state of a tgrep2 search string. Builds a lambda function representing a predicate on a tree node from the disjunction of several tgrep expressions. Also handles macro definitions and macro name binding, and node label definitions and node label binding. """ if len(tokens) == 1: return lambda n, m=None, l=None: tokens[0](n, None, {}) # filter out all the semicolons tokens = [x for x in tokens if x != ";"] # collect all macro definitions macro_dict = {} macro_defs = [tok for tok in tokens if isinstance(tok, dict)] for macro_def in macro_defs: macro_dict.update(macro_def) # collect all tgrep expressions tgrep_exprs = [tok for tok in tokens if not isinstance(tok, dict)] # create a new scope for the node label dictionary def top_level_pred(n, m=macro_dict, l=None): label_dict = {} # bind macro definitions and OR together all tgrep_exprs return any(predicate(n, m, label_dict) for predicate in tgrep_exprs) return top_level_pred def _build_tgrep_parser(set_parse_actions=True): """ Builds a pyparsing-based parser object for tokenizing and interpreting tgrep search strings. """ tgrep_op = pyparsing.Optional("!") + pyparsing.Regex("[$%,.<>][%,.<>0-9-':]*") tgrep_qstring = pyparsing.QuotedString( quoteChar='"', escChar="\\", unquoteResults=False ) tgrep_node_regex = pyparsing.QuotedString( quoteChar="/", escChar="\\", unquoteResults=False ) tgrep_qstring_icase = pyparsing.Regex('i@\\"(?:[^"\\n\\r\\\\]|(?:\\\\.))*\\"') tgrep_node_regex_icase = pyparsing.Regex("i@\\/(?:[^/\\n\\r\\\\]|(?:\\\\.))*\\/") tgrep_node_literal = pyparsing.Regex("[^][ \r\t\n;:.,&|<>()$!@%'^=]+") tgrep_expr = pyparsing.Forward() tgrep_relations = pyparsing.Forward() tgrep_parens = pyparsing.Literal("(") + tgrep_expr + ")" tgrep_nltk_tree_pos = ( pyparsing.Literal("N(") + pyparsing.Optional( pyparsing.Word(pyparsing.nums) + "," + pyparsing.Optional( pyparsing.delimitedList(pyparsing.Word(pyparsing.nums), delim=",") + pyparsing.Optional(",") ) ) + ")" ) tgrep_node_label = pyparsing.Regex("[A-Za-z0-9]+") tgrep_node_label_use = pyparsing.Combine("=" + tgrep_node_label) # see _tgrep_segmented_pattern_action tgrep_node_label_use_pred = tgrep_node_label_use.copy() macro_name = pyparsing.Regex("[^];:.,&|<>()[$!@%'^=\r\t\n ]+") macro_name.setWhitespaceChars("") macro_use = pyparsing.Combine("@" + macro_name) tgrep_node_expr = ( tgrep_node_label_use_pred | macro_use | tgrep_nltk_tree_pos | tgrep_qstring_icase | tgrep_node_regex_icase | tgrep_qstring | tgrep_node_regex | "*" | tgrep_node_literal ) tgrep_node_expr2 = ( tgrep_node_expr + pyparsing.Literal("=").setWhitespaceChars("") + tgrep_node_label.copy().setWhitespaceChars("") ) | tgrep_node_expr tgrep_node = tgrep_parens | ( pyparsing.Optional("'") + tgrep_node_expr2 + pyparsing.ZeroOrMore("|" + tgrep_node_expr) ) tgrep_brackets = pyparsing.Optional("!") + "[" + tgrep_relations + "]" tgrep_relation = tgrep_brackets | (tgrep_op + tgrep_node) tgrep_rel_conjunction = pyparsing.Forward() tgrep_rel_conjunction << ( tgrep_relation + pyparsing.ZeroOrMore(pyparsing.Optional("&") + tgrep_rel_conjunction) ) tgrep_relations << tgrep_rel_conjunction + pyparsing.ZeroOrMore( "|" + tgrep_relations ) tgrep_expr << tgrep_node + pyparsing.Optional(tgrep_relations) tgrep_expr_labeled = tgrep_node_label_use + pyparsing.Optional(tgrep_relations) tgrep_expr2 = tgrep_expr + pyparsing.ZeroOrMore(":" + tgrep_expr_labeled) macro_defn = ( pyparsing.Literal("@") + pyparsing.White().suppress() + macro_name + tgrep_expr2 ) tgrep_exprs = ( pyparsing.Optional(macro_defn + pyparsing.ZeroOrMore(";" + macro_defn) + ";") + tgrep_expr2 + pyparsing.ZeroOrMore(";" + (macro_defn | tgrep_expr2)) + pyparsing.ZeroOrMore(";").suppress() ) if set_parse_actions: tgrep_node_label_use.setParseAction(_tgrep_node_label_use_action) tgrep_node_label_use_pred.setParseAction(_tgrep_node_label_pred_use_action) macro_use.setParseAction(_tgrep_macro_use_action) tgrep_node.setParseAction(_tgrep_node_action) tgrep_node_expr2.setParseAction(_tgrep_bind_node_label_action) tgrep_parens.setParseAction(_tgrep_parens_action) tgrep_nltk_tree_pos.setParseAction(_tgrep_nltk_tree_pos_action) tgrep_relation.setParseAction(_tgrep_relation_action) tgrep_rel_conjunction.setParseAction(_tgrep_conjunction_action) tgrep_relations.setParseAction(_tgrep_rel_disjunction_action) macro_defn.setParseAction(_macro_defn_action) # the whole expression is also the conjunction of two # predicates: the first node predicate, and the remaining # relation predicates tgrep_expr.setParseAction(_tgrep_conjunction_action) tgrep_expr_labeled.setParseAction(_tgrep_segmented_pattern_action) tgrep_expr2.setParseAction( functools.partial(_tgrep_conjunction_action, join_char=":") ) tgrep_exprs.setParseAction(_tgrep_exprs_action) return tgrep_exprs.ignore("#" + pyparsing.restOfLine) def tgrep_tokenize(tgrep_string): """ Tokenizes a TGrep search string into separate tokens. """ parser = _build_tgrep_parser(False) if isinstance(tgrep_string, bytes): tgrep_string = tgrep_string.decode() return list(parser.parseString(tgrep_string)) def tgrep_compile(tgrep_string): """ Parses (and tokenizes, if necessary) a TGrep search string into a lambda function. """ parser = _build_tgrep_parser(True) if isinstance(tgrep_string, bytes): tgrep_string = tgrep_string.decode() return list(parser.parseString(tgrep_string, parseAll=True))[0] def treepositions_no_leaves(tree): """ Returns all the tree positions in the given tree which are not leaf nodes. """ treepositions = tree.treepositions() # leaves are treeposition tuples that are not prefixes of any # other treeposition prefixes = set() for pos in treepositions: for length in range(len(pos)): prefixes.add(pos[:length]) return [pos for pos in treepositions if pos in prefixes] def tgrep_positions(pattern, trees, search_leaves=True): """ Return the tree positions in the trees which match the given pattern. :param pattern: a tgrep search pattern :type pattern: str or output of tgrep_compile() :param trees: a sequence of NLTK trees (usually ParentedTrees) :type trees: iter(ParentedTree) or iter(Tree) :param search_leaves: whether ot return matching leaf nodes :type search_leaves: bool :rtype: iter(tree positions) """ if isinstance(pattern, (bytes, str)): pattern = tgrep_compile(pattern) for tree in trees: try: if search_leaves: positions = tree.treepositions() else: positions = treepositions_no_leaves(tree) yield [position for position in positions if pattern(tree[position])] except AttributeError: yield [] def tgrep_nodes(pattern, trees, search_leaves=True): """ Return the tree nodes in the trees which match the given pattern. :param pattern: a tgrep search pattern :type pattern: str or output of tgrep_compile() :param trees: a sequence of NLTK trees (usually ParentedTrees) :type trees: iter(ParentedTree) or iter(Tree) :param search_leaves: whether ot return matching leaf nodes :type search_leaves: bool :rtype: iter(tree nodes) """ if isinstance(pattern, (bytes, str)): pattern = tgrep_compile(pattern) for tree in trees: try: if search_leaves: positions = tree.treepositions() else: positions = treepositions_no_leaves(tree) yield [tree[position] for position in positions if pattern(tree[position])] except AttributeError: yield []
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.conch.ssh.keys}. """ from __future__ import absolute_import, division from twisted.python.reflect import requireModule cryptography = requireModule("cryptography") if cryptography is None: skipCryptography = 'Cannot run without cryptography.' pyasn1 = requireModule("pyasn1") if requireModule("Crypto"): import Crypto.Cipher.DES3 import Crypto.PublicKey.RSA import Crypto.PublicKey.DSA else: # we'll have to skip some tests without PyCrypto Crypto = None skipPyCrypto = 'Cannot run without PyCrypto.' if cryptography and pyasn1: from twisted.conch.ssh import keys, common, sexpy import base64 import os from twisted.conch.test import keydata from twisted.python import randbytes from twisted.trial import unittest from twisted.python.compat import long, _PY3 from incremental import Version from twisted.python.filepath import FilePath class ObjectTypeTests(unittest.TestCase): """ Unit tests for the objectType method. """ if cryptography is None: skip = skipCryptography if Crypto is None: skip = skipPyCrypto if pyasn1 is None: skip = "Cannot run without PyASN1" if _PY3: skip = "objectType is deprecated and is not being ported to Python 3." def getRSAKey(self): """ Return a PyCrypto RSA key to support the tests. @return: The RSA key to support the tests. @rtype: C{Crypto.PublicKey.RSA} """ # Use lazy import as PyCrypto will be deprecated. from Crypto.PublicKey import RSA return RSA.construct(( keydata.RSAData['n'], keydata.RSAData['e'], keydata.RSAData['d'], )) def getDSAKey(self): """ Return a PyCrypto DSA key to support the tests. @return: The DSA key to support the tests. @rtype: C{Crypto.PublicKey.DSA} """ # Use lazy import as PyCrypto will be deprecated. from Crypto.PublicKey import DSA return DSA.construct(( keydata.DSAData['y'], keydata.DSAData['g'], keydata.DSAData['p'], keydata.DSAData['q'], keydata.DSAData['x'], )) def checkDeprecation(self): """ Check that we have a deprecation warning for C{objectType}. """ warnings = self.flushWarnings() self.assertEqual(1, len(warnings)) self.assertIs(DeprecationWarning, warnings[0]['category']) self.assertEqual( 'twisted.conch.ssh.keys.objectType was deprecated in ' 'Twisted 15.5.0', warnings[0]['message']) def test_objectType_rsa(self): """ C{ssh-rsa} is the type of the RSA keys. """ key = self.getRSAKey() self.assertEqual(keys.objectType(key), b'ssh-rsa') self.checkDeprecation() def test_objectType_dsa(self): """ C{ssh-dss} is the type of the DSA keys. """ key = self.getDSAKey() self.assertEqual(keys.objectType(key), b'ssh-dss') self.checkDeprecation() def test_objectKey_none(self): """ A BadKeyError is raised when getting the type of L{None}. """ self.assertRaises(keys.BadKeyError, keys.objectType, None) self.checkDeprecation() def test_deprecation(self): """ It is deprecated. """ key = self.getRSAKey() keys.objectType(key) self.checkDeprecation() class KeyTests(unittest.TestCase): if cryptography is None: skip = skipCryptography if pyasn1 is None: skip = "Cannot run without PyASN1" def setUp(self): self.rsaObj = keys.Key._fromRSAComponents( n=keydata.RSAData['n'], e=keydata.RSAData['e'], d=keydata.RSAData['d'], p=keydata.RSAData['p'], q=keydata.RSAData['q'], u=keydata.RSAData['u'], )._keyObject self.dsaObj = keys.Key._fromDSAComponents( y=keydata.DSAData['y'], p=keydata.DSAData['p'], q=keydata.DSAData['q'], g=keydata.DSAData['g'], x=keydata.DSAData['x'], )._keyObject self.ecObj = keys.Key._fromECComponents( x=keydata.ECDatanistp256['x'], y=keydata.ECDatanistp256['y'], privateValue=keydata.ECDatanistp256['privateValue'], curve=keydata.ECDatanistp256['curve'] )._keyObject self.ecObj384 = keys.Key._fromECComponents( x=keydata.ECDatanistp384['x'], y=keydata.ECDatanistp384['y'], privateValue=keydata.ECDatanistp384['privateValue'], curve=keydata.ECDatanistp384['curve'] )._keyObject self.ecObj521 = keys.Key._fromECComponents( x=keydata.ECDatanistp521['x'], y=keydata.ECDatanistp521['y'], privateValue=keydata.ECDatanistp521['privateValue'], curve=keydata.ECDatanistp521['curve'] )._keyObject self.rsaSignature = (b'\x00\x00\x00\x07ssh-rsa\x00' b'\x00\x00`N\xac\xb4@qK\xa0(\xc3\xf2h \xd3\xdd\xee6Np\x9d_' b'\xb0>\xe3\x0c(L\x9d{\txUd|!\xf6m\x9c\xd3\x93\x842\x7fU' b'\x05\xf4\xf7\xfaD\xda\xce\x81\x8ea\x7f=Y\xed*\xb7\xba\x81' b'\xf2\xad\xda\xeb(\x97\x03S\x08\x81\xc7\xb1\xb7\xe6\xe3' b'\xcd*\xd4\xbd\xc0wt\xf7y\xcd\xf0\xb7\x7f\xfb\x1e>\xf9r' b'\x8c\xba') self.dsaSignature = ( b'\x00\x00\x00\x07ssh-dss\x00\x00\x00(?\xc7\xeb\x86;\xd5TFA\xb4' b'\xdf\x0c\xc4E@4,d\xbc\t\xd9\xae\xdd[\xed-\x82nQ\x8cf\x9b\xe8\xe1' b'jrg\x84p<' ) self.patch(randbytes, 'secureRandom', lambda x: b'\xff' * x) self.keyFile = self.mktemp() with open(self.keyFile, 'wb') as f: f.write(keydata.privateRSA_lsh) def tearDown(self): os.unlink(self.keyFile) def test_size(self): """ The L{keys.Key.size} method returns the size of key object in bits. """ self.assertEqual(keys.Key(self.rsaObj).size(), 768) self.assertEqual(keys.Key(self.dsaObj).size(), 1024) self.assertEqual(keys.Key(self.ecObj).size(), 256) self.assertEqual(keys.Key(self.ecObj384).size(), 384) self.assertEqual(keys.Key(self.ecObj521).size(), 521) def test__guessStringType(self): """ Test that the _guessStringType method guesses string types correctly. """ self.assertEqual(keys.Key._guessStringType(keydata.publicRSA_openssh), 'public_openssh') self.assertEqual(keys.Key._guessStringType(keydata.publicDSA_openssh), 'public_openssh') self.assertEqual(keys.Key._guessStringType(keydata.publicECDSA_openssh), 'public_openssh') self.assertEqual(keys.Key._guessStringType( keydata.privateRSA_openssh), 'private_openssh') self.assertEqual(keys.Key._guessStringType( keydata.privateDSA_openssh), 'private_openssh') self.assertEqual(keys.Key._guessStringType( keydata.privateECDSA_openssh), 'private_openssh') self.assertEqual(keys.Key._guessStringType(keydata.publicRSA_lsh), 'public_lsh') self.assertEqual(keys.Key._guessStringType(keydata.publicDSA_lsh), 'public_lsh') self.assertEqual(keys.Key._guessStringType(keydata.privateRSA_lsh), 'private_lsh') self.assertEqual(keys.Key._guessStringType(keydata.privateDSA_lsh), 'private_lsh') self.assertEqual(keys.Key._guessStringType( keydata.privateRSA_agentv3), 'agentv3') self.assertEqual(keys.Key._guessStringType( keydata.privateDSA_agentv3), 'agentv3') self.assertEqual(keys.Key._guessStringType( b'\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01\x01'), 'blob') self.assertEqual(keys.Key._guessStringType( b'\x00\x00\x00\x07ssh-dss\x00\x00\x00\x01\x01'), 'blob') self.assertEqual(keys.Key._guessStringType(b'not a key'), None) def test_isPublic(self): """ The L{keys.Key.isPublic} method returns True for public keys otherwise False. """ rsaKey = keys.Key.fromString(keydata.privateRSA_openssh) dsaKey = keys.Key.fromString(keydata.privateDSA_openssh) ecdsaKey = keys.Key.fromString(keydata.privateECDSA_openssh) self.assertTrue(rsaKey.public().isPublic()) self.assertFalse(rsaKey.isPublic()) self.assertTrue(dsaKey.public().isPublic()) self.assertFalse(dsaKey.isPublic()) self.assertTrue(ecdsaKey.public().isPublic()) self.assertFalse(ecdsaKey.isPublic()) def _testPublicPrivateFromString(self, public, private, type, data): self._testPublicFromString(public, type, data) self._testPrivateFromString(private, type, data) def _testPublicFromString(self, public, type, data): publicKey = keys.Key.fromString(public) self.assertTrue(publicKey.isPublic()) self.assertEqual(publicKey.type(), type) for k, v in publicKey.data().items(): self.assertEqual(data[k], v) def _testPrivateFromString(self, private, type, data): privateKey = keys.Key.fromString(private) self.assertFalse(privateKey.isPublic()) self.assertEqual(privateKey.type(), type) for k, v in data.items(): self.assertEqual(privateKey.data()[k], v) def test_fromOpenSSH(self): """ Test that keys are correctly generated from OpenSSH strings. """ self._testPublicPrivateFromString(keydata.publicECDSA_openssh, keydata.privateECDSA_openssh, 'EC', keydata.ECDatanistp256) self._testPublicPrivateFromString(keydata.publicRSA_openssh, keydata.privateRSA_openssh, 'RSA', keydata.RSAData) self.assertEqual(keys.Key.fromString( keydata.privateRSA_openssh_encrypted, passphrase=b'encrypted'), keys.Key.fromString(keydata.privateRSA_openssh)) self.assertEqual(keys.Key.fromString( keydata.privateRSA_openssh_alternate), keys.Key.fromString(keydata.privateRSA_openssh)) self._testPublicPrivateFromString(keydata.publicDSA_openssh, keydata.privateDSA_openssh, 'DSA', keydata.DSAData) def test_fromOpenSSHErrors(self): """ Tests for invalid key types. """ badKey = b"""-----BEGIN FOO PRIVATE KEY----- MIGkAgEBBDAtAi7I8j73WCX20qUM5hhHwHuFzYWYYILs2Sh8UZ+awNkARZ/Fu2LU LLl5RtOQpbWgBwYFK4EEACKhZANiAATU17sA9P5FRwSknKcFsjjsk0+E3CeXPYX0 Tk/M0HK3PpWQWgrO8JdRHP9eFE9O/23P8BumwFt7F/AvPlCzVd35VfraFT0o4cCW G0RqpQ+np31aKmeJshkcYALEchnU+tQ= -----END EC PRIVATE KEY-----""" self.assertRaises(keys.BadKeyError, keys.Key._fromString_PRIVATE_OPENSSH, badKey, None) def test_fromOpenSSH_with_whitespace(self): """ If key strings have trailing whitespace, it should be ignored. """ # from bug #3391, since our test key data doesn't have # an issue with appended newlines privateDSAData = b"""-----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQDylESNuc61jq2yatCzZbenlr9llG+p9LhIpOLUbXhhHcwC6hrh EZIdCKqTO0USLrGoP5uS9UHAUoeN62Z0KXXWTwOWGEQn/syyPzNJtnBorHpNUT9D Qzwl1yUa53NNgEctpo4NoEFOx8PuU6iFLyvgHCjNn2MsuGuzkZm7sI9ZpQIVAJiR 9dPc08KLdpJyRxz8T74b4FQRAoGAGBc4Z5Y6R/HZi7AYM/iNOM8su6hrk8ypkBwR a3Dbhzk97fuV3SF1SDrcQu4zF7c4CtH609N5nfZs2SUjLLGPWln83Ysb8qhh55Em AcHXuROrHS/sDsnqu8FQp86MaudrqMExCOYyVPE7jaBWW+/JWFbKCxmgOCSdViUJ esJpBFsCgYEA7+jtVvSt9yrwsS/YU1QGP5wRAiDYB+T5cK4HytzAqJKRdC5qS4zf C7R0eKcDHHLMYO39aPnCwXjscisnInEhYGNblTDyPyiyNxAOXuC8x7luTmwzMbNJ /ow0IqSj0VF72VJN9uSoPpFd4lLT0zN8v42RWja0M8ohWNf+YNJluPgCFE0PT4Vm SUrCyZXsNh6VXwjs3gKQ -----END DSA PRIVATE KEY-----""" self.assertEqual(keys.Key.fromString(privateDSAData), keys.Key.fromString(privateDSAData + b'\n')) def test_fromNewerOpenSSH(self): """ Newer versions of OpenSSH generate encrypted keys which have a longer IV than the older versions. These newer keys are also loaded. """ key = keys.Key.fromString(keydata.privateRSA_openssh_encrypted_aes, passphrase=b'testxp') self.assertEqual(key.type(), 'RSA') key2 = keys.Key.fromString( keydata.privateRSA_openssh_encrypted_aes + b'\n', passphrase=b'testxp') self.assertEqual(key, key2) def test_fromOpenSSH_windows_line_endings(self): """ Test that keys are correctly generated from OpenSSH strings with Windows line endings. """ privateDSAData = b"""-----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQDylESNuc61jq2yatCzZbenlr9llG+p9LhIpOLUbXhhHcwC6hrh EZIdCKqTO0USLrGoP5uS9UHAUoeN62Z0KXXWTwOWGEQn/syyPzNJtnBorHpNUT9D Qzwl1yUa53NNgEctpo4NoEFOx8PuU6iFLyvgHCjNn2MsuGuzkZm7sI9ZpQIVAJiR 9dPc08KLdpJyRxz8T74b4FQRAoGAGBc4Z5Y6R/HZi7AYM/iNOM8su6hrk8ypkBwR a3Dbhzk97fuV3SF1SDrcQu4zF7c4CtH609N5nfZs2SUjLLGPWln83Ysb8qhh55Em AcHXuROrHS/sDsnqu8FQp86MaudrqMExCOYyVPE7jaBWW+/JWFbKCxmgOCSdViUJ esJpBFsCgYEA7+jtVvSt9yrwsS/YU1QGP5wRAiDYB+T5cK4HytzAqJKRdC5qS4zf C7R0eKcDHHLMYO39aPnCwXjscisnInEhYGNblTDyPyiyNxAOXuC8x7luTmwzMbNJ /ow0IqSj0VF72VJN9uSoPpFd4lLT0zN8v42RWja0M8ohWNf+YNJluPgCFE0PT4Vm SUrCyZXsNh6VXwjs3gKQ -----END DSA PRIVATE KEY-----""" self.assertEqual( keys.Key.fromString(privateDSAData), keys.Key.fromString(privateDSAData.replace(b'\n', b'\r\n'))) def test_fromLSHPublicUnsupportedType(self): """ C{BadKeyError} exception is raised when public key has an unknown type. """ sexp = sexpy.pack([[b'public-key', [b'bad-key', [b'p', b'2']]]]) self.assertRaises( keys.BadKeyError, keys.Key.fromString, data=b'{' + base64.encodestring(sexp) + b'}', ) def test_fromLSHPrivateUnsupportedType(self): """ C{BadKeyError} exception is raised when private key has an unknown type. """ sexp = sexpy.pack([[b'private-key', [b'bad-key', [b'p', b'2']]]]) self.assertRaises( keys.BadKeyError, keys.Key.fromString, sexp, ) def test_fromLSHRSA(self): """ RSA public and private keys can be generated from a LSH strings. """ self._testPublicPrivateFromString( keydata.publicRSA_lsh, keydata.privateRSA_lsh, 'RSA', keydata.RSAData, ) def test_fromLSHDSA(self): """ DSA public and private key can be generated from LSHs. """ self._testPublicPrivateFromString( keydata.publicDSA_lsh, keydata.privateDSA_lsh, 'DSA', keydata.DSAData, ) def test_fromAgentv3(self): """ Test that keys are correctly generated from Agent v3 strings. """ self._testPrivateFromString(keydata.privateRSA_agentv3, 'RSA', keydata.RSAData) self._testPrivateFromString(keydata.privateDSA_agentv3, 'DSA', keydata.DSAData) self.assertRaises(keys.BadKeyError, keys.Key.fromString, b'\x00\x00\x00\x07ssh-foo'+ b'\x00\x00\x00\x01\x01'*5) def test_fromStringErrors(self): """ keys.Key.fromString should raise BadKeyError when the key is invalid. """ self.assertRaises(keys.BadKeyError, keys.Key.fromString, b'') # no key data with a bad key type self.assertRaises(keys.BadKeyError, keys.Key.fromString, b'', 'bad_type') # trying to decrypt a key which doesn't support encryption self.assertRaises(keys.BadKeyError, keys.Key.fromString, keydata.publicRSA_lsh, passphrase = b'unencrypted') # trying to decrypt a key with the wrong passphrase self.assertRaises(keys.EncryptedKeyError, keys.Key.fromString, keys.Key(self.rsaObj).toString('openssh', b'encrypted')) # key with no key data self.assertRaises(keys.BadKeyError, keys.Key.fromString, b'-----BEGIN RSA KEY-----\nwA==\n') # key with invalid DEK Info self.assertRaises( keys.BadKeyError, keys.Key.fromString, b"""-----BEGIN ENCRYPTED RSA KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: weird type 4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5 9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW 0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk 2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk 4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n 8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0 fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+ 0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5 xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c 8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7 CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P -----END RSA PRIVATE KEY-----""", passphrase='encrypted') # key with invalid encryption type self.assertRaises( keys.BadKeyError, keys.Key.fromString, b"""-----BEGIN ENCRYPTED RSA KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: FOO-123-BAR,01234567 4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5 9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW 0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk 2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk 4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n 8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0 fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+ 0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5 xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c 8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7 CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P -----END RSA PRIVATE KEY-----""", passphrase='encrypted') # key with bad IV (AES) self.assertRaises( keys.BadKeyError, keys.Key.fromString, b"""-----BEGIN ENCRYPTED RSA KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,01234 4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5 9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW 0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk 2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk 4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n 8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0 fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+ 0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5 xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c 8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7 CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P -----END RSA PRIVATE KEY-----""", passphrase='encrypted') # key with bad IV (DES3) self.assertRaises( keys.BadKeyError, keys.Key.fromString, b"""-----BEGIN ENCRYPTED RSA KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,01234 4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5 9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW 0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk 2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk 4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n 8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0 fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+ 0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5 xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c 8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7 CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P -----END RSA PRIVATE KEY-----""", passphrase='encrypted') def test_fromFile(self): """ Test that fromFile works correctly. """ self.assertEqual(keys.Key.fromFile(self.keyFile), keys.Key.fromString(keydata.privateRSA_lsh)) self.assertRaises(keys.BadKeyError, keys.Key.fromFile, self.keyFile, 'bad_type') self.assertRaises(keys.BadKeyError, keys.Key.fromFile, self.keyFile, passphrase='unencrypted') def test_init(self): """ Test that the PublicKey object is initialized correctly. """ obj = keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject key = keys.Key(obj) self.assertEqual(key._keyObject, obj) def test_equal(self): """ Test that Key objects are compared correctly. """ rsa1 = keys.Key(self.rsaObj) rsa2 = keys.Key(self.rsaObj) rsa3 = keys.Key( keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject) dsa = keys.Key(self.dsaObj) self.assertTrue(rsa1 == rsa2) self.assertFalse(rsa1 == rsa3) self.assertFalse(rsa1 == dsa) self.assertFalse(rsa1 == object) self.assertFalse(rsa1 == None) def test_notEqual(self): """ Test that Key objects are not-compared correctly. """ rsa1 = keys.Key(self.rsaObj) rsa2 = keys.Key(self.rsaObj) rsa3 = keys.Key( keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject) dsa = keys.Key(self.dsaObj) self.assertFalse(rsa1 != rsa2) self.assertTrue(rsa1 != rsa3) self.assertTrue(rsa1 != dsa) self.assertTrue(rsa1 != object) self.assertTrue(rsa1 != None) def test_dataError(self): """ The L{keys.Key.data} method raises RuntimeError for bad keys. """ badKey = keys.Key(b'') self.assertRaises(RuntimeError, badKey.data) def test_fingerprintdefault(self): """ Test that the fingerprint method returns fingerprint in L{FingerprintFormats.MD5-HEX} format by default. """ self.assertEqual(keys.Key(self.rsaObj).fingerprint(), '3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af') self.assertEqual(keys.Key(self.dsaObj).fingerprint(), '63:15:b3:0e:e6:4f:50:de:91:48:3d:01:6b:b3:13:c1') def test_fingerprint_md5_hex(self): """ fingerprint method generates key fingerprint in L{FingerprintFormats.MD5-HEX} format if explicitly specified. """ self.assertEqual( keys.Key(self.rsaObj).fingerprint( keys.FingerprintFormats.MD5_HEX), '3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af') self.assertEqual( keys.Key(self.dsaObj).fingerprint( keys.FingerprintFormats.MD5_HEX), '63:15:b3:0e:e6:4f:50:de:91:48:3d:01:6b:b3:13:c1') def test_fingerprintsha256(self): """ fingerprint method generates key fingerprint in L{FingerprintFormats.SHA256-BASE64} format if explicitly specified. """ self.assertEqual( keys.Key(self.rsaObj).fingerprint( keys.FingerprintFormats.SHA256_BASE64), 'ryaugIFT0B8ItuszldMEU7q14rG/wj9HkRosMeBWkts=') self.assertEqual( keys.Key(self.dsaObj).fingerprint( keys.FingerprintFormats.SHA256_BASE64), 'Wz5o2YbKyxOEcJn1au/UaALSVruUzfz0vaLI1xiIGyY=') def test_fingerprintBadFormat(self): """ A C{BadFingerPrintFormat} error is raised when unsupported formats are requested. """ with self.assertRaises(keys.BadFingerPrintFormat) as em: keys.Key(self.rsaObj).fingerprint('sha256-base') self.assertEqual('Unsupported fingerprint format: sha256-base', em.exception.args[0]) def test_type(self): """ Test that the type method returns the correct type for an object. """ self.assertEqual(keys.Key(self.rsaObj).type(), 'RSA') self.assertEqual(keys.Key(self.rsaObj).sshType(), b'ssh-rsa') self.assertEqual(keys.Key(self.dsaObj).type(), 'DSA') self.assertEqual(keys.Key(self.dsaObj).sshType(), b'ssh-dss') self.assertEqual(keys.Key(self.ecObj).type(), 'EC') self.assertEqual(keys.Key(self.ecObj).sshType(), keydata.ECDatanistp256['curve']) self.assertRaises(RuntimeError, keys.Key(None).type) self.assertRaises(RuntimeError, keys.Key(None).sshType) self.assertRaises(RuntimeError, keys.Key(self).type) self.assertRaises(RuntimeError, keys.Key(self).sshType) def test_fromBlobUnsupportedType(self): """ A C{BadKeyError} error is raised whey the blob has an unsupported key type. """ badBlob = common.NS(b'ssh-bad') self.assertRaises(keys.BadKeyError, keys.Key.fromString, badBlob) def test_fromBlobRSA(self): """ A public RSA key is correctly generated from a public key blob. """ rsaPublicData = { 'n': keydata.RSAData['n'], 'e': keydata.RSAData['e'], } rsaBlob = ( common.NS(b'ssh-rsa') + common.MP(rsaPublicData['e']) + common.MP(rsaPublicData['n']) ) rsaKey = keys.Key.fromString(rsaBlob) self.assertTrue(rsaKey.isPublic()) self.assertEqual(rsaPublicData, rsaKey.data()) def test_fromBlobDSA(self): """ A public DSA key is correctly generated from a public key blob. """ dsaPublicData = { 'p': keydata.DSAData['p'], 'q': keydata.DSAData['q'], 'g': keydata.DSAData['g'], 'y': keydata.DSAData['y'], } dsaBlob = ( common.NS(b'ssh-dss') + common.MP(dsaPublicData['p']) + common.MP(dsaPublicData['q']) + common.MP(dsaPublicData['g']) + common.MP(dsaPublicData['y']) ) dsaKey = keys.Key.fromString(dsaBlob) self.assertTrue(dsaKey.isPublic()) self.assertEqual(dsaPublicData, dsaKey.data()) def test_fromBlobECDSA(self): """ Key.fromString generates ECDSA keys from blobs. """ from cryptography import utils ecPublicData = { 'x': keydata.ECDatanistp256['x'], 'y': keydata.ECDatanistp256['y'], 'curve': keydata.ECDatanistp256['curve'] } ecblob = (common.NS(ecPublicData['curve']) + common.NS(ecPublicData['curve'][-8:]) + common.NS(b'\x04' + utils.int_to_bytes(ecPublicData['x'], 32) + utils.int_to_bytes(ecPublicData['y'], 32)) ) eckey = keys.Key.fromString(ecblob) self.assertTrue(eckey.isPublic()) self.assertEqual(ecPublicData, eckey.data()) def test_fromPrivateBlobUnsupportedType(self): """ C{BadKeyError} is raised when loading a private blob with an unsupported type. """ badBlob = common.NS(b'ssh-bad') self.assertRaises( keys.BadKeyError, keys.Key._fromString_PRIVATE_BLOB, badBlob) def test_fromPrivateBlobRSA(self): """ A private RSA key is correctly generated from a private key blob. """ rsaBlob = ( common.NS(b'ssh-rsa') + common.MP(keydata.RSAData['n']) + common.MP(keydata.RSAData['e']) + common.MP(keydata.RSAData['d']) + common.MP(keydata.RSAData['u']) + common.MP(keydata.RSAData['p']) + common.MP(keydata.RSAData['q']) ) rsaKey = keys.Key._fromString_PRIVATE_BLOB(rsaBlob) self.assertFalse(rsaKey.isPublic()) self.assertEqual(keydata.RSAData, rsaKey.data()) def test_fromPrivateBlobDSA(self): """ A private DSA key is correctly generated from a private key blob. """ dsaBlob = ( common.NS(b'ssh-dss') + common.MP(keydata.DSAData['p']) + common.MP(keydata.DSAData['q']) + common.MP(keydata.DSAData['g']) + common.MP(keydata.DSAData['y']) + common.MP(keydata.DSAData['x']) ) dsaKey = keys.Key._fromString_PRIVATE_BLOB(dsaBlob) self.assertFalse(dsaKey.isPublic()) self.assertEqual(keydata.DSAData, dsaKey.data()) def test_fromPrivateBlobECDSA(self): """ A private EC key is correctly generated from a private key blob. """ ecblob = ( common.NS(keydata.ECDatanistp256['curve']) + common.MP(keydata.ECDatanistp256['x']) + common.MP(keydata.ECDatanistp256['y']) + common.MP(keydata.ECDatanistp256['privateValue']) ) eckey = keys.Key._fromString_PRIVATE_BLOB(ecblob) self.assertFalse(eckey.isPublic()) self.assertEqual(keydata.ECDatanistp256, eckey.data()) def test_blobRSA(self): """ Return the over-the-wire SSH format of the RSA public key. """ self.assertEqual( keys.Key(self.rsaObj).blob(), common.NS(b'ssh-rsa') + common.MP(self.rsaObj.private_numbers().public_numbers.e) + common.MP(self.rsaObj.private_numbers().public_numbers.n) ) def test_blobDSA(self): """ Return the over-the-wire SSH format of the DSA public key. """ publicNumbers = self.dsaObj.private_numbers().public_numbers self.assertEqual( keys.Key(self.dsaObj).blob(), common.NS(b'ssh-dss') + common.MP(publicNumbers.parameter_numbers.p) + common.MP(publicNumbers.parameter_numbers.q) + common.MP(publicNumbers.parameter_numbers.g) + common.MP(publicNumbers.y) ) def test_blobEC(self): """ Return the over-the-wire SSH format of the EC public key. """ from cryptography import utils byteLength = (self.ecObj.curve.key_size + 7) // 8 self.assertEqual( keys.Key(self.ecObj).blob(), common.NS(keydata.ECDatanistp256['curve']) + common.NS(keydata.ECDatanistp256['curve'][-8:]) + common.NS(b'\x04' + utils.int_to_bytes( self.ecObj.private_numbers().public_numbers.x, byteLength) + utils.int_to_bytes( self.ecObj.private_numbers().public_numbers.y, byteLength)) ) def test_blobNoKey(self): """ C{RuntimeError} is raised when the blob is requested for a Key which is not wrapping anything. """ badKey = keys.Key(None) self.assertRaises(RuntimeError, badKey.blob) def test_privateBlobRSA(self): """ L{keys.Key.privateBlob} returns the SSH protocol-level format of an RSA private key. """ from cryptography.hazmat.primitives.asymmetric import rsa numbers = self.rsaObj.private_numbers() u = rsa.rsa_crt_iqmp(numbers.q, numbers.p) self.assertEqual( keys.Key(self.rsaObj).privateBlob(), common.NS(b'ssh-rsa') + common.MP(self.rsaObj.private_numbers().public_numbers.n) + common.MP(self.rsaObj.private_numbers().public_numbers.e) + common.MP(self.rsaObj.private_numbers().d) + common.MP(u) + common.MP(self.rsaObj.private_numbers().p) + common.MP(self.rsaObj.private_numbers().q) ) def test_privateBlobDSA(self): """ L{keys.Key.privateBlob} returns the SSH protocol-level format of a DSA private key. """ publicNumbers = self.dsaObj.private_numbers().public_numbers self.assertEqual( keys.Key(self.dsaObj).privateBlob(), common.NS(b'ssh-dss') + common.MP(publicNumbers.parameter_numbers.p) + common.MP(publicNumbers.parameter_numbers.q) + common.MP(publicNumbers.parameter_numbers.g) + common.MP(publicNumbers.y) + common.MP(self.dsaObj.private_numbers().x) ) def test_privateBlobEC(self): """ L{keys.Key.privateBlob} returns the SSH ptotocol-level format of EC private key. """ self.assertEqual( keys.Key(self.ecObj).privateBlob(), common.NS(keydata.ECDatanistp256['curve']) + common.MP(self.ecObj.private_numbers().public_numbers.x) + common.MP(self.ecObj.private_numbers().public_numbers.y) + common.MP(self.ecObj.private_numbers().private_value) ) def test_privateBlobNoKeyObject(self): """ Raises L{RuntimeError} if the underlying key object does not exists. """ badKey = keys.Key(None) self.assertRaises(RuntimeError, badKey.privateBlob) def test_toOpenSSHRSA(self): """ L{keys.Key.toString} serializes an RSA key in OpenSSH format. """ key = keys.Key.fromString(keydata.privateRSA_agentv3) self.assertEqual(key.toString('openssh'), keydata.privateRSA_openssh) self.assertEqual(key.toString('openssh', b'encrypted'), keydata.privateRSA_openssh_encrypted) self.assertEqual(key.public().toString('openssh'), keydata.publicRSA_openssh[:-8]) # no comment self.assertEqual(key.public().toString('openssh', b'comment'), keydata.publicRSA_openssh) def test_toOpenSSHDSA(self): """ L{keys.Key.toString} serializes a DSA key in OpenSSH format. """ key = keys.Key.fromString(keydata.privateDSA_lsh) self.assertEqual(key.toString('openssh'), keydata.privateDSA_openssh) self.assertEqual(key.public().toString('openssh', b'comment'), keydata.publicDSA_openssh) self.assertEqual(key.public().toString('openssh'), keydata.publicDSA_openssh[:-8]) # no comment def test_toOpenSSHECDSA(self): """ L{keys.Key.toString} serializes a ECDSA key in OpenSSH format. """ key = keys.Key.fromString(keydata.privateECDSA_openssh) self.assertEqual(key.public().toString('openssh', b'comment'), keydata.publicECDSA_openssh) self.assertEqual(key.public().toString('openssh'), keydata.publicECDSA_openssh[:-8]) # no comment def test_toLSHRSA(self): """ L{keys.Key.toString} serializes an RSA key in LSH format. """ key = keys.Key.fromString(keydata.privateRSA_openssh) self.assertEqual(key.toString('lsh'), keydata.privateRSA_lsh) self.assertEqual(key.public().toString('lsh'), keydata.publicRSA_lsh) def test_toLSHDSA(self): """ L{keys.Key.toString} serializes a DSA key in LSH format. """ key = keys.Key.fromString(keydata.privateDSA_openssh) self.assertEqual(key.toString('lsh'), keydata.privateDSA_lsh) self.assertEqual(key.public().toString('lsh'), keydata.publicDSA_lsh) def test_toAgentv3RSA(self): """ L{keys.Key.toString} serializes an RSA key in Agent v3 format. """ key = keys.Key.fromString(keydata.privateRSA_openssh) self.assertEqual(key.toString('agentv3'), keydata.privateRSA_agentv3) def test_toAgentv3DSA(self): """ L{keys.Key.toString} serializes a DSA key in Agent v3 format. """ key = keys.Key.fromString(keydata.privateDSA_openssh) self.assertEqual(key.toString('agentv3'), keydata.privateDSA_agentv3) def test_toStringErrors(self): """ L{keys.Key.toString} raises L{keys.BadKeyError} when passed an invalid format type. """ self.assertRaises(keys.BadKeyError, keys.Key(self.rsaObj).toString, 'bad_type') def test_signAndVerifyRSA(self): """ Signed data can be verified using RSA. """ data = b'some-data' key = keys.Key.fromString(keydata.privateRSA_openssh) signature = key.sign(data) self.assertTrue(key.public().verify(signature, data)) self.assertTrue(key.verify(signature, data)) def test_signAndVerifyDSA(self): """ Signed data can be verified using DSA. """ data = b'some-data' key = keys.Key.fromString(keydata.privateDSA_openssh) signature = key.sign(data) self.assertTrue(key.public().verify(signature, data)) self.assertTrue(key.verify(signature, data)) def test_signAndVerifyEC(self): """ Signed data can be verified using EC. """ data = b'some-data' key = keys.Key.fromString(keydata.privateECDSA_openssh) signature = key.sign(data) key384 = keys.Key.fromString(keydata.privateECDSA_openssh384) signature384 = key384.sign(data) key521 = keys.Key.fromString(keydata.privateECDSA_openssh521) signature521 = key521.sign(data) self.assertTrue(key.public().verify(signature, data)) self.assertTrue(key.verify(signature, data)) self.assertTrue(key384.public().verify(signature384, data)) self.assertTrue(key384.verify(signature384, data)) self.assertTrue(key521.public().verify(signature521, data)) self.assertTrue(key521.verify(signature521, data)) def test_verifyRSA(self): """ A known-good RSA signature verifies successfully. """ key = keys.Key.fromString(keydata.publicRSA_openssh) self.assertTrue(key.verify(self.rsaSignature, b'')) self.assertFalse(key.verify(self.rsaSignature, b'a')) self.assertFalse(key.verify(self.dsaSignature, b'')) def test_verifyDSA(self): """ A known-good DSA signature verifies successfully. """ key = keys.Key.fromString(keydata.publicDSA_openssh) self.assertTrue(key.verify(self.dsaSignature, b'')) self.assertFalse(key.verify(self.dsaSignature, b'a')) self.assertFalse(key.verify(self.rsaSignature, b'')) def test_verifyDSANoPrefix(self): """ Some commercial SSH servers send DSA keys as 2 20-byte numbers; they are still verified as valid keys. """ key = keys.Key.fromString(keydata.publicDSA_openssh) self.assertTrue(key.verify(self.dsaSignature[-40:], b'')) def test_reprPrivateRSA(self): """ The repr of a L{keys.Key} contains all of the RSA components for an RSA private key. """ self.assertEqual(repr(keys.Key(self.rsaObj)), """<RSA Private Key (768 bits) attr d: \t6e:1f:b5:55:97:eb:ed:67:ed:2b:99:6e:ec:c1:ed: \ta8:4d:52:d6:f3:d6:65:06:04:df:e5:54:9f:cc:89: \t00:3c:9b:67:87:ec:65:a0:ab:cd:6f:65:90:8a:97: \t90:4d:c6:21:8f:a8:8d:d8:59:86:43:b5:81:b1:b4: \td7:5f:2c:22:0a:61:c1:25:8a:47:12:b4:9a:f8:7a: \t11:1c:4a:a8:8b:75:c4:91:09:3b:be:04:ca:45:d9: \t57:8a:0d:27:cb:23 attr e: \t23 attr n: \t00:af:32:71:f0:e6:0e:9c:99:b3:7f:8b:5f:04:4b: \tcb:8b:c0:d5:3e:b2:77:fd:cf:64:d8:8f:c0:cf:ae: \t1f:c6:31:df:f6:29:b2:44:96:e2:c6:d4:21:94:7f: \t65:7c:d8:d4:23:1f:b8:2e:6a:c9:1f:94:0d:46:c1: \t69:a2:b7:07:0c:a3:93:c1:34:d8:2e:1e:4a:99:1a: \t6c:96:46:07:46:2b:dc:25:29:1b:87:f0:be:05:1d: \tee:b4:34:b9:e7:99:95 attr p: \t00:cb:4a:4b:d0:40:47:e8:45:52:f7:c7:af:0c:20: \t6d:43:0d:b6:39:94:f9:da:a5:e5:03:06:76:83:24: \teb:88:a1:55:a2:a8:de:12:3b:77:49:92:8a:a9:71: \td2:02:93:ff attr q: \t00:dc:9f:6b:d9:98:21:56:11:8d:e9:5f:03:9d:0a: \td3:93:6e:13:77:41:3c:85:4f:00:70:fd:05:54:ff: \tbc:3d:09:bf:83:f6:97:7f:64:10:91:04:fe:a2:67: \t47:54:42:6b attr u: \t00:b4:73:97:4b:50:10:a3:17:b3:a8:47:f1:3a:14: \t76:52:d1:38:2a:cf:12:14:34:c1:a8:54:4c:29:35: \t80:a0:38:b8:f0:fa:4c:c4:c2:85:ab:db:87:82:ba: \tdc:eb:db:2a>""") def test_reprPublicRSA(self): """ The repr of a L{keys.Key} contains all of the RSA components for an RSA public key. """ self.assertEqual(repr(keys.Key(self.rsaObj).public()), """<RSA Public Key (768 bits) attr e: \t23 attr n: \t00:af:32:71:f0:e6:0e:9c:99:b3:7f:8b:5f:04:4b: \tcb:8b:c0:d5:3e:b2:77:fd:cf:64:d8:8f:c0:cf:ae: \t1f:c6:31:df:f6:29:b2:44:96:e2:c6:d4:21:94:7f: \t65:7c:d8:d4:23:1f:b8:2e:6a:c9:1f:94:0d:46:c1: \t69:a2:b7:07:0c:a3:93:c1:34:d8:2e:1e:4a:99:1a: \t6c:96:46:07:46:2b:dc:25:29:1b:87:f0:be:05:1d: \tee:b4:34:b9:e7:99:95>""") def test_reprPublicECDSA(self): """ The repr of a L{keys.Key} contains all the OpenSSH format for an ECDSA public key. """ self.assertEqual(repr(keys.Key(self.ecObj).public()), """<Elliptic Curve Public Key (256 bits) curve: \tecdsa-sha2-nistp256 x: \t76282513020392096317118503144964731774299773481750550543382904345687059013883 y:""" + "\n\t8154319786460285263226566476944164753434437589431431968106113715931064" + "6683104>\n") def test_reprPrivateECDSA(self): """ The repr of a L{keys.Key} contains all the OpenSSH format for an ECDSA private key. """ self.assertEqual(repr(keys.Key(self.ecObj)), """<Elliptic Curve Private Key (256 bits) curve: \tecdsa-sha2-nistp256 privateValue: \t34638743477210341700964008455655698253555655678826059678074967909361042656500 x: \t76282513020392096317118503144964731774299773481750550543382904345687059013883 y:""" + "\n\t8154319786460285263226566476944164753434437589431431968106113715931064" + "6683104>\n") class KeyKeyObjectTests(unittest.TestCase): """ The L{keys.Key.keyObject} property provides deprecated access to a PyCrypto key instance of the corresponding type. """ if cryptography is None: skip = skipCryptography if Crypto is None: skip = skipPyCrypto def test_deprecation(self): """ Accessing the L{keys.Key.keyObject} property emits a deprecation warning. """ keys.Key.fromString(keydata.publicRSA_openssh).keyObject [warning] = self.flushWarnings([KeyKeyObjectTests.test_deprecation]) self.assertIs(warning['category'], DeprecationWarning) def test_keyObjectGetRSAPublic(self): """ The PyCrypto key instance for an RSA public key has the same components as the internal key. """ key = keys.Key.fromString(keydata.publicRSA_openssh) result = key.keyObject self.assertIsInstance(result, Crypto.PublicKey.RSA._RSAobj) self.assertEqual(keydata.RSAData['e'], result.key.e) self.assertEqual(keydata.RSAData['n'], result.key.n) def test_keyObjectGetRSAPrivate(self): """ The PyCrypto key instance for an RSA private key has the same components as the internal key. """ key = keys.Key.fromString(keydata.privateRSA_openssh) result = key.keyObject self.assertIsInstance(result, Crypto.PublicKey.RSA._RSAobj) self.assertEqual(keydata.RSAData['e'], result.key.e) self.assertEqual(keydata.RSAData['n'], result.key.n) self.assertEqual(keydata.RSAData['d'], result.key.d) self.assertEqual(keydata.RSAData['p'], result.key.p) self.assertEqual(keydata.RSAData['q'], result.key.q) self.assertEqual(keydata.RSAData['u'], result.key.u) def test_keyObjectGetDSAPublic(self): """ The PyCrypto key instance for a DSA public key has the same components as the internal key. """ key = keys.Key.fromString(keydata.publicDSA_openssh) result = key.keyObject self.assertIsInstance(result, Crypto.PublicKey.DSA._DSAobj) self.assertEqual(keydata.DSAData['y'], result.key.y) self.assertEqual(keydata.DSAData['g'], result.key.g) self.assertEqual(keydata.DSAData['p'], result.key.p) self.assertEqual(keydata.DSAData['q'], result.key.q) def test_keyObjectGetDSAPrivate(self): """ The PyCrypto key instance for a DSA private key has the same components as the internal key. """ key = keys.Key.fromString(keydata.privateDSA_openssh) result = key.keyObject self.assertIsInstance(result, Crypto.PublicKey.DSA._DSAobj) self.assertEqual(keydata.DSAData['y'], result.key.y) self.assertEqual(keydata.DSAData['g'], result.key.g) self.assertEqual(keydata.DSAData['p'], result.key.p) self.assertEqual(keydata.DSAData['q'], result.key.q) self.assertEqual(keydata.DSAData['x'], result.key.x) def test_keyObjectSetRSAPublic(self): """ Setting the L{keys.Key.keyObject} property to a PyCrypto public RSA key instance updates the internal key. """ key = keys.Key.fromString(keydata.publicDSA_openssh) newPyCryptoKey = Crypto.PublicKey.RSA.construct(( keydata.RSAData['n'], keydata.RSAData['e'], )) self.assertEqual('DSA', key.type()) key.keyObject = newPyCryptoKey [warning] = self.flushWarnings([ KeyKeyObjectTests.test_keyObjectSetRSAPublic]) self.assertIs(warning['category'], DeprecationWarning) self.assertEqual('RSA', key.type()) self.assertEqual({ 'n': keydata.RSAData['n'], 'e': keydata.RSAData['e'], }, key.data()) def test_keyObjectSetRSAPrivate(self): """ Setting the L{keys.Key.keyObject} property to a PyCrypto private RSA key instance updates the internal key. """ key = keys.Key.fromString(keydata.publicDSA_openssh) newPyCryptoKey = Crypto.PublicKey.RSA.construct(( keydata.RSAData['n'], keydata.RSAData['e'], keydata.RSAData['d'], keydata.RSAData['p'], keydata.RSAData['q'], keydata.RSAData['u'], )) self.assertEqual('DSA', key.type()) key.keyObject = newPyCryptoKey self.assertEqual('RSA', key.type()) self.assertEqual({ 'n': keydata.RSAData['n'], 'e': keydata.RSAData['e'], 'd': keydata.RSAData['d'], 'p': keydata.RSAData['p'], 'q': keydata.RSAData['q'], 'u': keydata.RSAData['u'], }, key.data()) def test_keyObjectSetDSAPublic(self): """ Setting the L{keys.Key.keyObject} property to a PyCrypto public DSA key instance updates the internal key. """ key = keys.Key.fromString(keydata.publicRSA_openssh) newPyCryptoKey = Crypto.PublicKey.DSA.construct(( keydata.DSAData['y'], keydata.DSAData['g'], keydata.DSAData['p'], keydata.DSAData['q'], )) self.assertEqual('RSA', key.type()) key.keyObject = newPyCryptoKey self.assertEqual('DSA', key.type()) self.assertEqual({ 'y': keydata.DSAData['y'], 'g': keydata.DSAData['g'], 'p': keydata.DSAData['p'], 'q': keydata.DSAData['q'], }, key.data()) def test_keyObjectSetDSAPrivate(self): """ Setting the L{keys.Key.keyObject} property to a PyCrypto private DSA key instance updates the internal key. """ key = keys.Key.fromString(keydata.publicRSA_openssh) newPyCryptoKey = Crypto.PublicKey.DSA.construct(( keydata.DSAData['y'], keydata.DSAData['g'], keydata.DSAData['p'], keydata.DSAData['q'], keydata.DSAData['x'], )) self.assertEqual('RSA', key.type()) key.keyObject = newPyCryptoKey self.assertEqual('DSA', key.type()) self.assertEqual({ 'y': keydata.DSAData['y'], 'g': keydata.DSAData['g'], 'p': keydata.DSAData['p'], 'q': keydata.DSAData['q'], 'x': keydata.DSAData['x'], }, key.data()) def test_constructorPyCrypto(self): """ Passing a PyCrypto key object to L{keys.Key} is deprecated. """ pycryptoKey = Crypto.PublicKey.RSA.construct(( keydata.RSAData['n'], keydata.RSAData['e'])) key = self.callDeprecated( (Version('Twisted', 16, 0, 0), 'passing a cryptography key object'), keys.Key, pycryptoKey) self.assertEqual('RSA', key.type()) self.assertEqual({ 'n': keydata.RSAData['n'], 'e': keydata.RSAData['e'], }, key.data()) class PersistentRSAKeyTests(unittest.TestCase): """ Tests for L{keys._getPersistentRSAKey}. """ if cryptography is None: skip = skipCryptography def test_providedArguments(self): """ L{keys._getPersistentRSAKey} will put the key in C{directory}/C{filename}, with the key length of C{keySize}. """ tempDir = FilePath(self.mktemp()) keyFile = tempDir.child("mykey.pem") key = keys._getPersistentRSAKey(keyFile, keySize=512) self.assertEqual(key.size(), 512) self.assertTrue(keyFile.exists()) def test_noRegeneration(self): """ L{keys._getPersistentRSAKey} will not regenerate the key if the key already exists. """ tempDir = FilePath(self.mktemp()) keyFile = tempDir.child("mykey.pem") key = keys._getPersistentRSAKey(keyFile, keySize=512) self.assertEqual(key.size(), 512) self.assertTrue(keyFile.exists()) keyContent = keyFile.getContent() # Set the key size to 1024 bits. Since it exists already, it will find # the 512 bit key, and not generate a 1024 bit key. key = keys._getPersistentRSAKey(keyFile, keySize=1024) self.assertEqual(key.size(), 512) self.assertEqual(keyFile.getContent(), keyContent) def test_keySizeZero(self): """ If the key generated by L{keys.getPersistentRSAKey} is set to None the key size should then become 0. """ tempDir = FilePath(self.mktemp()) keyFile = tempDir.child("mykey.pem") key = keys._getPersistentRSAKey(keyFile, keySize=512) key._keyObject = None self.assertEqual( key.size(), 0)
from rest_framework import serializers class LocationSerializer(serializers.Serializer): loc = serializers.CharField() lat = serializers.FloatField() lon = serializers.FloatField()
import sys numbers_counter=int(input()) counter=0 max_number= - sys.maxsize #The value sys.maxsize, on the other hand, reports the platform's pointer size, #and that limits the size of Python's data structures such as strings and lists. while counter<numbers_counter: number=int(input()) counter+=1 if number>max_number: max_number=number print(max_number)