def upload(self, filepath): # extract zip files = self.extractZipFiles(filepath) # validate files xmltools = XMLTools() allValid = xmltools.validateFiles(files) if len(files) != 0 and allValid: REST = RESTClient() for filetype, content in files: if filetype == "cp": cp = content # get topic name for filename tree = etree.fromstring(cp) ns = {'ns': 'http://www.imsglobal.org/xsd/imsld_v1p0'} topic = tree.xpath('//ns:learning-design/ns:title', namespaces=ns)[0].text # write cp file to db r = REST.post("cp", data={'topic': topic}, payload=cp) print r if filetype == "qti": qti = content # get item id for filename tree = etree.fromstring(qti) id = tree.xpath("/*[local-name()]")[0].attrib['identifier'] id = id.split("ITM_")[1] fname = 'qti_' + id + '.xml' #write qti file to db r = REST.post("item", data={'fname': fname}, payload=qti) print r
def service_thread(shelf): def callback(json): if shelf == None: return for obj in json: shelf.turnLedOn(obj['product_id']) requests.delete('http://iot.vpolevoy.com/api/jobs/%s/' % obj['product_id']) rest = RESTClient("http://iot.vpolevoy.com/api/jobs/?format=json", callback) rest.run()
def test_tokenEcho(): server = RESTServer(token='secret', default_echoes=True) server.start(block=False) # Test token works client = RESTClient(token='secret') assert client.tokenEcho('meow meow') == 'meow meow' # Test token rejected badClient = RESTClient() assert badClient.tokenEcho('meow meow') == 'Bad Token' server.stop()
def test_ssl_bad(): server = RESTServer(SSLKey="server.key", SSLCert="server.crt", portRange=[8000,9000]) server.start(block=False) client = RESTClient() error = False try: assert client.ping() == '' except ConnectionError: error = True assert error == True server.stop()
def test_ssl_ping(): # Test that SSL works server = RESTServer(SSLKey='server.key', SSLCert='server.crt') server.start(block=False) client = RESTClient(CACert='server.crt') assert client.ping() == 'PONG' server.stop() # Test that bad crt rejected badServer = RESTServer(SSLKey='server2.key', SSLCert='server2.crt') badServer.start(block=False) error = False try: client.ping() == '' except SSLError: error = True assert error == True badServer.stop()
def insertResources(self): # read learning content from json with open('../content/cp.json') as f: res = yaml.safe_load(f.read()) # load ims cp template and merge content into cp loader = airspeed.CachingFileLoader(self.templates.get("path")) t = loader.load_template(self.templates.get("cp")) cp = t.merge(res, loader=loader) # validate ims cp (incl. ld, md) xmltools = XMLTools() scheme_path = "../xsd/IMS_master.xsd" xmltools.validateStreamAgainstScheme(cp, scheme_path) # get topic name for filename topic = res.get("learning_design").get("title").lower() # write cp file to local file with open('../xml/cp_'+topic+'.xml', 'w+') as f: f.write(cp) # write cp file to db REST = RESTClient() r = REST.post("cp", data={'topic': topic}, payload=cp) print r # build and write qti items to db for la in res['learning_activities']: # load qti template t = loader.load_template(self.templates.get(la['content']['interaction'])) qti = t.merge(la, loader=loader) # write qti files to local files fname = 'qti_' + la['id'] + '.xml' with open('../xml/' + fname, 'w+') as f: f.write(qti) # write qti files to db r = REST.post("item", data={'fname': fname}, payload=qti) print r
def main(): online = False rest_client = RESTClient(address="http://localhost", port=8000) colors_data = [] scores_data = [] if rest_client.check_connection(): colors_data = rest_client.get_color_schemes() scores_data = rest_client.get_high_scores() online = True if colors_data: for enum, element in enumerate(colors_data, 1): color_schemes[enum] = { "name": element["name"], "snake_color": (element["snake_R"], element["snake_G"], element["snake_B"]), "apple_color": (element["apple_R"], element["apple_G"], element["apple_B"]), "walls_color": (element["walls_R"], element["walls_G"], element["walls_B"]), "background_color": (element["background_R"], element["background_G"], element["background_B"]), } pg.init() pg.display.set_caption("PySnake") display_resolution = width, height = 800, 600 screen = pg.display.set_mode(display_resolution) clock = pg.time.Clock() fps = 15 block_size = 20 game = Game(display_resolution, screen, fps, clock, block_size, colors, color_schemes, online) menu = Menu(game) menu.main_menu()
def test_echo(): server = RESTServer(default_echoes=True) server.start(block=False) client = RESTClient() assert client.echo('meow meow') == 'meow meow' server.stop()
def test_ping(): server = RESTServer() server.start(block=False) client = RESTClient() assert client.ping() == 'PONG' server.stop()
def __init__(self): self.nova_client = NovaClient.get_instance() self.server = RESTClient.getInstance() self.vm_name = None self.failed_info = None self.recovery_type = ""
from RESTClient import RESTClient, Services from DbAccess import DbAccess # Get last/todays rates client = RESTClient(Services.TODAYS_RATES) data = client.call_service() db = DbAccess() # Get item item = data.find('nsp:Cube', client.namespaces) # Insert entry in DB today = item.__getitem__(0).attrib['time'] today_id = db.insert_entry(today) if today_id == -1: today_id = db.entry_get_id(today)[0] # Insert rates in DB for rate in item.find('nsp:Cube', client.namespaces): db.insert_exchangeRate( today_id, rate.attrib['currency'], rate.attrib['rate'] )
def game_over(self): game_over_font = pg.font.SysFont(None, 100) font = pg.font.SysFont(None, 64) prompt_font = pg.font.SysFont(None, 40) game_over_text = game_over_font.render("GAME OVER", 1, (255, 0, 0)) game_over_width = game_over_text.get_width() self.screen.fill(self.black) txt_box = None if self.online and self.score > 0: self.screen.fill(self.black) prompt_text = prompt_font.render("Enter your name...", 1, (255, 0, 0), self.black) prompt_width = prompt_text.get_width() name_saved = False txt_box = external.eztext.Input(x=self.display_resolution[0] / 2 - 250, y=370, maxlength=20, color=(255, 0, 0), prompt='') while not name_saved: self.screen.fill(self.black) pg.draw.rect(self.screen, (255, 0, 0), (100, 250, 600, 180), 2) pg.draw.rect(self.screen, (100, 100, 100), (130, 360, 530, 40)) self.screen.blit(game_over_text, (self.display_resolution[0] / 2 - game_over_width / 2, 100)) self.screen.blit( prompt_text, (self.display_resolution[0] / 2 - prompt_width / 2, self.display_resolution[1] / 2)) events = pg.event.get() for event in events: if event.type == pg.QUIT: sys.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_RETURN: rest_client = RESTClient("http://localhost", 8000) name = txt_box.value if name == "": name = "unknown_knight" rest_client.add_high_score(name, self.score) name_saved = True txt_box.update(events) txt_box.draw(self.screen) self.clock.tick(self.fps) pg.time.wait(0) pg.display.update() score_text = font.render("YOUR SCORE: " + str(self.score), 1, (255, 0, 0)) score_width = score_text.get_width() play_again_text = font.render("PLAY AGAIN?", 1, (255, 0, 0)) play_again_width = play_again_text.get_width() yes_no_text = font.render("YES NO", 1, (255, 0, 0)) play_again = True while True: self.screen.fill(self.black) if play_again: pg.draw.rect(self.screen, (255, 0, 0), (295, 445, 100, 50), 2) else: pg.draw.rect(self.screen, (255, 0, 0), (418, 445, 100, 50), 2) self.screen.blit( game_over_text, (self.display_resolution[0] / 2 - game_over_width / 2, 100)) self.screen.blit( score_text, (self.display_resolution[0] / 2 - score_width / 2, 200)) self.screen.blit( play_again_text, (self.display_resolution[0] / 2 - play_again_width / 2, self.display_resolution[1] - 250)) self.screen.blit(yes_no_text, (300, 450)) pg.display.update() self.clock.tick(self.fps) pg.time.wait(0) for event in pg.event.get(): if event.type == pg.QUIT: game_exit = True sys.exit() if event.type == pg.K_ESCAPE: pg.quit() game_exit = True sys.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_LEFT: play_again = True pg.display.update() if event.key == pg.K_RIGHT: play_again = False pg.display.update() if event.key == pg.K_RETURN: if play_again: self.game_loop() else: menu = Menu(self) menu.main_menu()
from RESTClient import RESTClient, Services from DbAccess import DbAccess # Get last/todays rates client = RESTClient(Services.TODAYS_RATES) data = client.call_service() db = DbAccess() # Get item item = data.find('nsp:Cube', client.namespaces) # Insert entry in DB today = item.__getitem__(0).attrib['time'] today_id = db.insert_entry(today) if today_id == -1: today_id = db.entry_get_id(today)[0] # Insert rates in DB for rate in item.find('nsp:Cube', client.namespaces): db.insert_exchangeRate(today_id, rate.attrib['currency'], rate.attrib['rate'])
class HAInstance(object): server = RESTClient.getInstance() ha_instance_list = None instance_list = None host = subprocess.check_output(['hostname']).strip() @staticmethod def init(): HAInstance.instance_list = [] HAInstance.ha_instance_list = {} @staticmethod def get_instance_from_controller(): try: cluster_list = HAInstance.server.list_cluster()["data"] print(cluster_list) for cluster in cluster_list: cluster_uuid = cluster["cluster_id"] HAInstance.ha_instance_list[ cluster_uuid] = HAInstance._get_ha_instance(cluster_uuid) host_instance = HAInstance._get_instance_by_node( HAInstance.ha_instance_list) for cluster_id, instance_list in host_instance.iteritems(): for instance in instance_list: HAInstance.add_instance(cluster_id, instance) except Exception as e: message = "HAInstance get_instance_from_controller Except:" + str( e) logging.error(message) print(message) @staticmethod def _get_ha_instance(cluster_id): instance_list = [] try: instance_list = HAInstance.server.list_instance( cluster_id)["data"]["instanceList"] except Exception as e: message = "_get_ha_instance--get instance list from controller(rpc server) fail" + str( e) # instance_list = [] logging.error(message) finally: return instance_list @staticmethod def _get_instance_by_node(instance_lists): for id, instance_list in instance_lists.iteritems(): for instance in instance_list[:]: if HAInstance.host not in instance["host"]: instance_list.remove(instance) return instance_lists @staticmethod def add_instance(cluster_id, instance): """ :param cluster_id: :param instance: """ print("add vm") vm = Instance(cluster_id=cluster_id, ha_instance=instance) HAInstance.instance_list.append(vm) @staticmethod def get_instance_list(): """ :return: """ return HAInstance.instance_list @staticmethod def get_instance(name): """ :param name: :return: """ for instance in HAInstance.instance_list: if instance.name == name: return instance return None @staticmethod def is_HA_instance(name): for instance in HAInstance.instance_list: if instance.name == name: return True return False @staticmethod def get_detection_list(): detection_list = [] try: cluster_list = HAInstance.server.list_cluster()["data"] for cluster in cluster_list: cluster_uuid = cluster["cluster_id"] detection_list = HAInstance.server.list_node( cluster_uuid)["data"]["nodeList"][1]["detection_list"] except Exception as e: message = "_get_ha_detection--get detection list from controller(rpc server) fail" + str( e) logging.error(message) finally: detection_list.sort() if detection_list == []: detection_list = ['5', '6', '7'] print(detection_list) return detection_list @staticmethod def update_ha_instance(): HAInstance.init() HAInstance.get_instance_from_controller() print("update HA Instance finish")
import json from flask import Flask, render_template from flask_ask import Ask, statement, question, session from RESTClient import RESTClient from FiniteStateMachine import FiniteStateMachine from SessionManager import SessionManager from LearningGraph import LearningGraph, Node from QTIValidator import QTIValidator from time import strftime, localtime import Helper app = Flask(__name__) ask = Ask(app, "/") logging.getLogger("flask_ask").setLevel(logging.DEBUG) REST = RESTClient() FSM = FiniteStateMachine() SM = SessionManager() VAL = QTIValidator() @ask.launch def onLaunch(): # init FSM on launch session.attributes['state'] = FSM.initFSM() # set state launch session.attributes['state'] = FSM.setState("launch") # check if logged in isLoggedIn, name = SM.checkLoggedIn() # if logged in if isLoggedIn:
def high_scores_menu(self): # Font definitions game_title_font = pg.font.SysFont(None, 100) score_font = pg.font.SysFont(None, 32) back_font = pg.font.SysFont(None, 64) # Rendering text with fonts (args: Text, Antyaliasing, Text Color) game_title_txt = game_title_font.render("PySnake", 1, (0, 255, 0)) back_txt = back_font.render("Back", 1, self.game.black) offline_text = score_font.render( "This option in unavailable in offline mode...", 1, self.game.black) no_scores_text = score_font.render("Nothing to show here...", 1, self.game.black) # Saving text width game_title_width = game_title_txt.get_width() back_width = back_txt.get_width() offline_width = offline_text.get_width() no_scores_width = no_scores_text.get_width() rest_client = RESTClient("http://localhost", 8000) if rest_client.check_connection() and self.game.online: scores = rest_client.get_high_scores() while True: self.game.screen.fill(self.game.white) self.game.screen.blit(game_title_txt, (self.game.display_resolution[0] / 2 - game_title_width / 2, 50)) if rest_client.check_connection() and self.game.online: if scores: position = 0 for enum, score in enumerate(scores, 1): position += 30 score_txt = score_font.render( '{0}. {1} - {2}'.format(enum, score["score"], score["name"]), 1, self.game.black) self.game.screen.blit(score_txt, (100, 150 + position)) elif not scores: self.game.screen.blit( no_scores_text, (self.game.display_resolution[0] / 2 - no_scores_width / 2, self.game.display_resolution[1] / 2)) self.game.screen.blit( back_txt, (self.game.display_resolution[0] / 2 - back_width / 2, self.game.display_resolution[1] - 100)) pg.draw.rect(self.game.screen, (255, 0, 0), (self.game.display_resolution[0] / 2 - back_width / 2 - 10, 490, 125, 60), 2) pg.display.update() else: self.game.screen.blit( offline_text, (self.game.display_resolution[0] / 2 - offline_width / 2, self.game.display_resolution[1] / 2)) self.game.screen.blit( back_txt, (self.game.display_resolution[0] / 2 - back_width / 2, self.game.display_resolution[1] - 100)) pg.draw.rect(self.game.screen, (255, 0, 0), (self.game.display_resolution[0] / 2 - back_width / 2 - 10, 490, 125, 60), 2) pg.display.update() for event in pg.event.get(): if event.type == pg.QUIT: sys.exit() if event.type == pg.K_ESCAPE: pg.quit() sys.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_RETURN: self.main_menu() self.game.clock.tick(self.game.fps) pg.time.wait(0)
from RESTClient import RESTClient, Services from DbAccess import DbAccess # Get last/todays rates client = RESTClient(Services.ALL_RATES) data = client.call_service() db = DbAccess() list = data.find('nsp:Cube', client.namespaces) # Insert entries in DB for entry in list: entry_date = entry.attrib['time'] entry_date_id = db.insert_entry(entry_date) if entry_date_id == -1: entry_date_id = db.entry_get_id(entry_date)[0] # Insert rates in DB for rate in entry: db.insert_exchangeRate(entry_date_id, rate.attrib['currency'], rate.attrib['rate'])