def killProcess(agent, user, password, pid): s = Session(agent, service="ProcessStop") s.authorize(user, password) response = s.doRequest(attributes={"PID" : str(pid)}) return int(ElementTree.fromstring(response).get("ExitCode"))
def command_start(bot, update): chat_id = update.message.chat_id if chat_id not in SESSIONS.keys(): messenger = Messenger(bot, logger) SESSIONS[chat_id] = Session(chat_id, config_instance, logger) SESSIONS[chat_id].set_messenger(messenger) SESSIONS[chat_id].quiz = Quiz(SESSIONS[chat_id])
def prepSimProfile(self): """ Prepare data and create User Sessions (to be simulated). each of them will wait for the start signal. """ # @todo: implement a mechanism to load and use other types of RAS (from ras_type.py) self.__ras_obj = MikrotikRas(self.__sim_profile.nas_id, self.__sim_profile.nas_ip, self.__sim_profile.radius_secret, self.__sim_profile.aaa_server_ip) # @todo: we better save and keep track of the used IP ips = [] for ip in IPy.IP( self.__sim_profile.user_ips ): if str(ip).endswith("0") or "255" in str(ip): continue ips.append( str(ip) ) for i in xrange( self.__sim_profile.total_sessions ): session_type = random.choice( self.__sim_profile.session_types ) self.__start_sessions[ session_type ] = 1 + self.__start_sessions.get(session_type, 0) username, password = self.__genUserPass(i) sess = Session(session_type, self.__ready_event, username, password, ips.pop(0), self.__ras_obj) sess.start() self.__sessions.append(sess)
def get(self): username = self.request.get("user") password = self.request.get("password") self.response.headers['Content-Type'] = 'application/json; charset=utf-8' if not username or not password: # some fields were missing in the request self.response.write(json_error('invalid', '')) else: # check if username exists in db query_user = User.query(User.username == username).fetch() if query_user: # check if password is correct query = User.query(ndb.AND(User.username == username, User.pswd == password)).fetch() if query: # generate 64 char session cookie and send it back cookie = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(64)) session = Session(cookie = cookie, user = username) session.put() self.response.write(login_response('ok', cookie)) else: # password was incorrect self.response.write(json_error('failure', 'password')) else: # user didn't exist self.response.write(json_error('failure', 'user'))
def get(self): if 'pairing' in self.request.arguments: key = self.get_argument('pairing') # validate pairing key if 'type' in self.request.arguments: if 'session' in self.request.arguments: session = Session.get(self.get_argument('session')) if session: if self.get_argument('type') == 'update': self.writeout( session.get_update() ) elif self.get_argument('type') == 'function': queries = self.get_argument('queries') qargs = json.loads(queries) args = [urllib.unquote(arg) for arg in qargs] decoded = [decode_func_args(a) for a in args] for fnargs in decoded: self.writeout( session.handle_function(fnargs) ) return else: self.writeout( { 'no':'huh' } ) # validate session #self.writeout( [ {'add': {'btapp':{'torrent':{'aotheu':{'hello':23}}}} } ] ) else: self.set_status(404) else: #logging.info('no session id in args -- %s, %s' % (self.request.uri, self.request.arguments)) session = Session.create(Client.instances[0]) self.writeout( {'session':session.id} ) else: self.writeout( { 'hey':'whatup' } ) else: self.set_status(403)
class AppDelegate(NSObject): def applicationDidFinishLaunching_(self, app): self.session = None self.init_status_bar() self.init_menu() def init_status_bar(self): self.status_bar = NSStatusBar.systemStatusBar() self.status_item = self.status_bar.statusItemWithLength_(NSVariableStatusItemLength) self.status_item.setHighlightMode_(1) icon = NSImage.alloc().initWithContentsOfFile_('icon.png') self.status_item.setImage_(icon) def init_menu(self): self.menu = NSMenu.alloc().init() self.menu_item_start = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Start', 'start:', '') self.menu.addItem_(self.menu_item_start) menu_item_quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menu.addItem_(menu_item_quit) self.status_item.setMenu_(self.menu) def start_(self, notification): if self.session != None: self.session.stop() self.session = Session() self.session.start()
def post(self): username = self.get_argument("username", "") password = self.get_argument("password", "") error_messages = list() if username == "" or password == "": error_messages.append("参数不能为空") self.render("login.html", error_messages=error_messages, username="") return user = self.db.get("SELECT * FROM accounts WHERE username = %s", username) if user is None: error_messages.append("用户名密码错误") self.render("login.html", error_messages=error_messages, username=username) return if user["status"] == 0: error_messages.append("帐户没有开通") self.render("login.html", error_messages=error_messages, username=username) return password_generator = UserPassword() password_hash = password_generator.generate_hash(password, user["password_salt"]) if password_hash != user["password_hash"]: error_messages.append("用户名密码错误") self.render("login.html", error_messages=error_messages, username=username) return session = Session(self.settings["session_secretSid"], self.settings["session_secretEid"], self.settings["session_expired"]) if session.encode(user["id"]) is False: error_messages.append("用户数据错误") self.render("login.html", error_messages=error_messages, username=username) return sid = session.getSid() eid = session.getEid() self.set_secure_cookie("sid", sid, None) self.set_secure_cookie("eid", eid, None) self.redirect(self.get_argument("next", "/"))
def get_responses(self, id_=1): session = Session() bbs = session.query(BBS).filter(BBS.id == id_).one() responses = [ res.toDict() for res in bbs.responses] responses.reverse() return responses
def login(self, password): if self.password == password: current_session = Session(player_id=self.player_id) current_session.start_session() self.sessions.append(current_session) print("Player {} has logged in".format(self.name)) else: print("Password error. Try again.")
def __call__(self, environ, start_response): sc = SimpleCookie() if 'HTTP_COOKIE' in environ: sc.load(environ.get('HTTP_COOKIE')) ses = Session(ExpressSession(sc)) ses.read() environ['express.session'] = ses return self.app(environ, start_response)
def on_finish(self): try: self.session.commit() except Exception as e: self.session.rollback() import traceback logging.critical('Transaction needed to be rolled back because of: \n %s' % traceback.format_exc() ) Session.remove()
def main(): from pprint import pprint from sys import argv s = Session() s.login(argv[1], argv[2]) f = Forum(s) pprint(f.get_hot()) pprint(f.get_thread(argv[3]))
def retrieve_data_point_count(session: Session) -> int: while True: data_point_count = get_integer_from_user(session, 'How many data points do you want to create: ') if data_point_count <= 0: session.get_io().output('Your input must be greater than zero, instead got {}'.format(str(data_point_count))) time.sleep(1) session.clear() continue return data_point_count
def query(self, query_type, msg_body=None): session = Session(self.peer.connect_str, service="Manager") session.authorize(self.peer.domain.user, self.peer.domain.password) pwd_response = session.doRequest(attributes={"Type": "GetDatabaseCredentials", "Database": self.database.name}) pwd_xml = ElementTree.fromstring(pwd_response) pwd = pwd_xml.find("Password").text.strip() return queryEngine(self.address, self.port, query_type, pwd, msg_body)
class SocketHandler(tornado.websocket.WebSocketHandler): def open(self): logging.info("Connected: websocket") self.device = 'web' self.session = Session(self, world) self.session.start() def on_message(self, message): dispatch(self.session, message.strip())
def get_data_points_per_line(session: Session) -> int: while True: data_points_per_line = get_integer_from_user(session, 'How many data points per line should be outputted: ') if data_points_per_line <= 0: session.get_io().output('Your input must be greater than zero, instead got {}'.format(str(data_points_per_line))) time.sleep(1) session.clear() continue return data_points_per_line
def query(self, type, msgBody=None): s = Session(self.getPeer().getConnectStr(), service="Manager") s.authorize(self.getPeer().getDomain().getUser(), self.getPeer().getDomain().getPassword()) pwdResponse = s.doRequest(attributes={"Type": "GetDatabaseCredentials", "Database": self.getDbName()}) pwdXml = ElementTree.fromstring(pwdResponse) pwd = pwdXml.find("Password").text.strip() return queryEngine(self.getAddress(), self.getPort(), type, pwd, msgBody)
def execute(self, session: Session, args: Dict[str, Any]) -> ExitCode: data_to_remove = get_data_to_remove(session) data = args['data'] args['data'] = deque(filterfalse(lambda x: x == data_to_remove, data)) session.get_io().output('Removed {} data points'.format(len(data) - len(args['data']))) return ExitCode.SUCCESS
def __init__(self, host, port, service='SQL2'): """Constructor for the EncodedSession class.""" Session.__init__(self, host, port=port, service=service) self.doConnect() self.__output = None self.__input = None self.__inpos = 0 self.closed = False
def __init__(self, capabilities): Session.__init__(self, capabilities) self._host_keys = paramiko.HostKeys() self._transport = None self._connected = False self._channel = None self._buffer = StringIO() # for incoming data # parsing-related, see _parse() self._parsing_state = 0 self._parsing_pos = 0
def start_hangout(url, robot_sid): """Start google hangout in a selenium chromebrowser instance.""" # # TODO if we have no network at this point, we fail, then never get a # control port and can't close the selenium hangout # hangout = HangoutSession() robot_session = RobotSession(robot_sid) robot_session.set('hangout_control_port', hangout.driver.service.port) hangout.join_hangout(url)
def execute(self, session: Session, args: Dict[str, Any]) -> ExitCode: data_to_remove = get_data_to_remove(session) try: args['data'].remove(data_to_remove) session.get_io().output('Removed the first instance of data point "{}"'.format(data_to_remove)) except ValueError: session.get_io().error('Data point "{}" is not present in the data store!'.format(data_to_remove)) return ExitCode.SUCCESS
class TestSession(unittest.TestCase): def setUp(self): self.session=Session() def test_correct_authentication(self): username='******' password='******' self.session.newSession(username, password) self.assertTrue(self.session.check()) def test_wrong_authentication(self): username='******' password='******' self.session.newSession(username, password) self.assertFalse(self.session.check()) username='******' password='******' self.session.newSession(username, password) self.assertFalse(self.session.check()) def test_password_visibility(self): try: print self.session._password self.fail() except: pass
class BaseHandler(tornado.web.RequestHandler): def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.session = Session(self) # autosave session to server when request finish def on_finish(self): self.session.save() def get_current_user(self): return self.session.get("user", None)
def getSocketHandler(self, socket): session = Session() connection = Connection(socket) session.setDebugger(self) session.setConnection(connection) connection.setSession(session) connection.setSocketManager(self.__socketmanager) self.__sessions.append(session) return connection
def stopProcess(address, port, dbPassword): s = Session(address, port=port, service="Monitor") s.authorize("Cloud", dbPassword) s.doConnect() s.send("<Request Action=\"shutdown\"/>") s.close()
class Gui(Tk): def openfolder(self): folderloc= filedialog.askdirectory() self.session = Session(folderloc) self.session.update() self.drawmap() def __init__(self): Tk.__init__(self) resolution = [1600, 900] z_level = 0 self.configure(background="green") #menu bar menubar = Menu(self) self["menu"] = menubar filemenu = Menu(menubar) optionmenu = Menu(menubar) menubar.add_cascade(label="File", menu=filemenu) menubar.add_cascade(label="Options", menu=optionmenu) filemenu.add_command(label="Open", command=self.openfolder) optionmenu.add_command(label="Nothing") #main canvas self.maincan = Canvas(master=self) self.maincan.titlecardpil = PIL.Image.open("titlecard.png") #self.maincan.testimg2 = PIL.Image.open("testimg2.png") #self.maincan.titlecardpil.paste(self.maincan.testimg2, (50,40), self.maincan.testimg2) self.maincan.titlecard = ImageTk.PhotoImage(self.maincan.titlecardpil) self.maincan.config(width = resolution[0]-5, height = resolution[1]-10, background = "green") title = self.maincan.create_image(0,0,image=self.maincan.titlecard, anchor="nw") self.maincan.grid(row="0") def drawmap(self): map_arr = self.session.map_arr print("Map loaded into gui") x_dim = len(map_arr[0][0]) y_dim = len(map_arr[0]) z_dim = len(map_arr) print(x_dim, y_dim, z_dim) print(z_level)
def db_session(): session = None try: session = create_session() yield session session.commit() except: if session: session.rollback() logger.exception('error occurs') finally: Session.remove()
def handle(self): db = self.__db cursor = self.__cursor form = cgi.FieldStorage(keep_blank_values="True") uHandler = UserHandler(db, cursor) #print "Content-type:text/html" # TEMPORARY, REMOVE AFTER DEBUGGING TO HAVE SCRIPT REDIRECT PROPERLY!!!!!! #print # DITTO #print `form` if form.has_key("username"): # store the user ID for use throughout the session; add to other views in addition to create in PHP currUname = form.getvalue("username") currUser = uHandler.getUserByDescription(currUname) Session.setUser(currUser) elif form.has_key("curr_user_id"): currUID = form.getvalue("curr_user_id") currUser = uHandler.getUserByID(currUID) Session.setUser(currUser) if form.has_key("create_project"): self.createProject(form) elif form.has_key("modify_project"): self.modifyProject(form) elif form.has_key("save_project"): self.saveProject(form) elif form.has_key("cancel_project"): self.cancelModification(form) elif form.has_key("delete_project"): self.deleteProject(form) elif form.has_key("view_project"): self.printProjectInfo(form) elif form.has_key("view_packet"): # go to project view from User detailed view self.viewPacket(form) # Oct. 12, 2010 elif form.has_key("search_project_by_keyword"): self.findPacket(form) cursor.close() db.close()
def monitorEngine(address, port, dbPassword, listener=None): if not listener: listener = _StandardOutListener() s = Session(address, port=port, service="Monitor") s.authorize("Cloud", dbPassword) monitor = SessionMonitor(s, listener=listener) monitor.start() s.doConnect() return EngineMonitor(monitor, s)
def ed_unit_test(): data = Session('../dataset_prepared_2014_09_18_ALMTransientInhibition/ANM257772_20141121.mat') ## Basic checks data.n_units == data.units.shape[0] data.n_trials == data.units.shape[1] len(data.stim_on_time) == data.n_trials ## Changing values in a deepcopy should not affect the original data2 = data.deepcopy() data2.task_pole_off_time[0] = 10000 assert data.task_pole_off_time[0] != 10000 ## Aligning time should change the flag data.time_aligned assert data.time_aligned == False data.align_time() assert data.time_aligned == True ## Selecting units should result in filtering the correct units data3 = data.deepcopy() data3.select_units([3]) assert data3.n_units == 1 assert data3.units.shape[0] == 1 for (a,b) in zip(data.units[3], data3.units[0]): assert np.array_equal(a,b) print('All tests passed.')
def loop(self): self.session = Session(self.send_string, self.remote[0]) dbg("Setting timeout to " + str(self.timeout) + " seconds") self.sock.settimeout(self.timeout) try: self.test_opt(1) # Kill of Session if longer than self.maxtime ts_start = int(time.time()) self.send_string("Login: "******"Password: "******"\r\nWelcome to EmbyLinux 3.13.0-24-generic\r\n") self.session.login(u, p) while True: l = self.recv_line() try: self.session.shell(l) except: traceback.print_exc() self.send_string("sh: error\r\n") if ts_start + self.maxtime < int(time.time()): dbg("Session too long. Killing off.") break except socket.timeout: dbg("Connection timed out") except EOFError: dbg("Connection closed") self.session.end()
def main(): """ Main function to put the pieces together and run the recipe """ # NOTE: not allow GDAL to create auxilary file which causes problem when no permission on the input data folder command = "export GDAL_PAM_ENABLED=NO" os.system(command) reg = RecipeRegistry() validate() # Parse input arguments from command line arguments = parse_arguments() ingredients_file_path = arguments.ingredients_file ConfigManager.user = arguments.user ConfigManager.passwd = arguments.passwd if arguments.identity_file is not None: key_value = FileUtil.read_file_to_string(arguments.identity_file) if ":" not in key_value: raise RuntimeException( "credentials in the identity file '" + arguments.identity_file + "' " "must be specified in the file as username:password") tmps = key_value.split(":") ConfigManager.user = tmps[0].strip() ConfigManager.passwd = tmps[1].strip() try: ingredients = decode_ingredients( read_ingredients(ingredients_file_path)) hooks = ingredients["hooks"] if "hooks" in ingredients else None session = Session(ingredients['config'], ingredients['input'], ingredients['recipe'], hooks, os.path.basename(ingredients_file_path), FileUtil.get_directory_path(ingredients_file_path)) reg.run_recipe(session) except RecipeValidationException as re: log.error(str(re)) exit_error() except RuntimeException as re: log.error(str(re)) exit_error() except WCSTException as re: log.error(str(re)) exit_error() except Exception as ex: log.error( "An error has occured in the execution of the program. Error Message: " + str(ex) + "\nStack Trace: " + traceback.format_exc()) exit_error()
def _msg_group_send_handler(self, session: Session, request): group_entity: GroupEntity = self.group_repository.find_by_code(request['code']) if session.user.username in group_entity.members: pass else: session.send_response({ 'FOR': 'MSG-GROUP-SEND', 'status': 'failed', 'message': 'You are not a member of the group!' }) return members = group_entity.members for member in members: if member == session.user.username: continue member_session: Session = SessionManager.get_by_username(member) if member_session is not None: member_session.send_response({ 'FOR': 'NOTIF', 'from_group': group_entity.group_name, 'from_user': session.user.username, 'text': request['message'] }) print('send to '+member_session.user.username) group_entity.inbox.append({ 'from_user': session.user.username, 'text': request['message'] }) session.send_response({ 'FOR': 'MSG-GROUP-SEND', 'status': 'success' }) self.group_repository.save(group_entity)
def test_update_word_display(self): """Check that the word display successfully updates in response to guesses. """ session = Session() session.current_word = 'TACONY' session.guesses.append('E') session.letters_guessed.append('E') session.guesses.append('S') session.letters_guessed.append('S') session.update_word_display() assert session.word_display == ['_', '_', '_', '_', '_', '_'] session.guesses.append('T') session.letters_guessed.append('T') session.guesses.append('A') session.letters_guessed.append('A') session.update_word_display() assert session.word_display == ['T', 'A', '_', '_', '_', '_'] session.guesses.append('TACONY') session.word_guessed = 'TACONY' session.update_word_display() assert session.word_display == ['T', 'A', 'C', 'O', 'N', 'Y']
def test_high_card(): sesh = Session(LOGGER, player_count=2) players = ['player1', 'player2'] for i, player in enumerate(players): sesh.players[i].name = player sesh.setup_game() sesh.players[0].hand[0] = Card('H', 12) sesh.players[0].hand[1] = Card('S', 14) sesh.players[1].hand[0] = Card('C', 2) sesh.players[1].hand[1] = Card('D', 6) sesh.community_cards[0] = Card('D', 10) sesh.community_cards[1] = Card('S', 9) sesh.community_cards[2] = Card('C', 5) sesh.community_cards[3] = Card('D', 3) sesh.community_cards[4] = Card('C', 13) res = sesh.get_best_hands() assert res[sesh.players[0]][0] == HandVal.HIGH_CARD assert res[sesh.players[0]][1] == [14, 13, 12, 10, 9] assert res[sesh.players[1]][0] == HandVal.HIGH_CARD assert res[sesh.players[1]][1] == [13, 10, 9, 6, 5]
def __init__(self, webini='../../WEB-INF', sessionlifetime=180, usecgi=True): """ Konstruktor: @param webini Pfad auf WEB-INI Verzeichnis @param sessionlifetime Minuten welche die Session gueltig ist @param usecgi True: es wird die cgi Classe fuer das Interfacehandling benutzt False: es wurd nur der QUERY_STRING geparst Das Standardverhalten ist usecgi=True. """ self.usecgi = usecgi self.config = Config() # lese path aus CGI self.query_string = os.environ['QUERY_STRING'] self.path = self.getPathFromQueryString() # Konfiguration self.homeurl = self.config.homeurl self.webini = webini self.menu = Menu(self.config) self.configMenu() self.sidebox = Sidebox(config=self.config) self.session = Session(self.config.sessionpath, sessionlifetime=sessionlifetime) self.mframeversion = Version().VERSION self.version = '0.1-E001' self.connectDb() self.authen = Authen(session=self.session, db=self.db) self.menu.authen = self.authen self.tplateengine = TemplateEngine(self.config) self.writelog("-- usecgi: {0}".format(usecgi)) if usecgi: self.form = cgi.FieldStorage(keep_blank_values=1) self.path = self.cgiparam(name='path', nvl='/')
def crash_to_session(self): with open("crash.json", "r") as crash: data = crash.readlines()[0] data = json.loads(data) task = data["task"] task_time = data["task_time"] time_started = data["time_started"] date_started = data["date_started"] session = Session(task=task, task_time=task_time, time_started=time_started, date_started=date_started) return session
def index(): if not os.path.exists(os.path.join('git', 'sessionsTest', 'sessions.json')): abort(404) jsonl = None with codecs.open(os.path.join('git', 'sessionsTest', 'sessions.json'), 'r', 'utf-8') as f: jsonl = json.load(f) sessions = [ Session(title=x['title'], author=x['author']) for x in jsonl['sessions'] ] return render_template('index.html', sessions=sessions)
def test_over_scheduling_volunteer(self): vol = Volunteer(volunteer_id='v001') # create 5 sessions on the same day, each session with a different student group sessions = [] for i in range(1, 6): group = StudentGroup('A' + str(i)) sess = Session(week='week2', day='thursday', session_id='s00' + str(i)) sess.assign_student_group(group) sessions.append(sess) # schedule the volunteer for all sessions for session in sessions: session.schedule_volunteer(vol) self.assertEqual(len(vol.get_schedule()['thursday']['week2']), 4, "only four of the five sessions are scheduled")
def createSession(self, clientsock, username): """ Creates a new session and appends it to the sessions list. @type socket: socket @param socket: The socket for the current client @rtype: Session @return: The newly created Session """ user = rbacManager.getInstance().getUserFromLogin(username) session = Session(self.nextSessionId, clientsock, float(time.time()), user) self.sessions.append(session) self.nextSessionId = self.nextSessionId + 1 return session
def handleLoginRequest(self, user, legacyName, password, extra): self.logger.debug("handleLoginRequest(user=%s, legacyName=%s)" % (user, legacyName)) # Key word means we should register a new password if password == 'register': if user not in self.sessions: self.sessions[user] = RegisterSession(self, user, legacyName, extra) else: if user not in self.sessions: self.sessions[user] = Session(self, user, legacyName, extra) self.sessions[user].login(password)
def run(): parser = parse_args() d = Movielens(parser.data_path, parser.threshold) train_dl, test_dl = get_Dataloader(d.train_set, d.test_set, parser.batch_size, parser.cores) model = FactorMachine(d.sparse_n_features, d.dense_n_features, parser.n_classes, parser.n_factors, parser.batch_size, parser.decay) model = model.cuda() optimizer = optim.Adam(model.parameters(), lr=parser.lr) sess = Session(model, d.max_user_id, d.max_item_id) for epoch in range(parser.num_epoch): loss, cross_loss, l2_loss = sess.train(train_dl, optimizer) print("epoch: {:d}, loss = [{:.6f} == {:.6f} + {:.6f}]".format( epoch, loss, cross_loss, l2_loss)) loss, cross_loss, l2_loss, auc = sess.test(test_dl) print("loss = [{:.6f} == {:.6f} + {:.6f}], auc = [{:.6f}]".format( loss, cross_loss, l2_loss, auc)) print('\n')
def test_ace_low_straight(): sesh = Session(LOGGER, player_count=2) players = ['player1', 'player2'] for i, player in enumerate(players): sesh.players[i].name = player sesh.setup_game() sesh.players[0].hand[0] = Card('S', 14) sesh.players[0].hand[1] = Card('C', 2) sesh.players[1].hand[0] = Card('D', 10) sesh.players[1].hand[1] = Card('D', 8) sesh.community_cards[0] = Card('S', 3) sesh.community_cards[1] = Card('D', 4) sesh.community_cards[2] = Card('C', 5) sesh.community_cards[3] = Card('D', 9) sesh.community_cards[4] = Card('C', 10) res = sesh.get_best_hands() assert res[sesh.players[0]][0] == HandVal.STRAIGHT for i in reversed(range(2, 6)): assert res[sesh.players[0]][1][5 - i] == i assert res[sesh.players[0]][1][-1] == 1 #ace assert res[sesh.players[1]][0] == HandVal.PAIR assert res[sesh.players[1]][1] == [10, 10, 9, 8, 5]
def __init__(self, master=None): super().__init__(master) self.master = master self.master.configure(background="#121212") self.session = Session() self.pack() self.fonts() self.tvars() self.bg_color = "#121212" self.fg_color = "#ffffff" self.down_color = "#ef5350" self.up_color = "#26a69a" self.active_color = "#444444" self.configure(bg=self.bg_color) self.construct_widget() self.playback_running = False self.current_position = None self.order_type = None self.order_side = None self.done_positions = []
def __init__(self, screen, bypass = False): """ displays the main menu and ensures that the user is logged in before proceeding. If bypass==True the menu creates a dummy session, used for testing.""" console_msg('Main menu', 0) self.screen = screen # this flag prevents certain key actions from automatically repeating # it is cleared when any key is released self.repeat_lock = False self._quit = False self._return_to_game = False self.clock = pygame.time.Clock() self.title_y_pos = 100 self.title_size = 28 self.items_y_pos = 370 self.title = "Main Menu" self.items = ["Play", "Options", "Quit:"] self.selected_item = -1 # start off with nothing selected self.session = None if bypass: self.session = Session("dummy_user", "dummy_class") self._return_to_game = True else: # load the fonts if pygame.font.get_init() is False: pygame.font.init() console_msg("Font system initialised", 2) # we explicitly load all required fonts # so that the TTF files can be bundled to run on other PCs self.menu_title_font = pygame.font.Font(MENU_FONT_FILE, 48) self.menu_title_bg_font = pygame.font.Font(MENU_FONT_FILE, 50) self.menu_font = pygame.font.Font(MENU_FONT_FILE, 32) self.menu_input_font = pygame.font.Font(CODE_FONT_FILE, 32) console_msg("Menu font loaded", 3) self.input_dialog = MenuInputDialog(self.screen, "Input", self.menu_input_font)
def __describe_coverage(self): """ Send a DescribeCoverage request to petascope """ try: service_call = self.wcs_service + "?service=WCS&request=DescribeCoverage&version=" + \ Session.get_WCS_VERSION_SUPPORTED() + "&coverageId=" + self.coverage_id response = validate_and_read_url(service_call) return response except Exception as ex: raise RuntimeException("Could not retrieve the axis labels. " "Detail error: {}".format(str(ex)))
def train(self, learning_rate, step_num, init_step=None, restoring_file=None): print('%s: training...' % datetime.now()) sys.stdout.flush() session = Session(self._graph, self.models_dir) init_step = session.init(self._network, init_step, restoring_file) session.start() last_step = init_step+step_num print('%s: training till: %d steps' %(datetime.now(), last_step)) print_loss = 0 train_loss = None save_loss = 0 save_step = 0 feed_dict={self._lr_placeholder: learning_rate} for step in range(init_step+1, last_step+1): start_time = time.time() _, loss_batch = session.run([self._train, self._loss], feed_dict=feed_dict) duration = time.time() - start_time assert not np.isnan(loss_batch), 'Model diverged with loss = NaN' print_loss += loss_batch save_loss += loss_batch save_step += 1 if ((step - init_step) % Trainer.PRINT_FREQUENCY == 0): examples_per_sec = Trainer.BATCH_SIZE / duration format_str = ('%s: step %d, loss = %.2f, lr = %f, ' '(%.1f examples/sec; %.3f sec/batch)') print_loss /= Trainer.PRINT_FREQUENCY print(format_str % (datetime.now(), step, print_loss, learning_rate, examples_per_sec, float(duration))) print_loss = 0 # Save the model checkpoint and summaries periodically. if (step == last_step or (Trainer.SAVE_FREQUENCY is not None and (step - init_step) % Trainer.SAVE_FREQUENCY == 0)): session.save(step) train_loss = save_loss / save_step print('%s: train_loss = %.3f' % (datetime.now(), train_loss)) save_loss = 0 save_step = 0 if (self.writer): summary_str = session.run(self._all_summaries, feed_dict=feed_dict) self.writer.write_summaries(summary_str, step) self.writer.write_scalars({'losses/training/total_loss': train_loss}, step) session.stop() return step, train_loss
def readLogs(filename, INACT_TIME, outputFile): ''' (str, timestamp, str) -> None Process input files and stream them based on time and order of the entries. ''' # format for datetime object FORMAT = '%Y-%m-%d %H:%M:%S' # time dict and queue sessionDict = OrderedDict() # Read EDGAR Log with open(filename, 'r') as txt: for idx, line in enumerate(txt): # Skip Header if (idx == 0): continue # Get needed information data = line.split(',') ip, date, time = data[:3] # Format Date and Time Columns try: accessTime = datetime.strptime(date + ' ' + time, FORMAT) except: print("date or time is not in the correct format.") continue # write to output if passed inactivity period removed_list = [] for temp_ip, session in sessionDict.items(): if session.isExpired(accessTime): writeOutput(outputFile, str(session)) removed_list.append(temp_ip) for item in removed_list: sessionDict.pop(item) # Put Record in sessionDict if ip not in sessionDict: sessionDict[ip] = Session(ip, accessTime, INACT_TIME) else: sessionDict[ip].updateEndTime(accessTime) # Assume all records as ex writeAll(outputFile, sessionDict)
def connect(self, session_id=None): """if the session_id is not given, a new session is to be created, otherwise return an existing session. """ if session_id == None or not session_id in self._sessions: i = 1 while i in self._sessions.keys(): i += 1 ses = Session(i) self._sessions[i] = ses else: ses = self._sessions[session_id] print self._sessions return ses
def __init__(self, url, username='******', password='******', resume=False, BasicAuth=False): print "in rest.py url {}".format(url) self.result = {} self.headers = {'User-Agent': 'JasperServer-Python'} self._url = url self._rest_url = url + '/rest' self.session = Session() self.content = None if BasicAuth: self.headers.update({ "Authorization": "Basic " + base64.b64encode( (username + ":" + str(password)).encode('ascii')) }) if not resume: self._login(username, password) self.rs = None self.rps = None
def start_new_session(self, name): if self._session: self.close_session() self._is_temporary = True self._session_name = name self._date = strftime("%d_%m_%Y") if self._date not in os.listdir(self._sessions_folder): self._session_id = 1 self._session = Session(self._date, self._session_id, self._session_name) self._session_folder = self._sessions_folder + self._session.path os.mkdir(self._sessions_folder + self._date) os.mkdir(self._session_folder) else: self._session_id = len( os.listdir(self._sessions_folder + self._date)) + 1 self._session = Session(self._date, self._session_id, self._session_name) self._session_folder = self._sessions_folder + self._session.path os.mkdir(self._session_folder) self._initiate_reporters()
def test_expression_grad(self): graph = Graph() a = graph.tensor() b = graph.tensor() c = a + b d = b + 1 e = c * d de_da, de_db = graph.gradients(e, [a, b]) sess = Session(graph) a_, b_, c_, d_, e_, de_da_, de_db_ = sess.run([a, b, c, d, e, de_da, de_db], feed_dict={a: 2, b: 1}) self.assertEqual(a_, 2) self.assertEqual(b_, 1) self.assertEqual(c_, 3) self.assertEqual(d_, 2) self.assertEqual(e_, 6) self.assertEqual(de_da_, 2) self.assertEqual(de_db_, 5)
def create_pokemon_move(name_or_id): query_type = "move" json_data = Session.query_info(query_type, name_or_id) name = json_data['name'] id = json_data['id'] generation = json_data['generation']['name'] accuracy = json_data['accuracy'] pp = json_data['pp'] power = json_data['power'] move_type = json_data['type']['name'] damage_class = json_data['damage_class']['name'] short_effect = json_data['effect_entries'][0]['short_effect'] return PokemonMove(name, id, generation, accuracy, pp, power, move_type, damage_class, short_effect)
def return_user_playlist(user_id): with Session() as sess: user_data = sess.query(models.User).filter_by(id=user_id).first() if user_data is None: abort(404) try: response = jsonify([ create_playlist_response(user_data.playlists[i]) for i in range(len(user_data.playlists)) ]) response.status_code = 200 return response except IndexError: abort(404)
def return_user(): j = { "users": [], } with Session() as sess: users = sess.query(models.User).all() for user in users: user_data = { "id": user.id, "name": user.name, "exchange": user.exchange.exchange_id } j["users"].append(user_data) return jsonify(j)
def create_and_fill_sessions(self): session_list = [] morning_session = Session(SessionType.Morning, MORNING_START_TIME, MORNING_SESSION_DURATION) self.fill_session(morning_session) session_list.append(morning_session) lunch_session = Session(SessionType.Lunch, LUNCH_START_TIME, LUNCH_SESSION_DURATION) lunch_session.add_slot('Lunch', LUNCH_SLOT_DURATION) session_list.append(lunch_session) noon_session = Session(SessionType.Noon, NOON_START_TIME, NOON_SESSION_DURATION) self.fill_session(noon_session) session_list.append(noon_session) networking_start_time = noon_session.next_slot_time validate_network_start_time(networking_start_time) networking_session = Session(SessionType.Networking, [ networking_start_time.hour, networking_start_time.minute, networking_start_time.second ], NETWORKING_SESSION_DURATION) networking_session.add_slot('Networking', NETWORKING_SLOT_DURATION) session_list.append(networking_session) return session_list
def __init__(self, route, request=None): self.session = Session() self.route = route if not request: if route.is_flask(): assert has_flask request = flask_request elif route.is_appengine(): request = route.request else: raise ValueError(u'HttpRequest-object is missing') self.request = request
def chat(): sessao = Session() if request.method == 'POST': msg = str(request.form['msg']) user = sessao.get_logged_user() sessao.sendmensagem(msg, user) return redirect(url_for('.index')) if request.method == 'GET': return jsonify(list(map(lambda x: x.to_json(), sessao.getmensagem())))
def display_npatchs(n, col): res = Session().first(n, col) npatchs = Session().get_patchs_number()[0] fig, ax = plt.subplots(1) minx = 9999999999999 miny = 9999999999999 for id in range(1, npatchs): mx = Session().get_patch_min(id)['x'] my = Session().get_patch_min(id)['y'] if mx < minx: minx = mx if my < miny: miny = my width_max = 0 height_max = 0 for id in range(1, npatchs): # build points mi = Session().get_patch_min(id) ma = Session().get_patch_max(id) # build rectangle x = mi['x'] - minx y = mi['y'] - miny width = ma['x'] - mi['x'] height = ma['y'] - mi['y'] cl = 'white' if id in res: cl = 'red' r = patches.Rectangle((x, y), width, height, ec='black', lw=1, fill='true', color=cl) ax.add_patch(r) if (width + x) > width_max: width_max = width + x if (height + y) > height_max: height_max = height + y ax.set_xlim(0, ceil(width_max)) ax.set_ylim(0, ceil(height_max)) plt.title('PC Patch') plt.xlabel('x') plt.ylabel('y') plt.savefig("{0}_{1}.png".format(col, n))