def check_old_instance(self): demo = Demo(self.config) database = demo.database logging.debug('CHECK OLD INSTANCE') query = database\ .query(Instance)\ .filter(Instance.status != 'DELETED')\ .filter(Instance.status != 'POOL') logging.debug("%s count", query.count()) instances = demo.provider.get_instances() for data_instance in query.all(): if data_instance.get_dead_time() == -1: logging.info('%s is to old', data_instance.provider_id) demo.database_remove_server(data_instance.provider_id) on_cloud = False for id in instances: if data_instance.provider_id == id: on_cloud = True break if not on_cloud and data_instance.provider_id: logging.info( '%s is not present on cloud anymore', data_instance.id ) demo.database_remove_server(data_instance.provider_id)
def run(self): name = self.name i = self.begin end = i + 100 while i < end: de = Demo() de.parse(i,name) print('第',i,'页已经写入文件') i += 1
def start_demo(self): """Shows how to use the namespace to share data among processes.""" self.ns.msg = "0" from demo import Demo d = Demo(self.ns) d.setup() p = Process(name='demo', target=d.control_loop) p.start() for i in range(3): time.sleep(1) self.ns.msg = str(i) print("Updating msg to %d" % i)
def background_thread(): """Demo ball.""" ball = Demo() while True: time.sleep(0.01) ball.move() data = 'Player "%s" (%s) moved to %s.' % (ball.nick, ball.color, ball.short_coords()) socketio.emit('response', { 'data': data, # 'count': count, }, namespace='/test')
def demo(config): with open(config.word_emb_file, "r") as fh: word_mat = np.array(json.load(fh), dtype=np.float32) with open(config.char_emb_file, "r") as fh: char_mat = np.array(json.load(fh), dtype=np.float32) with open(config.test_meta, "r") as fh: meta = json.load(fh) model_dict = { 'Raw': Raw_Model, 'TPE': TPE_Model, 'T5': T5_Model, 'T5_Nob': T5_Nob_Model, 'Soft_T5': Soft_T5_Model, 'Soft_T5_Nob': Soft_T5_NoB_Model } if config.model not in model_dict: print('wrong %s model name' % (config.model)) exit(0) model = model_dict[config.model](config, None, word_mat, char_mat, trainable=False, demo=True) demo = Demo(model, config)
def quadratic(): turtle.setworldcoordinates(-12, -2, 12, 102) f = lambda x: x**2 demo = Demo(f) demo.start(-10) demo.bag([x * 0.5 for x in range(-20, 21)]) gen = hill_climb.seek(-10, 0.5, f) for x, y in gen: demo.move(x, y, False)
def cosine_slope(): turtle.setworldcoordinates(-6.2, -12, 6.2, 12) f = lambda x: -x + 5 * math.cos(x) demo = Demo(f) demo.start(-6) demo.bag([x * 0.1 for x in range(-62, 62)]) gen = hill_climb.seek(-6, 0.1, f) for x, y in gen: demo.move(x, y, False)
def demo(config): with open(config.word_emb_file, "r") as fh: word_mat = np.array(json.load(fh), dtype=np.float32) with open(config.test_meta, "r") as fh: meta = json.load(fh) model = Model(config, None, word_mat, trainable=False, demo=True) demo = Demo(model, config)
def process_video(name, fps=None): cap = cv2.VideoCapture(name) if fps is None: fps = cap.get(cv2.CAP_PROP_FPS) d = Demo(fps) for frame in cap_at_speed(cap, fps): d.data.append(gen_update(frame)) return d
def sa_demo(curr_x, step, f, temperature, x_points, min_x, max_x, *setup): turtle.setworldcoordinates(*setup) demo = Demo(f) demo.start(curr_x) demo.bag(x_points) gen = sim_anneal.seek(curr_x, step, f, temperature, min_x, max_x) for x, y, t, j in gen: demo.move(x, y, j) curr_x = x print(curr_x, f(curr_x))
def slanty_bag(): turtle.setworldcoordinates(-2.2, -2, 12.2, 22) demo = Demo(slanty_bag_curve) demo.bag([x * 0.5 for x in range(-1, 22)]) x = -0.5 step = 0.1 demo.start(x) gen = hill_climb.seek(x, step, slanty_bag_curve) for x, y in gen: demo.move(x, y, False)
def stuck(): turtle.setworldcoordinates(-12, -1, 12, 15) f = lambda x: math.fabs(x) demo = Demo(f) start = -10 step = 3 demo.start(start) demo.bag(range(-10, 11)) gen = hill_climb.seek(start, step, f) for x, y in gen: demo.move(x, y, False)
def open(self): self.ui.video_progressBar.setProperty("value", 0) self.ui.DispalyLabel.clear() self.stopEvent.clear() self.ui.close.setEnabled(True) self.ui.open.setEnabled(False) if self.isVideo: self.demo = Demo(self.fileName, self.output_video, self.output_txt, self.modes, self.callback_progress, self.callback_video, self.isVideo) else: self.rtsp_path = self.ui.input_camera_rtsp.toPlainText() self.demo = Demo(self.rtsp_path, self.output_video, self.output_txt, self.modes, callback_video=self.callback_video, is_video=self.isVideo) self.demo.start( ) # demo.start() 在执行open函数之后,就回收了,所以要使用self.demo,这样可以保留
def demo(config): """ Initiate a demo server to test/use the model visually. :param config: Contains the configurations to be used. :return: The created demo object. """ with open(config.word_emb_file, "r") as fh: word_mat = np.array(json.load(fh), dtype=np.float32) with open(config.char_emb_file, "r") as fh: char_mat = np.array(json.load(fh), dtype=np.float32) with open(config.test_meta, "r") as fh: meta = json.load(fh) model = Model(config, None, word_mat, char_mat, trainable=False, demo=True) d = Demo(model, config) return d
def pso_demo(f, bounded, count, epochs, w, c1, c2): #must be bounded if not bounded: print "ERROR: failure immanent: must be bounded" x_points = [x * 0.1 for x in range(-62, 62)] min_x, max_x = bounds(bounded, x_points) demo = [Demo(f) for _ in range(count)] demo[0].bag(x_points) gen = pso.swarm(count, min_x, max_x, epochs, f, w, c1, c2) start = True for particles in gen: for i, p in enumerate(particles): jump = True if start: demo[i].start(p.x) else: demo[i].move(p.x, f(p.x), jump) start = False
def demo(args, config): logger = logging.getLogger('qarc') logger.info('Start demo...') logger.info('Load vocab...') with open(os.path.join(config.vocab_dir, config.dataset_name + '_vocab.data'), 'rb') as fin: vocab = pickle.load(fin) model = choose_algo(args.algo, vocab, config) sess_config = tf.ConfigProto() sess_config.gpu_options.allow_growth = True sess = tf.Session(config=sess_config) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() saver.restore( sess, os.path.join(config.model_dir, args.algo)) demo = Demo(sess, config, model)
def sa_cosine_turtles(bounded): turtle.setworldcoordinates(-6.2, -12, 6.2, 12) curr_x = [-6.0, 0, +6.0] f = lambda x: 10 * math.cos(x) count = 3 demo = [Demo(f) for _ in range(count)] x_points = [x * 0.1 for x in range(-62, 62)] demo[0].bag(x_points) min_x, max_x = bounds(bounded, x_points) gens = [] temperature = 10.0 step = 0.2 for i, x in enumerate(curr_x): demo[i].start(curr_x[i]) gens.append(sim_anneal.seek(x, step, f, temperature, min_x, max_x)) for (x1, y1, t1, j1), (x2, y2, t2, j2), (x3, y3, t3, j3) in zip(*gens): demo[0].move(x1, y1, j1) demo[1].move(x2, y2, j2) demo[2].move(x3, y3, j3)
def check_pool(self): demo = Demo(self.config) database = demo.database logging.debug('CHECK POOL INSTANCE') images_pool = {} instances_pool = {} # Get image key with pool value for key, image in self.config.images.items(): images_pool[key] = {'need': 0, 'instances': []} if 'pool' in image: images_pool[key]['need'] = image['pool'] # Get all pooled instance for instance in demo.get_pooled_instance_database(): # Type in database but not in config if instance['type'] not in images_pool: images_pool[instance['type']] = {'need': 0, 'instances': []} images_pool[instance['type']]['instances'].append(instance) for key, image_pool in images_pool.items(): count_pool_instance = len(image_pool['instances']) # Remove overpopulated pool if image_pool['need'] < count_pool_instance: logging.debug('Pool %s is overpopulated', key) while count_pool_instance > image_pool['need']: instance_to_remove = image_pool['instances'].pop() demo.database_remove_server(instance_to_remove['id']) count_pool_instance -= 1 elif image_pool['need'] > count_pool_instance: logging.debug('Pool %s is underpopulated', key) while count_pool_instance < image_pool['need']: logging.debug('Pool create %s', key) demo.create_pool_instance(key) count_pool_instance += 1 else: logging.debug('Pool %s is ok', key)
def demo(): dict_ = pickle.load(open(Params.data_dir + "dictionary.pkl","r")) vocab_size = dict_.vocab_size model = Model(is_training = False, vocab_size = vocab_size, demo = True); print("Built model") demo_run = Demo(model = model)
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo([ #x , y, z, yaw, sleep [0.0, 0.0, 0.8, 0, 3], [0.5, 0.0, 0.8, 0, 3], [0.0, 0.5, 0.8, 0, 3], [-0.5, 0.0, 0.8, 0, 3], [0.0, -0.5, 0.8, 0, 3], ]) demo.run()
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo( [ #x , y, z, yaw, sleep [0.0 , 0.5, 1, 0, 2], [0 , -0.5, 1, 0, 2], [0.5 , -0.5, 1, 0, 2], [0.5 , 0, 1, 0, 2], [0.0 , 0, 1, 0, 0], ] ) demo.run()
from demo import Demo if __name__ == '__main__': print("Run the local host for online demo...") demo_run = Demo()
def test_demo(self): self.assertEqual(Demo().demo1(1,23), 45)
def __init__(self): ckpt_path = './ckpt/exif_final/exif_final.ckpt' self.model = Demo(ckpt_path=ckpt_path, use_gpu=0, quality=3.0, num_per_dim=30)
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo([ #x , y, z, yaw, sleep [0.0, -1.0, 0.5, 0, 2], [1.5, -1.0, 0.5, 0, 2], [-0.5, -1.0, 0.75, 0, 2], [-0.5, -1.5, 0.5, 0, 2], [0.0, -1.0, 0.5, 0, 0], ]) demo.run()
""" Some long comment """ if __name__ == '__main__': from demo import Demo # line comment print "enter test_demo" Demo(0,0) d = Demo(1,0) if 0: d.f()
from flask import Flask from demo import Demo from flask import Flask, request from PIL import Image from gevent.pywsgi import WSGIServer import base64 app = Flask(__name__) D = Demo( "checkpoint/IPCGANS/2019-01-14_08-34-45/saved_parameters/gepoch_6_iter_4000.pth" ) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/upload_file', methods=['POST']) def upload_file(): img = request.files['img'] img.save("tmp.jpg") img = Image.open("tmp.jpg").resize((400, 400), Image.BILINEAR) for i in range(5): D.demo(img, i).resize((400, 400), Image.BILINEAR).save("tmp%d.jpg" % i) with open("tmp.jpg", "rb") as f: base64_data = base64.b64encode(f.read()) return base64_data @app.route('/get_image/<string:age>', methods=['GET'])
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo([ #x , y, z, yaw, sleep [-0.75, 0.3, 0.5, 0, 5], [-0.75, 0.6, 0.5, 0, 5], [-1, 0.3, 0.75, 0, 2], # [-1.5 , 0.5, 0.5, 0, 2], # [0.0 , 0.0, 0.5, 0, 0], #[0.0 , 1.0, 0.3, 0], #[1.0 , 1.0, 0.5, 0], #[0.0 , 0.5, 0.2, 0], #[0.0 , 0.5, 0.0, 0], ]) demo.run() # xmax = 0.8 ymax = 1.2 xmin = -1.7 ymin = -0.9
class GuiEvent: def __init__(self, ui, mainWnd): self.ui = ui self.mainWnd = mainWnd # 默认视频源为相机 self.ui.radioButtonVideo.setChecked(True) self.isVideo = True # 信号槽设置 ui.open.clicked.connect(self.open) ui.close.clicked.connect(self.close) ui.radioButtonCam.clicked.connect(self.radioButtonCam) ui.radioButtonVideo.clicked.connect(self.radioButtonVideo) ui.find_video.clicked.connect(self.find_video) ui.find_output.clicked.connect(self.find_output) # 创建一个关闭事件并设为未触发 self.stopEvent = threading.Event() self.stopEvent.clear() self.ui.close.setEnabled(False) self.modes = init_models() print(" ") def callback_progress(self, percentage): self.ui.video_progressBar.setProperty("value", percentage * 100) def callback_video(self, image): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) showImage = QtGui.QImage(image.data, image.shape[1], image.shape[0], QtGui.QImage.Format_RGB888) self.ui.DispalyLabel.setPixmap(QPixmap.fromImage(showImage)) if self.stopEvent.is_set(): # 关闭事件置为未触发,清空显示label self.stopEvent.clear() return True return False # self.ui.DispalyLabel.clear() # pix = QtGui.QPixmap.fromImage(showImage) # self.item = QGraphicsPixmapItem(pix) # 创建像素图元 # self.scene = QGraphicsScene() # 创建场景 # self.scene.addItem(self.item) # self.ui.graphicsView.setScene(self.scene) # 将场景添加至视图 def radioButtonCam(self): self.isVideo = False def radioButtonVideo(self): self.isVideo = True def find_video(self): self.fileName, self.fileType = QFileDialog.getOpenFileName( self.mainWnd, 'Choose file', '', '*') self.ui.input_video_path.setPlainText(self.fileName) def find_output(self): self.output_dir = QFileDialog.getExistingDirectory( self.mainWnd, 'Choose dir', '') self.ui.output_path.setPlainText(self.output_dir) self.output_video = os.path.join(self.output_dir, opt.default_output_name + '.avi') self.output_txt = os.path.join(self.output_dir, opt.default_output_name + '.txt') def open(self): self.ui.video_progressBar.setProperty("value", 0) self.ui.DispalyLabel.clear() self.stopEvent.clear() self.ui.close.setEnabled(True) self.ui.open.setEnabled(False) if self.isVideo: self.demo = Demo(self.fileName, self.output_video, self.output_txt, self.modes, self.callback_progress, self.callback_video, self.isVideo) else: self.rtsp_path = self.ui.input_camera_rtsp.toPlainText() self.demo = Demo(self.rtsp_path, self.output_video, self.output_txt, self.modes, callback_video=self.callback_video, is_video=self.isVideo) self.demo.start( ) # demo.start() 在执行open函数之后,就回收了,所以要使用self.demo,这样可以保留 def close(self): # 关闭事件设为触发,关闭视频播放 self.stopEvent.set() self.ui.open.setEnabled(True) self.ui.close.setEnabled(False)
def main(): """SimDem CLI interpreter""" commands = config.modes command_string = "" for command in commands: command_string = command_string + command + "|" command_string = command_string[0:len(command_string)-1] p = optparse.OptionParser("%prog [" + command_string + "] <options> DEMO_NAME", version=config.SIMDEM_VERSION) p.add_option('--style', '-s', default="tutorial", help="The style of simulation you want to run. 'tutorial' (the default) will print out all text and pause for user input before running commands. 'simulate' will not print out the text but will still pause for input.") p.add_option('--path', '-p', default="demo_scripts/", help="The Path to the demo scripts directory.") p.add_option('--auto', '-a', default="False", help="Set to 'true' (or 'yes') to prevent the application waiting for user keypresses between commands. Set to 'no' when running in test mode to allow users to step through each test.") p.add_option('--test', '-t', default="False", help="If set to anything other than False the output of the command will be compared to the expected results in the sript. Any failures will be reported") p.add_option('--fastfail', default="True", help="If set to anything other than True test execution has will stop on the first failure. This has no affect if running in any mode other than 'test'.") p.add_option('--debug', '-d', default="False", help="Turn on debug logging by setting to True.") p.add_option('--webui', '-w', default="False", help="If set to anything other than False will interact with the user through a Web UI rather than the CLI.") p.add_option('--output', '-o', default="log", help="Format of the output. The default is `log` which will output all stdout data. Other options are `summary` which provides a summary of the execution status and `json`") options, arguments = p.parse_args() if not options.path.endswith("/"): options.path += "/" if options.auto == "False": is_automatic = False else: is_automatic = True if options.test == "False": is_test = False else: is_test = True if options.fastfail == "True": is_fast_fail= True else: is_fast_fail= False if options.style == "simulate": simulate = True elif options.style == 'tutorial': simulate = False else: print("Unknown style (--style, -s): " + options.style) exit(1) if options.debug.lower() == "true": config.is_debug = True if len(arguments) == 2: script_dir = options.path + arguments[1] else: script_dir = options.path cmd = None if len(arguments) > 0: cmd = arguments[0] # 'run' is deprecated in the CLI, but not yet removed from code if cmd == "tutorial": cmd = "run" if cmd == "test": is_test = True is_auto = True filename = "README.md" is_docker = os.path.isfile('/.dockerenv') demo = Demo(is_docker, script_dir, filename, simulate, is_automatic, is_test, is_fast_fail, output_format=options.output); if options.webui == "False": ui = Ui() else: ui = WebUi(config.port) print("Server started. Listening on port " + str(ui.port)) print("Point your browser at " + str(ui.port)) print() while not ui.ready: time.sleep(0.25) print("Waiting for client connection") cmd = None demo.set_ui(ui) demo.run(cmd)
class Handler(BaseHTTPRequestHandler, object): def __init__(self, *args, **kwargs): self.config = DemoConfig() self.demo = Demo(self.config) self.user = None self.headers_to_send = {} super(Handler, self).__init__(*args, **kwargs) def send_http_error(self, code, error_message, error_type=None): self.wfile.flush() self.send_response(code) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write( json.dumps({ 'error': error_message, 'type': error_type }) ) def send_http_message(self, code=200, message=''): self.wfile.flush() self.send_response(code) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(json.dumps({'info': message})) def send_all_header(self, code=200): self.send_response(code) logging.debug('Add Header') for name, value in self.headers_to_send.items(): logging.debug('name %s value %s', name, value) self.send_header(name, value) self.end_headers() def send_file(self, file): f = open('web/'+file) self.set_mime() self.send_all_header(200) self.wfile.write(f.read()) f.close() return def instance_create(self, image_key, time=None): id = self.demo.create_instance( image_key, token=self.user.token, time=time ) rep = {'id': id} self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(201) self.wfile.write(json.dumps(rep)) self.wfile.write('\n') return def instance_info(self, instance_id): self.demo.check_user_own_instance( self.user.token, instance_id, raise_exception=True ) if not self.demo.provider.instance_exist(instance_id): raise DemoExceptionInstanceNotFound() info = {'id': instance_id, 'system_up': False, 'instance_up': False} if self.demo.instance_is_up(instance_id): info['instance_up'] = True info['id'] = instance_id info['address'] = self.demo.provider.get_instance_ip(instance_id) info['demo_address'] = self.demo.get_soft_address(instance_id) info['life_time'] = self.demo.get_life_time(instance_id) info['dead_time'] = self.demo.get_dead_time(instance_id) if self.demo.check_system_up(instance_id): info['system_up'] = True self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(info)) return def get_user(self): is_admin = self.demo.auth.is_admin(self.user.login) info = { 'token': self.user.token, 'login': self.user.login, 'admin': is_admin } self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(info)) def user_instances_info(self): if self.user is None: self.send_http_error(404, 'User not found') instances = self.demo.get_user_instance_database(self.user.token) self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(instances)) return def all_instances_info(self): instances = self.demo.get_all_instance_database() self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(instances)) return def pool_instances_info(self): instances = self.demo.get_pooled_instance_database() self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(instances)) return def images_info(self): http_images = {} for name in self.config.images.keys(): image = self.config.images[name] time_max = None if 'time_max' in image: time_max = image['time_max'] data = { 'name': image['name'], 'desc': image['desc'], 'img': image['img'], 'max_time': time_max, 'default_time': image['time_default'] } http_images[name] = data self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(http_images)) return def image_info(self, image_key): if image_key not in self.config.images: raise DemoExceptionInstanceNotFound() image = self.config.images[image_key] time_max = None if 'time_max' in image: time_max = image['time_max'] data = { 'name': image['name'], 'desc': image['desc'], 'img': image['img'], 'max_time': time_max, 'default_time': image['time_default'], 'info': image['info'] } http_image = data self.headers_to_send['Content-type'] = 'application/json' self.send_all_header(200) self.wfile.write(json.dumps(http_image)) return def connect(self, user, password): mail = self.demo.auth.check_auth(user, password) if not mail: raise DemoExceptionErrorAuth user = self.demo.create_user(mail) self.write_cookie(COOKIE_SESSION_NAME, user.token) self.send_all_header() def set_mime(self): mimetype = None if self.path.endswith(".html"): mimetype = 'text/html' if self.path.endswith(".js"): mimetype = 'application/javascript' if self.path.endswith(".css"): mimetype = 'text/css' if self.path.endswith(".jpg"): mimetype = 'image/jpg' if self.path.endswith(".gif"): mimetype = 'image/gif' if self.path.endswith(".png"): mimetype = 'image/png' if mimetype is not None: self.headers_to_send['Content-type'] = mimetype def do_GET(self): str_path = self.path.split('?')[0] try: # Public URL if self.path == "/": self.send_file('index.html') return if os.path.isfile('web/'+str_path): self.send_file(str_path) return if self.path == '/api/disconnect': self.write_cookie(COOKIE_SESSION_NAME, 'disable') self.send_all_header() return # Private URL if not self.cookie_session(): self.send_http_error(404, 'No action') return if self.path == "/api/user": self.get_user() return if self.path == "/api/image": self.images_info() return if self.path == "/api/myinstance": self.user_instances_info() return match = re.match("/api/instance/(.*)", self.path) if match: self.instance_info(match.group(1)) return match = re.match("/api/image/(.*)", self.path) if match: self.image_info(match.group(1)) return # Admin url if not self.demo.auth.is_admin(self.user.login): self.send_http_error(404, 'No action') return if self.path == "/api/allinstance": self.all_instances_info() return if self.path == "/api/poolinstance": self.pool_instances_info() return self.send_http_error(404, 'No action') except DemoExceptionInstanceNotFound as e: self.send_http_error(404, e.message) except (DemoExceptionErrorAuth, DemoExceptionInvalidOwner) as e: if self.config.security_type == 'email': type = 'email' else: type = 'auth' self.send_http_error(401, e.message, type) except DemoExceptionToMuchInstanceImage as e: self.send_http_error(503, e.message, str(type(e))) except Exception as e: if self.config.dev: raise self.send_http_error(500, e.message, str(type(e))) return def do_PUT(self): try: length = int(self.headers.getheader('Content-Length')) put_vars = json.loads(self.rfile.read(length)) # Public match = re.match("/api/user", self.path) if match: if 'email' in put_vars: url = 'http://'+self.headers.getheader('Host')+'/' email = put_vars['email'] user = self.demo.create_user(email) self.demo.mail.send_token_mail(user.login, user.token, url) self.send_all_header() return else: self.send_http_error(400, 'Email not found in request') return # Private if not self.cookie_session(): return match = re.match("/api/instance/(.*)", self.path) if match: time = None if 'time' in put_vars: time = int(put_vars['time']) self.instance_create(match.group(1), time=time) return self.send_http_error(404, 'No action') except DemoExceptionInstanceNotFound as e: self.send_http_error(404, e.message) except DemoExceptionToMuchInstanceImage as e: self.send_http_error(400, e.message) except (DemoExceptionErrorAuth, DemoExceptionInvalidOwner) as e: if self.config.security_type == 'email': type = 'email' else: type = 'auth' self.send_http_error(401, e.message, type) except Exception as e: if self.config.dev: raise self.send_http_error(500, e.message, str(type(e))) return def do_POST(self): try: length = int(self.headers.getheader('Content-Length')) put_vars = json.loads(self.rfile.read(length)) # Public if self.path == '/api/connect': if 'user' in put_vars and 'password' in put_vars and\ self.demo.auth: self.connect(put_vars['user'], put_vars['password']) return self.send_http_error(404, 'No action') # Private if not self.cookie_session(): return match = re.match("/api/instance", self.path) if match: if 'id' in put_vars: id = put_vars['id'] if 'add_time' in put_vars: self.demo.check_user_own_instance(self.user.token, id) self.demo.instance_add_time( id, int(put_vars['add_time']) ) self.instance_info(id) return # Admin url if not self.demo.auth.is_admin(self.user.login): self.send_http_error(404, 'No action') return if 'time' in put_vars: self.demo.instance_set_life_time( id, int(put_vars['time']) ) self.send_http_message(200, 'ok') return self.send_http_error(404, 'No action') except DemoExceptionInstanceNotFound as e: self.send_http_error(404, e.message) except DemoExceptionNonUpdatableInstance as e: self.send_http_error(400, e.message) except (DemoExceptionErrorAuth, DemoExceptionInvalidOwner) as e: if self.config.security_type == 'email': type = 'email' else: type = 'auth' self.send_http_error(401, e.message, type) except Exception as e: if self.config.dev: raise self.send_http_error(500, e.message) return def do_DELETE(self): try: if not self.cookie_session(): return match = re.match("/api/instance/(.*)", self.path) if match: provider_id = match.group(1) self.demo.check_user_own_instance( self.user.token, provider_id ) self.demo.database_remove_server(provider_id) self.send_http_message(200, 'ok') return self.send_http_error(404, 'No action') except DemoExceptionInstanceNotFound as e: self.send_http_error(404, e.message) except (DemoExceptionErrorAuth, DemoExceptionInvalidOwner) as e: if self.config.security_type == 'email': type = 'email' else: type = 'auth' self.send_http_error(401, e.message, type) except Exception as e: if self.config.dev: raise self.send_http_error(500, e.message) return def cookie_session(self): token = self.read_cookie(COOKIE_SESSION_NAME) if token is not None: self.user = self.demo.get_user_by_token(token) if self.user: self.demo.update_user_last_connection(self.user.login) # Update session time self.write_cookie(COOKIE_SESSION_NAME, self.user.token) if self.user: return True if self.config.security_type == 'open': self.user = self.demo.create_user() self.write_cookie(COOKIE_SESSION_NAME, self.user.token) else: if self.config.security_type == 'email': type = 'email' else: type = 'auth' raise DemoExceptionErrorAuth return False return True def write_cookie(self, name, value, age=999999999999): c = Cookie.SimpleCookie() c[name] = value c[name]['max-age'] = age c[name]['path'] = '/' logging.debug('New cookie : %s %s', name, value) self.headers_to_send['Set-Cookie'] = c.output(header='') def read_cookie(self, name): if "Cookie" in self.headers: c = Cookie.SimpleCookie(self.headers["Cookie"]) logging.debug(" Cookies : %s", self.headers["Cookie"]) if name not in c: return None return c[name].value return None
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo([ #x , y, z, yaw, sleep [0.0, 0.0, 0.5, 0, 5], [0.0, 0.0, 0.5, 0, 2], [0.0, 0.0, 0.7, 0, 2], [0.0, 0.0, 0.5, 0, 2], [0.0, 0.0, 0.5, 0, 0], """ [-.5 , 0.0, 0.6, 0, 2], [0.0 , 0.0, 0.6, 0, 2], [0.0 , 0.5, 0.6, 0, 2], [-.5 , 0.5, 0.6, 0, 2], [-.5 , 0.0, 0.6, 0, 0], """ ]) demo.run()
if current_song is None: current_song = CURRENT_SONGS.get("chrome") if current_song is None or current_song not in SONG_DB: if current_song is not None: download = strtobool( input( "Would you like to download and process {} by {}?".format( current_song[1], current_song[0]))) if download: if current_song[0] is not None: search = " - ".join(current_song) else: search = current_song[1] url = get_url(search) print(url) gen_video(url, SONG_DB, SONG_LOCK) print(SONG_DB) else: print("Sleeping...", current_song) time.sleep(5) continue demo = Demo.from_file(SONG_DB[current_song]) print(len(demo.data), len(demo.wav)) seconds = 4 frames = 48000 * seconds data = read_stream(stream, frames) start = time.time() xcorr = fftconvolve(demo.wav, data[::-1]) time_in_video = time.time() - start + xcorr.argmax() / 48000 play_at_time(demo, time_in_video)
#!/usr/bin/env python import os, sys, time import logging from demo import Demo logging.basicConfig( level=logging.DEBUG ) if __name__ == "__main__": with open(sys.argv[1], "r") as f: Demo.from_file(f).parse()
def on_pubmsg(self, connection, event): source = event.source() nick = source.split('!')[0] args = event.arguments() message = args[0].split(' ') if message[0] == '!!' and len(message) > 1: try: if self.admins[event.source()] == 'admin': command = "say \"^8(^1IRC:^5@^2" + nick + "^8)^7 " + ' '.join(message[1:]) + "\"" elif self.admins[event.source()] == 'mod': command = "say \"^8(^1IRC:^5+^2" + nick + "^8)^7 " + ' '.join(message[1:]) + "\"" self.rcon.send(command) except: #command = "say \"^8(^1IRC:^2" + nick + "^8)^7 " + ' '.join(message[1:]) + "\"" self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN_PRIV) elif message[0][0] == '@' and len(message[0]) > 1 and len(message) > 1: if message[0][1:].isdigit(): cid = message[0].split("@")[1] output = "tell " + cid + " \"^8(^1IRC:^2" + nick + "^8)^7 " + ' '.join(message[1:]) + "\"" self.rcon.send(output) elif message[0] == '!bigtext' and len(message) > 1: command = "bigtext \"" + ' '.join(message[1:]) + "\"" self.rcon.send(command) elif message[0] == '!kick' and len(message) > 1: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) self.rcon.send("kick " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_KICK % (nick, c.coloredIrcNickname())) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!slap' and len(message) > 1: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) self.rcon.send("slap " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_SLAP % (nick, c.coloredIrcNickname())) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!nuke' and len(message) > 1: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) self.rcon.send("nuke " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_NUKE % (nick, c.coloredIrcNickname())) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!mute' and len(message) > 1: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) self.rcon.send("mute " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_MUTE % (nick, c.coloredIrcNickname())) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!nextmap' and len(message) > 1: try: if self.admins[event.source()] == 'admin': self.rcon.send("g_nextmap " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_NEXTMAP % (message[1])) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!map': if len(message) > 1: try: if self.admins[event.source()] == 'admin': self.rcon.send("map " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_MAP %(nick, message[1])) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) else: self.connection.privmsg(self.target, self.m.MSG_CURR_MAP %(self.currentMap)) elif message[0] == "!shuffle": try: if self.admins[event.source()] == 'admin': self.rcon.send("shuffleteams") self.connection.privmsg(self.target, self.m.MSG_RCON_SHUFFLE % (nick)) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!force' and len(message) > 3: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) self.rcon.send("forcecvar " + message[1] + " " + message[2] + " " + ''.join(message[3:])) self.connection.privmsg(self.target, self.m.MSG_RCON_FORCECVAR % (nick, message[2], ''.join(message[3:]), c.coloredIrcNickname())) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!list': if self.reader != None: output = (self.m.MSG_LIST % (len(self.reader.clients), self.currentMap)) + " " for key, c in self.reader.clients.iteritems(): output = output + "(" + str(key) + ")" + c.coloredIrcNickname() + " " self.connection.privmsg(self.target, output) else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT) elif message[0] == '!ts3' and self.cfg.ts3enabled: try: ts3client = TS3(self.cfg.ts3host, self.cfg.ts3port, self.cfg.ts3user, self.cfg.ts3pass, self, self.target, "list", "") ts3client.start() except: self.connection.privmsg(self.target, self.m.MSG_ERR_GENERAL) elif message[0] == '!ts3info' and len(message) > 1 and self.cfg.ts3enabled: try: ts3client = TS3(self.cfg.ts3host, self.cfg.ts3port, self.cfg.ts3user, self.cfg.ts3pass, self, self.target, "info", message[1]) ts3client.start() except: self.connection.privmsg(self.target, self.m.MSG_ERR_GENERAL) elif message[0] == '!ban' and len(message) > 1: if self.reader != None: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) self.rcon.send("addIP " + c.ip) self.rcon.send("kick " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_BAN % (nick, c.coloredIrcNickname(), c.ip)) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except KeyError: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif (message[0] == '!banguid' or message[0] == '!permban') and len(message) > 2: if self.reader != None: try: if self.admins[event.source()] == 'admin': try: c = client.Client(-1) if message[1][0] == "#": ext_id = message[1].split("#")[1] ret = self.db.extInfo(int(ext_id)) c.guid = ret[2] c.name = ret[3] c.ip = ret[0] else: c = self.getClientObject(message[1]) guid = c.guid reason = ' '.join(message[2:]) id = self.db.getId(c.guid) try: self.db.permBan(id, reason, nick) except: self.connection.privmsg(self.target, self.m.MSG_ERR_DB) self.rcon.send("addIP " + c.ip) self.rcon.send("kick " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_BANGUID % (nick, c.coloredIrcNickname(), c.guid, c.ip, reason)) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!search' and len(message) > 1: try: if self.admins[event.source()] == 'admin': try: if len(message[1]) >= 3 and message[1].isalnum(): results = self.db.search(message[1]) output = self.m.MSG_SEARCH % (message[1]) + " " if len(results) > 40: output = output + self.m.MSG_ERR_SEARCH_RES else: for result in results: output = output + "(\x02#" + str(result[1]) + "\x02)" + result[0] + " " else: output = self.m.MSG_ERR_SEARCH self.connection.privmsg(self.target, output) except: print sys.exc_info() self.connection.privmsg(self.target, self.m.MSG_ERR_DB) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!tempban' and len(message) > 2: try: if self.admins[event.source()] == 'admin': try: c = client.Client(-1) c = self.getClientObject(message[1]) id = self.db.getId(c.guid) duration = float(message[2]) if duration > 0.0: self.db.tempBan(id, duration, nick) self.rcon.send("kick " + message[1]) self.connection.privmsg(self.target, self.m.MSG_RCON_TEMPBAN % (nick, c.coloredIrcNickname(), str(duration))) except: self.connection.privmsg(self.target, self.m.MSG_ERR_DB) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!extinfo' and len(message) > 1: try: if self.admins[event.source()] == 'admin': try: ret = self.db.extInfo(int(message[1])) try: (ip_ptr, alias, addr) = socket.gethostbyaddr(ret[0]) added = " [" + ip_ptr + "]" except: added = "" output = self.m.MSG_EXTINFO % (message[1], ret[3], ret[0], added, ret[2], str(ret[1])) self.connection.privmsg(self.target, output) except: print sys.exc_info() self.connection.privmsg(self.target, self.m.MSG_ERR_DB) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN) elif message[0] == '!aliases' or message[0] == '!alias' and len(message) > 1: if self.reader != None: try: if self.admins[event.source()] == 'mod' or self.admins[event.source()] == 'admin': try: c = client.Client(-1) if message[1][0] == "#": ext_id = message[1].split("#")[1] ret = self.db.extInfo(int(ext_id)) c.guid = ret[2] c.name = ret[3] c.ip = ret[0] else: c = self.reader.clients[int(message[1])] guid = c.guid try: aliases = self.db.getAliases(guid) output = self.m.MSG_ALIASES % (c.coloredIrcNickname()) + " " if len(aliases) == 0: output = output + "None" self.connection.privmsg(self.target, output) else: i = 0 for alias in aliases: output = output + alias[0] + " " i = i + 1 if i == 10: self.connection.privmsg(self.target, output) i = 0 output = self.m.MSG_ALIASES % (c.coloredIrcNickname()) + " " time.sleep(1.0) if i != 0: self.connection.privmsg(self.target, output) except: print sys.exc_info() self.connection.privmsg(self.target, self.m.MSG_ERR_DB) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN_MOD) else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT) elif message[0] == '!info' and len(message) > 1: if self.reader != None: try: if self.admins[event.source()] == 'admin' or self.admins[event.source()] == 'mod': try: c = client.Client(-1) c = self.reader.clients[int(message[1])] output = self.m.MSG_INFO + " " + c.coloredIrcNickname() + " " ip = c.ip.split(':')[0] try: (ip_ptr, alias, addr) = socket.gethostbyaddr(ip) added = " [" + ip_ptr + "]" except: print sys.exc_info() added = "" output = output + "(" + c.ip + added + ", " + c.guid + ")" if self.cfg.geoEnabled: loc = Localization(self, c.ip, output, self.target) loc.start() else: self.connection.privmsg(self.target, output) except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN_MOD) else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT) elif message[0] == '!demo' and len(message) > 1: if self.reader != None: try: if self.admins[event.source()] == 'admin' or self.admins[event.source()] == 'mod': try: if len(message) >= 3: try: duration = int(message[2]) except: duration = 1 else: duration = 1 c = client.Client(-1) c = self.reader.clients[int(message[1])] output = self.m.MSG_DEMO + c.coloredIrcNickname() d = Demo(self, self.rcon, output, self.target, duration, c.id) d.start() except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID) except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN_MOD) else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT) elif message[0] == '!stamina' and len(message) > 2: if self.reader != None: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) output = self.m.MSG_RCON_STAMINA % (c.coloredIrcNickname(), message[2]) self.rcon.send("stamina " + message[1] + " " + message[2]) self.connection.privmsg(self.target, output); except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID); except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN); else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT); elif message[0] == '!wj' and len(message) > 2: if self.reader != None: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) output = self.m.MSG_RCON_WJ % (c.coloredIrcNickname(), message[2]) self.rcon.send("walljumps " + message[1] + " " + message[2]) self.connection.privmsg(self.target, output); except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID); except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN); else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT); elif message[0] == '!damage' and len(message) > 3: if self.reader != None: try: if self.admins[event.source()] == 'admin': try: c = self.getClientObject(message[1]) if message[2] == 'source' or message[2] == 'target': output = self.m.MSG_RCON_DAMAGE % (c.coloredIrcNickname(), message[2], message[3]) self.rcon.send("damage " + message[1] + " " + message[2] + " " + message[3]) self.connection.privmsg(self.target, output); else: self.connection.privmsg(self.target, self.m.MSG_ERR_PARAMS); except: self.connection.privmsg(self.target, self.m.MSG_ERR_CID); except: self.connection.privmsg(self.target, self.m.MSG_ERR_ADMIN); else: self.connection.privmsg(self.target, self.m.MSG_ERR_OBJECT);
import time import pyaudio from matplotlib import pyplot as plt from scipy.signal import fftconvolve from videoprocess import process_video, play_at_time from demo import Demo import ffmpeg import numpy as np CHUNKSIZE = 512 # fixed chunk size def read_stream(stream, frames): return np.mean(np.frombuffer(stream.read(frames), dtype=np.int16).reshape(-1, 2), axis=1) if __name__ == '__main__': demo = Demo.from_file("Drunk.npz") out, err = ( ffmpeg .input('Robotaki - Drunk.mp4') .output('pipe:', ac=1, ar=48000, format='wav') .run(capture_stdout=True, capture_stderr=True) ) wavrate = int(re.search(r"([0-9]+) Hz", err.decode('utf-8')).group(1)) wav = ( np .frombuffer(out, np.int16) )
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo( [ #x , y, z, yaw, sleep [0.0 , 0.0, 0.5, 0, 2], [1.5 , 0.0, 0.5, 0, 2], [-1.5 , 0.0, 0.75, 0, 2], [-1.5 , 0.5, 0.5, 0, 2], [0.0 , 0.0, 0.5, 0, 0], #[0.0 , 1.0, 0.3, 0], #[1.0 , 1.0, 0.5, 0], #[0.0 , 0.5, 0.2, 0], #[0.0 , 0.5, 0.0, 0], ] ) demo.run()
def main(): """SimDem CLI interpreter""" commands = config.modes command_string = "" for command in commands: command_string = command_string + command + "|" command_string = command_string[0:len(command_string) - 1] p = optparse.OptionParser("%prog [" + command_string + "] <options> DEMO_NAME", version=config.SIMDEM_VERSION) p.add_option( '--style', '-s', default="tutorial", help= "The style of simulation you want to run. 'tutorial' (the default) will print out all text and pause for user input before running commands. 'simulate' will not print out the text but will still pause for input." ) p.add_option('--path', '-p', default="demo_scripts/", help="The Path to the demo scripts directory.") p.add_option( '--auto', '-a', default="False", help= "Set to 'true' (or 'yes') to prevent the application waiting for user keypresses between commands. Set to 'no' when running in test mode to allow users to step through each test." ) p.add_option( '--test', '-t', default="False", help= "If set to anything other than False the output of the command will be compared to the expected results in the sript. Any failures will be reported" ) p.add_option( '--fastfail', default="True", help= "If set to anything other than True test execution has will stop on the first failure. This has no affect if running in any mode other than 'test'." ) p.add_option('--debug', '-d', default="False", help="Turn on debug logging by setting to True.") p.add_option( '--webui', '-w', default="False", help= "If set to anything other than False will interact with the user through a Web UI rather than the CLI." ) options, arguments = p.parse_args() if not options.path.endswith("/"): options.path += "/" if options.auto == "False": is_automatic = False else: is_automatic = True if options.test == "False": is_test = False else: is_test = True if options.fastfail == "True": is_fast_fail = True else: is_fast_fail = False if options.style == "simulate": simulate = True elif options.style == 'tutorial': simulate = False else: print("Unknown style (--style, -s): " + options.style) exit(1) if options.debug.lower() == "true": config.is_debug = True if len(arguments) == 2: script_dir = options.path + arguments[1] else: script_dir = options.path cmd = None if len(arguments) > 0: cmd = arguments[0] # 'run' is deprecated in the CLI, but not yet removed from code if cmd == "tutorial": cmd = "run" if cmd == "test": is_test = True is_auto = True filename = "README.md" is_docker = os.path.isfile('/.dockerenv') demo = Demo(is_docker, script_dir, filename, simulate, is_automatic, is_test) if options.webui == "False": ui = Ui() else: ui = WebUi(config.port) print("Server started. Listening on port " + str(ui.port)) print("Point your browser at " + str(ui.port)) print() while not ui.ready: time.sleep(0.25) print("Waiting for client connection") cmd = None demo.set_ui(ui) demo.run(cmd)
from logger import logging from constants import APP_NAME from cabs.factories.populate_db import populate_db from demo import Demo if __name__ == '__main__': logging.info(f"Welcome to {APP_NAME}") populate_db() Demo.run_demo()
def __init__(self, *args, **kwargs): self.config = DemoConfig() self.demo = Demo(self.config) self.user = None self.headers_to_send = {} super(Handler, self).__init__(*args, **kwargs)
#!/usr/bin/env python from demo import Demo if __name__ == '__main__': demo = Demo([ #x , y, z, yaw, sleep [0.5, 0.0, 0.5, 0, 2], [-0.5, 0, 0.5, 0, 2], [-0.5, 0.5, 0.5, 0, 2], [0, 0.5, 0.5, 0, 2], [0.0, 0.0, 0.5, 0, 0], #[0.0 , 1.0, 0.3, 0], #[1.0 , 1.0, 0.5, 0], #[0.0 , 0.5, 0.2, 0], #[0.0 , 0.5, 0.0, 0], ]) demo.run()