def test_SaveSessionFile(self): options = AnObject() options.server = self.host options.username = self.user options.password = self.password options.savesessionfile = self.sessionFile sessionOptions = SessionOptions(options) session = Session(sessionOptions) session.Login() stub = session.stub session.Logout() # Make sure session file exists and readable by user only if sys.platform == "win32": # Windows os.stat().st_mode always returns og rw # TODO: Use some other way to test pass else: st = os.stat(options.savesessionfile) if (st.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) != 0: raise Exception("Session file is world readable!!!") # Should remain authenticated after logout self.AuthenticatedAction(stub) # Close this session del session # Test session file is usable options = AnObject() options.sessionfile = self.sessionFile self.LoginLogout(options, skipLogoutTest=True)
def testSessionEncode(self): transaction = Transaction() session = Session(transaction, 'test') self.assertEqual(session.sessionEncode('myurl'), 'myurl?_SID_=test') self.assertEqual( session.sessionEncode('http://localhost/Webware/Servlet?a=1&b=2'), 'http://localhost/Webware/Servlet?a=1&b=2&_SID_=test')
def __init__(self, credentials): self.credentials = credentials self.queue = RequestQueue(request_limit=600) self.session = Session(self.credentials, self.queue) self.all_endpoints = { 'ticket': { 'plural': 'tickets', 'singular': 'ticket' }, 'organization': { 'plural': 'organizations', 'singular': 'organization' }, 'requester': { 'plural': 'users', 'singular': 'user' }, 'user': { 'plural': 'users', 'singular': 'user' }, 'assignee': { 'plural': 'users', 'singular': 'user' } } self.object_cache = BasicCache() self.tickets = Endpoint('ticket', self) self.organizations = Endpoint('organization', self) self.users = Endpoint('user', self)
def start_session(self): if self.active_session == None: self.active_session = Session(self) self.active_session.start() self.sessions.append(self.active_session) else: print("This subject already runs a time")
def get_timetable(school, user, password): # App4 Timetable Url with school identifier url = "http://{}.app4.ws/portal/timetable.php".format(school) # Creates a browser. Then opens the Timetable Url which leads to a login page br = mechanicalsoup.StatefulBrowser() br.open(url) # Log in using user and password br.select_form(nr=0) br["txtLoginUserID"] = user br["txtLoginPassword"] = password br.submit_selected() # With Permission reopens the Timetable page br.open(url) # Makes a soup of the pages html page = br.get_current_page() # Gets everyday's html daysRaw = page.find_all('td', {"width": '18%'}) # Empty Container to be populated with day objects timetable = [] for day in daysRaw: # Variables with Day args day_name = day.find_all("td", {"class": re.compile("^ttdark")})[0].string.extract() day_id = daysRaw.index(day)+1 # Appends a Day Object and Passes an empty list to be populated bt Session Objects, day_name and day_id timetable.append(Day([], day_name, day_id)) # List with all day's sessions html sessions = day.find_all("td", {"class": re.compile("^tt")}) # Iterates through all sessions appending a Session object to each Day object for session in sessions: # If session is a session continue if len(session.find_all("td")) > 0: # Variables with Session args session_number = int(session.find_all("td")[0].string.extract()) session_code = session.find_all("td")[1].find_all("span")[0].string.extract() # List of teacher, room and time session_periph = session.find_all("td")[1].find_all("span")[1].get_text("|").split("|") # Appends a Session Object to current day (i.e, days[-1]) # Checks if it is not an empty session (e.g, Lunch, Community Service) if len(session_periph) > 2: timetable[-1].append( Session( session_number, session_code, session_periph[0], str(session_periph[1]).strip(), session_periph[2] ) ) # If it is an empty session do not pass a teacher or room else: timetable[-1].append( Session( session_number, session_code, session_periph[0], None, None ) ) return timetable
def run(self): world = World(self.sizeOfWorldGrid, self.sizeOfWorldGrid) robby = Robby() curGeneration = None random.seed() for _iGen in range(self.noOfGenerations): curGeneration = self.createNextGeneration(curGeneration) for iChrom in range(curGeneration.getSize()): curChromosome = curGeneration.getChromosomeAt(iChrom) for iSession in range(self.noOfSessionsPerChromosome): session = Session(curGeneration.getNo(), curChromosome, iSession, world, robby, self.noOfSessionsPerChromosome, self.noOfActionsPerSession) session.run(self.updateListener) curChromosome.updateAvgFitness(session) self.updateListener.updateChromosome(curChromosome) curGeneration.updateMaxAvgFitness( curChromosome.getAvgFitness()) self.updateListener.updateGeneration(curGeneration)
def create_bike(x, y, bias=None, kernels=None, epochs=5): # Start my custom stuff d = Dense(x, 1) d2 = Dense(d, 1) d3 = Dense(d2, 1) # Assign Kernel matrix to weights if kernels is not None: print 'k' d.W = kernels[0] #d2.W = kernels[1] d.b = bias[0] #d2.b = bias[1] relu = ReLu() sess = Session() sess.add_node(d) sess.add_node(ReLu()) ''' sess.add_node(d2) sess.add_node(ReLu()) sess.add_node(d3) sess.add_node(relu) ''' sess.add_node(subtr(d3, y)) sess.add_node(MeanSqrError(d3)) print '\n' return sess
def click_generate_query_plans(self): print("generate query plans") if not self.plaintextedit_query1.toPlainText().strip( ) or not self.plaintextedit_query2.toPlainText().strip(): self.pop_up_message("Please ensure both box has SQL query") return if not self.connection: self.pop_up_message("Please connect to PostgesSQL server first.") return try: self.session = Session(self.connection, self.plaintextedit_query1.toPlainText(), self.plaintextedit_query2.toPlainText()) except psycopg2.Error as e: self.show_error_message(e.pgerror) self.click_connect(True) return self.query_one_button.setEnabled(True) self.query_two_button.setEnabled(True) self.plaintextedit_queryplan1.setPlainText( str(json.dumps(self.session.query_one_qep_raw))) self.plaintextedit_queryplan2.setPlainText( str(json.dumps(self.session.query_two_qep_raw))) query_one_explanation_list = vocalizer2.textVersion( self.session.query_one_qep_root_node) query_two_explanation_list = vocalizer2.textVersion( self.session.query_two_qep_root_node) self.query_one_explanation.setPlainText( "\n".join(query_one_explanation_list)) self.query_two_explaination.setPlainText( "\n".join(query_two_explanation_list))
def openSession(self): session = Session() session.exec() if session.ret: if session.new: self.onBtnLoadRef() else: print(session.sel)
def testInsert(self): sdao = SessionDAO() session = Session() session.startDate = '2009-10-10' session.lastUpdate = '2009-10-10' session.source.id = self.sourceId session.file.id = self.fileId session.address.id = self.addressId sid = sdao.insert(session) assert sid != -1, 'error inserting session'
def AuthPage(svc, rduri, cid, name, pw, state, resptype, scope): clients = clientdb.ClientDB() try: # check client_id valid client = clients.find_client(cid) if client is None: raise AuthClientError() # check redirect_uri match client_id if not client.check_redirect_uri(rduri): raise AuthClientError() # check client_id may use response_type if not client.check_response_type(resptype): raise AuthError(rduri, 'invalid_client') user = UserManager.LoadUser(name) if (user == None): raise AuthError(rduri, 'access_denied') if not scope: scopes = client.get_scopes() else: scopes = scope.split(' ') for one_scope in scopes: if not client.check_scope(one_scope): raise AuthError(rduri, 'invalid_scope') if (user.Authorize(pw)): session = Session(user, svc.client_address[0], scopes=scopes) session.RecordLogin(True) if resptype == "code": # give session, so other info may be recorded code = Auth.RecordSession(session, cid) target_uri = "%s?code=%s" % (rduri, code) if state: target_uri += "&state=%s" % state elif resptype == "token": token = session.GetID() target_uri = "%s?access_token=%s&token_type=session&expires_in=%d&scope=%s" % ( rduri, token, Config.SESSION_TIMEOUT_SECONDS, ' '.join(scopes)) if state: target_uri += "&state=%s" % state else: raise AuthError(rduri, 'unsupported_response_type') svc.send_response(302) svc.send_header('Location', target_uri) svc.send_header('Content-Length', 0) svc.end_headers() svc.wfile.flush() else: raise AuthError(rduri, 'access_denied') finally: clients.close()
def __init__(self, host, username, pwd): CLIHandler.__init__(self) opts = Values({ 'server' : host, 'portnumber' : 443, 'username' : username, 'password' : pwd }) sessionOptions = SessionOptions(opts) self.session = Session(sessionOptions) self.session.Login()
def do_HEAD(self, method='get', postData={}): self.session = Session.load(Session.determineKey(self)) self.processingRequest() try: self.buildResponse(method, postData) self.sendHead() except Redirect as r: self.responseCode = 302 self.response = '' self.sendHead(additionalHeaders={'Location': r.target})
def do_HEAD(self, method = 'get', postData = {}): self.session = Session.load(Session.determineKey(self)) self.processingRequest() try: self.buildResponse(method, postData) self.sendHead() except Redirect as r: self.responseCode = 302 self.response = '' self.sendHead(additionalHeaders = {'Location': r.target})
def testTimeout(self): transaction = Transaction() session = Session(transaction, 'test') self.assertEqual(session.timeout(), 3600) session.setTimeout(3700) self.assertEqual(session.timeout(), 3700) session.invalidate() self.assertEqual(session.timeout(), 0)
def testIsNew(self): transaction = Transaction() session = Session(transaction, 'test') self.assertIs(session.isNew(), True) session.awake(transaction) self.assertIs(session.isNew(), True) session.awake(transaction) self.assertIs(session.isNew(), False)
def initSession(self, phone, AESKey): print "Core.initSession called" if self.session == None or self.session.authStatus == Constants.AUTHSTATUS_IDLE: #self.yowsupStarted==0 and self.yowsupStarted = 1 if self.session == None: self.session = Session(self, phone, AESKey) self.session.getAuthData() self.signalsInterface.registerListener("disconnected", self.onDisconnected) self.session.login() else: print "\nPretty sure yowsup is already started."
def getHeatMapSessions(self,_json=True): _h = [] _e = [] _t = [] _nSessions = 0 _x = 0 for _folder in reversed(os.listdir(self._dataFolder)): for _device in self.devices: if _device in _folder: #get only the folders from his/her device _file = self._dataFolder + _folder _d = Session(_file) _mdata = _d.getMetaDataOnly() _avgHR = _mdata["session"]["statistics"]["HR_avg"] _avgEDA = _mdata["session"]["statistics"]["EDA_avg"] _avgTEMP = _mdata["session"]["statistics"]["TEMP_avg"] _HM_HR= {} _HM_EDA= {} _HM_TEMP= {} if(_avgHR > 90): _HM_HR["sessionId"] = _folder _HM_HR["date"] = int(_folder[:-7]) _HM_HR["value"] = 60 + _x #silly hack to get links on the heatmap else: _HM_HR["sessionId"] = _folder _HM_HR["date"] = int(_folder[:-7]) _HM_HR["value"] = 2 + _x print _HM_HR _h.append(_HM_HR) if(_avgEDA > 5): _HM_EDA["sessionId"] = _folder _HM_EDA["date"] = int(_folder[:-7]) _HM_EDA["value"] = 60 + _x else: _HM_EDA["sessionId"] = _folder _HM_EDA["date"] = int(_folder[:-7]) _HM_EDA["value"] = 2+ _x _e.append(_HM_EDA) if(_avgTEMP > 37.5): _HM_TEMP["sessionId"] = _folder _HM_TEMP["date"] = int(_folder[:-7]) _HM_TEMP["value"] = 60+ _x else: _HM_TEMP["sessionId"] = _folder _HM_TEMP["date"] = int(_folder[:-7]) _HM_TEMP["value"] = 2+ _x _t.append(_HM_TEMP) _x +=1 if(_json): return [json.dumps(_h),json.dumps(_e),json.dumps(_t)] else: return [_HM_HR,_HM_EDA,_HM_TEMP]
def LoginLogout(self, options, skipLogoutTest=False): # Get session sessionOptions = SessionOptions(options) session = Session(sessionOptions) # Login, do something and then logout stub = session.stub # Not need. Auto login when getting stub: # session.Login() self.AuthenticatedAction(stub) session.Logout() if not skipLogoutTest: self.FailIfRemainAuthenticated(stub)
def MainMenu(): toke = Request.Headers.get("X-Plex-Token", "") if toke: session_id = Hash.MD5(toke) #Hash by token to create user session. else: session_id = Hash.MD5(str(Datetime.Now())) if session_id in sessions: # Prior session started, continue sesh = sessions[session_id] else: # Create a new session sesh = Session(session_id=session_id) sessions[session_id] = sesh RemoveOldSessions() return sesh.SMainMenu()
def HandleLogin(svc, username, passwd): user = UserManager.LoadUser(username) if (user == None): raise Unauthorized('Login failed') if (user.Authorize(passwd)): session = Session(user, svc.client_address[0]) ret = {} ret['session'] = session.GetID() svc.writedata(json.dumps(ret)) else: raise Unauthorized('Login failed')
def start_session(): global start_session_signal global first_req_of_session global current_session current_session = Session() current_session.speaker_id = 'Mohammad' start_session_signal = True print(bcolors.FAIL + "*************NEW SESSION****************" + bcolors.ENDC) log_time("__________ Session Started __________") first_req_of_session = True while (start_session_signal == True): pass return
def createSessionCallback(self, request): print(" [.] createSession(%s)" % request) try: sessionName, boardSize, username = request.split(":") except ValueError: return "FAIL", "" session = Session(self, sessionName, username, int(boardSize)) self.sessions[sessionName] = session session.tryAddPlayer(username) response = "CREATED:" + sessionName # First argument is sent to only the sender. The second one is broadcasted globally. return response, ""
def testCreationAndAccessTime(self): transaction = Transaction() session = Session(transaction, 'test') t = session.creationTime() self.assertIsInstance(t, float) self.assertEqual(session.creationTime(), session.lastAccessTime()) session = Session(transaction, 'test2') self.assertGreaterEqual(session.creationTime(), t)
def start_session(): global start_session_signal global first_req_of_session global current_session global nlp current_session = Session(nlp) current_session.speaker_id = 'Mohammad' start_session_signal = True print(bcolors.FAIL + "*************NEW SESSION****************" + bcolors.ENDC) first_req_of_session = True idle_state_end_pipe.write_to_pipe("s") while (start_session_signal == True): pass return
def doTests(self,_json=True): #create a new session and call check to the last 5 sessions _results = [] _resultJson = {"device_id":self.device,"tests":[]} for _x,_s in enumerate(self._sessions): _se = Session(_s) _res = _se.checkSessionStatus() _results.append(_res) _resultJson["tests"].append(_res) if _x == 4: break if(_json): return json.dumps(_resultJson) else: return _results
def main(): from Session import Session session = Session('z3nbe', '*****@*****.**', token='ExYtkWBYio2KwTedfZ1zgDABL4KPZC8mUUau6iwu') memberships = session.groups.get_all() print([membership.name for membership in memberships])
def Login(self): username = input("用户名(或注册y or n)>>>:").strip() pawd = "" if username == "y" or username == "Y": self.setRegister() self.Login() else: pawd = input("password>>>:").strip() with open(self.__DB_User, "rb") as f: if os.path.getsize(self.__DB_User) == 0: read = {} else: read = pickle.loads(f.read()) if username in read: if Common().Jem_hash(pawd, read[username]["password"]): session = Session()["username"] = username if session: print("登录成功") return True else: print("登录失败:A") return False else: print("登录失败:B") return False else: print("用户不存在") return False
def control_connection(conn, client_addr): print("Connection attempt from" + str(client_addr)) is_correct_authentication, username = check_authentication(conn) conn.sendall(bytes(str(is_correct_authentication) + "\r\n", 'utf-8')) if is_correct_authentication: print("[" + username + "] connected!") current_session = Session(os.getcwd(), username) sessions[conn] = current_session while True: command_line = receive_message(conn) command = command_line.split(" ")[0] command_args = command_line.split(" ")[1:] if command == "close" or command == "quit": print("[" + username + "] disconnected!") sessions.pop(conn) conn.close() break else: manage_command_line(command, command_args, conn) else: print("[" + username + "] failed on authentication") conn.close()
def create_session(self, session_id, model_key): if session_id in self._SESSION_MAP: raise ValueError("session_id %d has already been created" % (session_id)) if model_key not in MODELS: raise ValueError( "%s is not a valid model, check the keys in models.json" % (model_key)) worker = self._WORKER_POOL.get( ) # this will block until we have a free one port = get_free_tcp_port() MODELS[model_key].update({"gpu_id": worker["gpu_id"], "port": port}) if worker["type"] == "local": gpu_id = worker["gpu_id"] process = self._spawn_local_worker(**MODELS[model_key]) model = PytorchUNet(MODELS[model_key]["fn"], gpu_id, MODELS[model_key]["inputShape"]) session = Session(session_id, model) self._SESSION_MAP[session_id] = session self._SESSION_INFO[session_id] = { "worker": worker, "process": process } LOGGER.info("Created a local worker for (%s) on GPU %d" % (session_id, gpu_id)) elif worker["type"] == "remote": raise NotImplementedError("Remote workers aren't implemented yet") else: raise ValueError("Worker type %s isn't recognized" % (worker["type"]))
def testDirectAccess(self): transaction = Transaction() session = Session(transaction, 'test') with self.assertRaises(KeyError): session['a'] # pylint: disable=pointless-statement self.assertNotIn('a', session) session['a'] = 'foo' self.assertEqual(session['a'], 'foo') self.assertIn('a', session) self.assertEqual(session.value('a'), 'foo') self.assertTrue(session.hasValue('a')) del session['a'] with self.assertRaises(KeyError): session['a'] # pylint: disable=pointless-statement self.assertNotIn('a', session) self.assertFalse(session.hasValue('a'))
def testUniqueIds(self): transaction = Transaction() identifiers = set() for _count in range(3): session = Session(transaction) identifier = session.identifier() self.assertIsInstance(identifier, str) self.assertEqual(len(identifier), 47) parts = identifier.split('-') self.assertEqual(len(parts), 2) self.assertEqual(len(parts[0]), 14) self.assertEqual(len(parts[1]), 32) self.assertTrue(parts[0].isdigit()) self.assertTrue(all(c in '0123456789abcdef' for c in parts[1])) self.assertNotIn(identifier, identifiers) identifiers.add(identifier)
def __init__(self, parent=None, callback=None): """ @summary: Create new authentication dialog. @param parent: GtkWindow parent. """ super(AuthDialog, self).__init__() self.__session__ = Session() super(AuthDialog, self).set_title(self.__trans__("Google Authentication")) super(AuthDialog, self).set_flags(gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT) super(AuthDialog, self).add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK) super(AuthDialog, self).set_transient_for(parent) if (parent != None): super(AuthDialog, self).set_position(gtk.WIN_POS_CENTER_ON_PARENT) else: super(AuthDialog, self).set_position(gtk.WIN_POS_CENTER) # Add signals super(AuthDialog, self).connect("response", self.__closeEvent__) super(AuthDialog, self).set_size_request(self.__DEFAULT_WINDOW_WIDTH__, self.__DEFAULT_WINDOW_HEIGHT__) self.__initUI__() self.__callback__ = callback
def extractSessions(source, filename=None): Sessons = Utils.File.readCSV(source) tmp = {} logs = [] print('...start to extract data') for row in Sessons: try: tmpLog = Log(row) tmpLog.setType(setTypeOfLogs(tmpLog.Message)) logs.append(tmpLog) except BaseException as e: print e pass Sessions = {} for log in logs: id = log.getId() if id in Sessions: Sessions[id].update(log) else: Sessions[id] = Session(id) Sessions[id].update(log) print('...start to calc features') for x in Sessions: Sessions[x].calcFeature() if filename != None: print('...start to save session to {0}'.format(filename)) with open(filename, 'w') as f: json.dump(Sessions, f, default=lambda x: x.__dict__) print('...finish') return json.loads(json.dumps(Sessions, default=lambda x: x.__dict__))
def getSessions(self,_json=True): _availableSessions = {"sessions":[],"count":0} _nSessions = 0 for _folder in reversed(os.listdir(self._dataFolder)): for _device in self.devices: if _device in _folder: #get only the folders from his/her device _file = self._dataFolder + _folder _d = Session(_file) _availableSessions["sessions"].append(_d.getMetaDataOnly()) _nSessions += 1 _availableSessions["count"] = _nSessions if(_json): return json.dumps(_availableSessions) else: return _availableSessions
def test_SessionFile(self): session = self.GetValidRootSession() stub = session.stub # Do not logout from stub yet # Save lwp cookie session._SaveCookieFile(self.sessionFile, stub.cookie) # Load cookie options = AnObject() options.sessionfile = self.sessionFile sessionOptions = SessionOptions(options) session2 = Session(sessionOptions) # Check the session is valid self.AuthenticatedAction(session2.stub) # Now we can logout stub = session.stub stub2 = session2.stub session.Logout(force=True) # Make sure both stub are invalid self.FailIfRemainAuthenticated(stub) self.FailIfRemainAuthenticated(stub2)
def read_db(db): # Clears timetable so it can be overwritten timetable = [] # Loops over timetable every day and for day in db.all(): # Creates a local empty lsit to be populated with database session sessions = [] # Appends a Session to current day passing session number, code, teacher, room, time for session in day['sessions']: sessions.append(Session( session['number'], session['code'], session['teacher'], session['room'], session['time'] )) # Appends a Day object passing session, day_name, day_id timetable.append( Day( sessions, day['day_name'], day['day_id'] ) ) return timetable
def login(cls, para): if not checkPara(para, ['version', 'did', ('type', lambda x: x in [cls.DEVICE_TYPE, cls.FB_TYPE])]): return Error.INVALID_PARAM version = para['version'] did = para['did'] if para['type'] == cls.DEVICE_TYPE: (uid, is_new) = Login.device_login(did) else: if para['fb_id'] in para['frd_list']: return Error.INVALID_PARAM (uid, is_new) = Login.fb_login(did, para['fb_id'], para['fb_name'], para['frd_list']) sid = Session.gen_session(uid) ret = {'uid': uid, 'sid': sid} user_info = User(uid).get(['coin', 'level', 'exp', 'name'], True) user_info['exp'] /= 100 ret.update(user_info) if version < Config.LATEST_VERSION: ret['update'] = Config.PKG_URL User(uid).login_time = int(time.time()) if 'ip' in para: g = cls.GEO.city(para['ip']) Location.update(uid, g['country_code'], g['region']) return ret
def __init__(self,name,attrs={},logger=None,logpath='./'): self.sutname=name self.attrs=attrs command = attrs.get('CMD') if not attrs.get('TIMEOUT'): self.attrs.update({'TIMEOUT':int(30)}) else: self.attrs.update({'TIMEOUT':int(attrs.get('TIMEOUT'))}) #spawn.__init__(self, command, args, timeout, maxread, searchwindowsize, logfile, cwd, env, ignore_sighup) import os log = os.path.abspath(logpath) log= '%s%s%s'%(log,os.path.sep,'%s.log'%name) if self.attrs.get('LOGIN'): from common import csvstring2array self.loginstep= csvstring2array(self.attrs['LOGIN']) self.seslog = open(log, "wb") CSession.__init__(self, name, attrs,logger, logpath)
def button_click(self): global configWin global session global myapp global mail pop3Name=str(configWin.ui.lineEdit.text()) smtpName=str(configWin.ui.lineEdit_2.text()) userName=str(self.ui.lineEdit.text()) passwd=str(self.ui.lineEdit_2.text()) session=Session([pop3Name, smtpName, userName, passwd]) resultcode=session.sessionLogin() if resultcode==0: lastaccount=[pop3Name, smtpName, userName, passwd] init.writein(lastaccount) mail=MyMail(session) myapp = MyMailBox() myapp.show() myapp.ui.menubar.addMenu(lastaccount[2]).addAction(myapp.ui.logout) self.close()
def lock(self, type=Constants.LockType_Shared): """Contextmanager yielding a session to a locked machine. Machine must be registered.""" session = Session.create() with VirtualBoxException.ExceptionHandler(): self.getIMachine().lockMachine(session.getISession(), type) try: session._setMachine(VirtualMachine(session.getIMachine())) yield session finally: session.unlockMachine(wait=True)
def __init__(self, credentials): self.credentials = credentials self.queue = RequestQueue(request_limit=600) self.session = Session(self.credentials, self.queue) self.all_endpoints = {'ticket':{'plural':'tickets', 'singular':'ticket'}, 'organization':{'plural':'organizations', 'singular':'organization'}, 'requester': {'plural':'users','singular':'user'}, 'user': {'plural':'users','singular':'user'}, 'assignee': {'plural':'users','singular':'user'}} self.object_cache = BasicCache() self.tickets = Endpoint('ticket', self) self.organizations = Endpoint('organization', self) self.users = Endpoint('user', self)
def folderAdd(self, folderObject): """ each time one adds a new FileWalker object it triggers a new session that is stored using the unique FileWalker name """ if isinstance(folderObject, FileWalker): # clone list of classes and create new thisSession = Session(folderObject.name, folderObject.path, self.classes) # iterate over all files thisSession.addFiles(folderObject) # append the completed session to the list self.sessions.append(thisSession) print "add Folder: %s" % folderObject.name else: return NotImplemented return True
def validate(self, name, pwd): cur = self._conn.cursor() cur.execute(""" SELECT users.id as id ,users.name as name ,auth.hash as pass FROM users ,auth WHERE users.id = auth.user_id and users.name = '""" + name + """' and auth.hash = '""" + pwd + """' """) numrows = cur.rowcount assert numrows in {0, 1} if numrows == 0: return None row = cur.fetchone() sess = Session() sess.set(row[0], row[1], 9999) return sess
def powerOn(self, type="gui", env=""): """Spawns a new process that executes a virtual machine. This is spawning a "remote session" in VirtualBox terms.""" # TODO: Add a wait argument if not self.isRegistered(): raise VirtualBoxException.VirtualBoxInvalidVMStateException( "VM is not registered") with VirtualBoxException.ExceptionHandler(): iMachine = self.getIMachine() session = Session.create() iprogress = iMachine.launchVMProcess(session.getISession(), type, env) progress = Progress(iprogress) progress.waitForCompletion() session.unlockMachine()
def __init__(self): self.arms = Arms() self.world = World() self.session = Session(object_list=self.world.get_frame_list(), is_debug=True) self._viz_publisher = rospy.Publisher('visualization_marker_array', MarkerArray) rospy.Subscriber('recognized_command', Command, self.speech_command_cb) rospy.Subscriber('gui_command', GuiCommand, self.gui_command_cb) self._undo_function = None self.responses = { Command.TEST_MICROPHONE: Response(Interaction.empty_response, [RobotSpeech.TEST_RESPONSE, GazeGoal.NOD]), Command.RELAX_RIGHT_ARM: Response(self.relax_arm, 0), Command.RELAX_LEFT_ARM: Response(self.relax_arm, 1), Command.OPEN_RIGHT_HAND: Response(self.open_hand, 0), Command.OPEN_LEFT_HAND: Response(self.open_hand, 1), Command.CLOSE_RIGHT_HAND: Response(self.close_hand, 0), Command.CLOSE_LEFT_HAND: Response(self.close_hand, 1), Command.STOP_EXECUTION: Response(self.stop_execution, None), Command.UNDO: Response(self.undo, None), Command.DELETE_ALL_STEPS: Response(self.delete_all_steps, None), Command.DELETE_LAST_STEP: Response(self.delete_last_step, None), Command.REPEAT_LAST_STEP: Response(self.repeat_step, None), Command.FREEZE_RIGHT_ARM: Response(self.freeze_arm, 0), Command.FREEZE_LEFT_ARM: Response(self.freeze_arm, 1), Command.CREATE_NEW_ACTION: Response(self.create_action, None), Command.EXECUTE_ACTION: Response(self.execute_action, None), Command.NEXT_ACTION: Response(self.next_action, None), Command.PREV_ACTION: Response(self.previous_action, None), Command.SAVE_POSE: Response(self.save_step, None), Command.RECORD_OBJECT_POSE: Response( self.record_object_pose, None), Command.START_RECORDING_MOTION: Response( self.start_recording, False), Command.START_RECORDING_RELATIVE_MOTION: Response( self.start_recording, True), Command.STOP_RECORDING_MOTION: Response(self.stop_recording, None) } rospy.loginfo('Interaction initialized.')
def find(self, id): self.cursor.execute("""SELECT * FROM """+self.tablename+""" WHERE id = %s""", (id,)) rs = self.cursor.fetchall() session = Session() if not rs: return None for row in rs: session.id = row[0] session.startDate = row[1] session.lastUpdate = row[2] session.downloaded = row[3] session.uploaded = row[4] session.source.id = row[5] session.file.id = row[6] session.address.id = row[7] session.kind = row[8] return session
def __addSession(self, address, param, sessionId, monitor): status = SessionStatus() status.setId(sessionId) status.setProtocol(self.protocol) status.setParam(param) status.setAddress(address) self.IDs.append(sessionId) imp = SessionFactory.createSession(self.protocol) self.lockForSessions.acquire() session = Session(imp, status) status.setSession(session) session.registerObserver(self)#SessionGroup as the observer of session. session.registerMonitor(monitor) session.init() self.sessions.append(session) self.actionsComposite.addAction(session) self.lockForSessions.release()
class TestSequence(unittest.TestCase): def setUp(self): class1 = FileClass('documents', ['.pdf', '.doc']) class2 = FileClass('C-code', ['.c', '.h', '.py']) self.session = Session('testSession', './', [class1, class2]) pass def tearDown(self): pass def test_constructor(self): self.assertEqual(2, len(self.session.classes)) print self.session def test_addingFiles(self): self.folder = FileWalker('AimValley TITAN', '/Users/bastian/Jobb/Transmode/R21-EDU/Software/AIMVALLEY-Titan-R1_03_00-LD3.0-20121119/av-Titan-r1_03_00-ld3.0-121119') self.assertTrue(self.session.addFiles(self.folder)) print self.session
def api(request): try: para = json.loads(request.body) Log.info('Request: %s' % (log_kv(para))) cmd = para['cmd'] if cmd in API_ROUTER: processPara(para) if cmd == 'login': if request.META.has_key('HTTP_X_REAL_IP'): para['ip'] = request.META['HTTP_X_REAL_IP'] else: para['ip'] = request.META['REMOTE_ADDR'] if cmd != 'verify_purchase' and para['version'] < Config.MIN_VERSION: Log.info('unsupported version: %d' % para['version']) return HttpResponse(genResponse(Error.VERSION_TOO_LOW)) if cmd != 'login' and cmd != 'verify_purchase': if not Session.is_valid(para['uid'], para['sid']): Log.error('session invalid') return HttpResponse(genResponse(Error.INVALID_SESSION)) ret = API_ROUTER[cmd](para) response = genResponse(ret, para['uid']) Log.info('Request: %s, Response: %s' % (para, response)) return HttpResponse(response, content_type="application/json") else: Log.error('unknown cmd') return HttpResponse(genResponse(Error.UNKNOWN_CMD)) except Exception, e: traceback.print_exc() Log.error(traceback.format_exc()) return HttpResponseServerError("Unknown error: %s" % str(e))
def findBySourceFileAddress(self, sourceId, fileId, addressId): query = "SELECT * FROM %s WHERE source_id = %s and file_id = %s and address_id = %s " % (self.tablename, sourceId, fileId, addressId) logging.debug(query) self.cursor.execute(query) rs = self.cursor.fetchall() if not rs: return None session = Session() for row in rs: session.id = row[0] session.startDate = row[1] session.lastUpdate = row[2] session.downloaded = row[3] session.uploaded = row[4] session.source.id = row[5] session.file.id = row[6] session.address.id = row[7] session.kind = row[8] return session
class Wrapper: def __init__(self, credentials): self.credentials = credentials self.queue = RequestQueue(request_limit=600) self.session = Session(self.credentials, self.queue) self.all_endpoints = {'ticket':{'plural':'tickets', 'singular':'ticket'}, 'organization':{'plural':'organizations', 'singular':'organization'}, 'requester': {'plural':'users','singular':'user'}, 'user': {'plural':'users','singular':'user'}, 'assignee': {'plural':'users','singular':'user'}} self.object_cache = BasicCache() self.tickets = Endpoint('ticket', self) self.organizations = Endpoint('organization', self) self.users = Endpoint('user', self) def get_all(self, member, fetch=False): singular = self.all_endpoints[member]['singular'] plural = self.all_endpoints[member]['plural'] responses = self.session.get_all(plural) objects = itertools.chain.from_iterable(((zenContainer(self, singular, item['id'], data=item) for item in response.json()[plural]) for response in responses)) if(fetch): objects = list(objects) return objects def get(self, member, object_id, cache=True): singular = self.all_endpoints[member]['singular'] plural = self.all_endpoints[member]['plural'] endpoint = '{}/{}'.format(self.plural, object_id) if not cache: self.expire_cache(endpoint) new_obj = self.object_cache.get(endpoint) if new_obj: return new_obj return zenContainer(self, singular, object_id) def expire_cache(endpoint): cache_url = self.credentials.create_url(endpoint) self.queue.cache.delete(cache_url) self.object_cache.delete(endpoint)
def __init__(self): self.arms = Arms() self.world = World() self.session = Session(object_list=self.world.get_frame_list(), is_debug=True) self._viz_publisher = rospy.Publisher('visualization_marker_array', MarkerArray) self._demo_state = None self._is_busy = True rospy.Subscriber('recognized_command', Command, self.speech_command_cb) rospy.Subscriber('gui_command', GuiCommand, self.gui_command_cb) self.responses = { Command.TEST_MICROPHONE: Response(self.default_response, [RobotSpeech.TEST_RESPONSE, GazeGoal.NOD]), Command.TAKE_TOOL: Response(self.take_tool, 0), Command.RELEASE_TOOL: Response(self.release_tool, 0), Command.START_RECORDING: Response(self.start_recording, None), Command.STOP_RECORDING: Response(self.stop_recording, None), Command.REPLAY_DEMONSTRATION: Response(self.replay_demonstration, None) Command.DETECT_SURFACE: Response(self.detect_surface, None) } rospy.loginfo('Will wait until arms ready to respond.') while ((self.arms.get_ee_state(0) is None) or (self.arms.get_ee_state(1) is None)): time.sleep(0.1) rospy.loginfo('Starting to move to the initial pose.') # TODO: Make it possible to take with either hand self._move_to_arm_pose('take', 0) self._move_to_arm_pose('away', 1) self._wait_for_arms() self._demo_state = DemoState.READY_TO_TAKE Response.say(RobotSpeech.HAND_TOOL_REQUEST) Response.perform_gaze_action(GazeGoal.GLANCE_RIGHT_EE) self._is_busy = False rospy.loginfo('Interaction initialized.')
def __init__(self): self.arms = Arms() self.world = World() self.session = Session(object_list=self.world.get_frame_list(), is_debug=True) self._viz_publisher = rospy.Publisher('visualization_marker_array', MarkerArray) rospy.Subscriber('recognized_command', Command, self.speech_command_cb) rospy.Subscriber('gui_command', GuiCommand, self.gui_command_cb) self._undo_function = None self.responses = { Command.TEST_MICROPHONE: Response(Interaction.empty_response, [RobotSpeech.TEST_RESPONSE, GazeGoal.NOD]), Command.NEW_DEMONSTRATION: Response(self.create_action, None), Command.TAKE_TOOL: Response(self.take_tool, 0), Command.RELEASE_TOOL: Response(self.open_hand, 0), Command.DETECT_SURFACE: Response(self.record_object_pose, None), Command.START_RECORDING: Response(self.start_recording, None), Command.STOP_RECORDING: Response(self.stop_recording, None), Command.REPLAY_DEMONSTRATION: Response(self.execute_action, None), Command.SAVE_ARM_POSE: Response(self.save_arm_pose, None) } rospy.loginfo('Will wait until arms ready to respond.') while ((self.arms.get_ee_state(0) is None) or (self.arms.get_ee_state(1) is None)): time.sleep(0.1) rospy.loginfo('Starting to move to the initial pose.') self._move_to_arm_pose('initial', 0) self._move_to_arm_pose('initial', 1) rospy.loginfo('Interaction initialized.')
class Interaction: '''Finite state machine for the human interaction''' _is_programming = True _is_recording_motion = False _arm_trajectory = None _trajectory_start_time = None def __init__(self): self.arms = Arms() self.world = World() self.session = Session(object_list=self.world.get_frame_list(), is_debug=True) self._viz_publisher = rospy.Publisher('visualization_marker_array', MarkerArray) rospy.Subscriber('recognized_command', Command, self.speech_command_cb) rospy.Subscriber('gui_command', GuiCommand, self.gui_command_cb) self._undo_function = None self.responses = { Command.TEST_MICROPHONE: Response(Interaction.empty_response, [RobotSpeech.TEST_RESPONSE, GazeGoal.NOD]), Command.NEW_DEMONSTRATION: Response(self.create_action, None), Command.TAKE_TOOL: Response(self.take_tool, 0), Command.RELEASE_TOOL: Response(self.open_hand, 0), Command.DETECT_SURFACE: Response(self.record_object_pose, None), Command.START_RECORDING: Response(self.start_recording, None), Command.STOP_RECORDING: Response(self.stop_recording, None), Command.REPLAY_DEMONSTRATION: Response(self.execute_action, None), Command.SAVE_ARM_POSE: Response(self.save_arm_pose, None) } rospy.loginfo('Will wait until arms ready to respond.') while ((self.arms.get_ee_state(0) is None) or (self.arms.get_ee_state(1) is None)): time.sleep(0.1) rospy.loginfo('Starting to move to the initial pose.') self._move_to_arm_pose('initial', 0) self._move_to_arm_pose('initial', 1) rospy.loginfo('Interaction initialized.') def load_known_arm_poses(self): '''This loads important poses from the hard drive''' # TODO pass def open_hand(self, arm_index): '''Opens gripper on the indicated side''' if self.arms.set_gripper_state(arm_index, GripperState.OPEN): speech_response = Response.open_responses[arm_index] if (Interaction._is_programming and self.session.n_actions() > 0): self.save_gripper_step(arm_index, GripperState.OPEN) speech_response = (speech_response + ' ' + RobotSpeech.STEP_RECORDED) return [speech_response, Response.glance_actions[arm_index]] else: return [Response.already_open_responses[arm_index], Response.glance_actions[arm_index]] def take_tool(self, arm_index): self.close_hand(arm_index) self._move_to_arm_pose('initial', arm_index) def close_hand(self, arm_index): '''Closes gripper on the indicated side''' if Arms.set_gripper_state(arm_index, GripperState.CLOSED): speech_response = Response.close_responses[arm_index] return [speech_response, Response.glance_actions[arm_index]] else: return [Response.already_closed_responses[arm_index], Response.glance_actions[arm_index]] def relax_arm(self, arm_index): '''Relaxes arm on the indicated side''' if self.arms.set_arm_mode(arm_index, ArmMode.RELEASE): return [Response.release_responses[arm_index], Response.glance_actions[arm_index]] else: return [Response.already_released_responses[arm_index], Response.glance_actions[arm_index]] def freeze_arm(self, arm_index): '''Stiffens arm on the indicated side''' if self.arms.set_arm_mode(arm_index, ArmMode.HOLD): return [Response.hold_responses[arm_index], Response.glance_actions[arm_index]] else: return [Response.already_holding_responses[arm_index], Response.glance_actions[arm_index]] def edit_action(self, dummy=None): '''Goes back to edit mode''' if (self.session.n_actions() > 0): if (Interaction._is_programming): return [RobotSpeech.ALREADY_EDITING, GazeGoal.SHAKE] else: Interaction._is_programming = True return [RobotSpeech.SWITCH_TO_EDIT_MODE, GazeGoal.NOD] else: return [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE] def save_action(self, dummy=None): '''Goes out of edit mode''' self.session.save_current_action() Interaction._is_programming = False return [RobotSpeech.ACTION_SAVED + ' ' + str(self.session.current_action_index), GazeGoal.NOD] def create_action(self, dummy=None): '''Creates a new empty action''' self._move_to_arm_pose('take', 0) self.world.clear_all_objects() self.session.new_action() Interaction._is_programming = True return [RobotSpeech.SKILL_CREATED + ' ' + str(self.session.current_action_index), GazeGoal.NOD] def next_action(self, dummy=None): '''Switches to next action''' if (self.session.n_actions() > 0): if self.session.next_action(self.world.get_frame_list()): return [RobotSpeech.SWITCH_SKILL + ' ' + str(self.session.current_action_index), GazeGoal.NOD] else: return [RobotSpeech.ERROR_NEXT_SKILL + ' ' + str(self.session.current_action_index), GazeGoal.SHAKE] else: return [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE] def previous_action(self, dummy=None): '''Switches to previous action''' if (self.session.n_actions() > 0): if self.session.previous_action(self.world.get_frame_list()): return [RobotSpeech.SWITCH_SKILL + ' ' + str(self.session.current_action_index), GazeGoal.NOD] else: return [RobotSpeech.ERROR_PREV_SKILL + ' ' + str(self.session.current_action_index), GazeGoal.SHAKE] else: return [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE] def delete_all_steps(self, dummy=None): '''Deletes all steps in the current action''' if (self.session.n_actions() > 0): if (Interaction._is_programming): if self.session.n_frames() > 0: self.session.clear_current_action() self._undo_function = self._resume_all_steps return [RobotSpeech.SKILL_CLEARED, GazeGoal.NOD] else: return [RobotSpeech.SKILL_EMPTY, None] else: return ['Action ' + str(self.session.current_action_index) + RobotSpeech.ERROR_NOT_IN_EDIT, GazeGoal.SHAKE] else: return [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE] def _resume_all_steps(self): '''Resumes all steps after clearing''' self.session.undo_clear() return [RobotSpeech.ALL_POSES_RESUMED, GazeGoal.NOD] def _resume_last_step(self): '''Resumes last step after deleting''' self.session.resume_deleted_step() return [RobotSpeech.POSE_RESUMED, GazeGoal.NOD] def stop_execution(self, dummy=None): '''Stops ongoing execution''' if (self.arms.is_executing()): self.arms.stop_execution() return [RobotSpeech.STOPPING_EXECUTION, GazeGoal.NOD] else: return [RobotSpeech.ERROR_NO_EXECUTION, GazeGoal.SHAKE] def save_gripper_step(self, arm_index, gripper_state): '''Saves an action step that involves a gripper state change''' if (self.session.n_actions() > 0): if (Interaction._is_programming): states = self._get_arm_states() step = ActionStep() step.type = ActionStep.ARM_TARGET step.armTarget = ArmTarget(states[0], states[1], 0.2, 0.2) actions = [self.arms.get_gripper_state(0), self.arms.get_gripper_state(1)] actions[arm_index] = gripper_state step.gripperAction = GripperAction(actions[0], actions[1]) self.session.add_step_to_action(step, self.world.get_frame_list()) def start_recording(self, dummy=None): '''Starts recording continuous motion''' if (self.session.n_actions() > 0): if (Interaction._is_programming): if (not Interaction._is_recording_motion): Interaction._is_recording_motion = True Interaction._arm_trajectory = ArmTrajectory() Interaction._trajectory_start_time = rospy.Time.now() if self.session.n_frames() > 0: self.session.clear_current_action() return [RobotSpeech.STARTED_RECORDING_MOTION, GazeGoal.NOD] else: return [RobotSpeech.ALREADY_RECORDING_MOTION, GazeGoal.SHAKE] else: return ['Action ' + str(self.session.current_action_index) + RobotSpeech.ERROR_NOT_IN_EDIT, GazeGoal.SHAKE] else: return [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE] def stop_recording(self, dummy=None): '''Stops recording continuous motion''' if (Interaction._is_recording_motion): Interaction._is_recording_motion = False traj_step = ActionStep() traj_step.type = ActionStep.ARM_TRAJECTORY waited_time = Interaction._arm_trajectory.timing[0] for i in range(len(Interaction._arm_trajectory.timing)): Interaction._arm_trajectory.timing[i] -= waited_time Interaction._arm_trajectory.timing[i] += rospy.Duration(0.1) '''If motion was relative, record transformed pose''' traj_step.armTrajectory = ArmTrajectory( Interaction._arm_trajectory.rArm[:], Interaction._arm_trajectory.lArm[:], Interaction._arm_trajectory.timing[:], Interaction._arm_trajectory.rRefFrame, Interaction._arm_trajectory.lRefFrame, Interaction._arm_trajectory.rRefFrameObject, Interaction._arm_trajectory.lRefFrameObject) traj_step.gripperAction = GripperAction( self.arms.get_gripper_state(0), self.arms.get_gripper_state(1)) self.session.add_step_to_action(traj_step, self.world.get_frame_list()) Interaction._arm_trajectory = None Interaction._trajectory_start_time = None return [RobotSpeech.STOPPED_RECORDING_MOTION + ' ' + RobotSpeech.STEP_RECORDED, GazeGoal.NOD] else: return [RobotSpeech.MOTION_NOT_RECORDING, GazeGoal.SHAKE] def _fix_trajectory_ref(self): '''Makes the reference frame of continuous trajectories uniform''' (r_ref, _), (_, r_ref_obj) = self._find_dominant_ref( Interaction._arm_trajectory.rArm) (l_ref, _), (_, l_ref_obj) = self._find_dominant_ref( Interaction._arm_trajectory.lArm) for i in range(len(Interaction._arm_trajectory.timing)): Interaction._arm_trajectory.rArm[i] = World.convert_ref_frame( Interaction._arm_trajectory.rArm[i], r_ref, r_ref_obj) Interaction._arm_trajectory.lArm[i] = World.convert_ref_frame( Interaction._arm_trajectory.lArm[i], l_ref, l_ref_obj) Interaction._arm_trajectory.rRefFrame = r_ref Interaction._arm_trajectory.rRefFrameObject = r_ref_obj Interaction._arm_trajectory.lRefFrame = l_ref Interaction._arm_trajectory.lRefFrameObject = l_ref_obj def _find_dominant_ref(self, arm_traj): '''Finds the most dominant reference frame in a continuous trajectory''' def addEnt(dic, ent): key = (ent.refFrame, ent.refFrameObject.name) if (key in dic): dic[key] = (1 + dic[key][0], dic[key][1]) else: dic[key] = (1, ent.refFrameObject) return dic cnt = reduce(addEnt, arm_traj, {}) return reduce(lambda a, b: a if a[1][0] > b[1][0] else b, cnt.items()) def _save_arm_to_trajectory(self): '''Saves current arm state into continuous trajectory''' if (Interaction._arm_trajectory != None): states = self._get_arm_states() Interaction._arm_trajectory.rArm.append(states[0]) Interaction._arm_trajectory.lArm.append(states[1]) Interaction._arm_trajectory.timing.append( rospy.Time.now() - Interaction._trajectory_start_time) def _move_to_arm_pose(self, pose_name, arm_index): '''Moves the robot's arm to a pre-specified arm pose''' action = self.session.pose_set[pose_name] if action is None: rospy.logwarn('Arm pose does not exist:' + pose_name) else: step = action.get_step(0) if arm_index == 0: self.arms.start_move_to_pose(step.armTarget.rArm, 0) self.arms.set_gripper_state(0, step.gripperAction.rGripper) else: self.arms.start_move_to_pose(step.armTarget.lArm, 1) self.arms.set_gripper_state(1, step.gripperAction.lGripper) rospy.loginfo('Moved arm ' + str(arm_index) + ' to pose ' + pose_name) def save_arm_pose(self, dummy=None): '''Saves current arm state as an action step''' states = self._get_arm_states() step = ActionStep() step.type = ActionStep.ARM_TARGET step.armTarget = ArmTarget(states[0], states[1], 0.2, 0.2) step.gripperAction = GripperAction( self.arms.get_gripper_state(0), self.arms.get_gripper_state(1)) self.session.save_arm_pose(step, self.world.get_frame_list()) return [RobotSpeech.STEP_RECORDED, GazeGoal.NOD] def _get_arm_states(self): '''Returns the current arms states in the right format''' abs_ee_poses = [Arms.get_ee_state(0), Arms.get_ee_state(1)] joint_poses = [Arms.get_joint_state(0), Arms.get_joint_state(1)] states = [None, None] for arm_index in [0, 1]: nearest_obj = self.world.get_nearest_object( abs_ee_poses[arm_index]) if (nearest_obj == None): states[arm_index] = ArmState(ArmState.ROBOT_BASE, abs_ee_poses[arm_index], joint_poses[arm_index], Object()) else: # Relative rel_ee_pose = World.transform( abs_ee_poses[arm_index], 'base_link', nearest_obj.name) states[arm_index] = ArmState(ArmState.OBJECT, rel_ee_pose, joint_poses[arm_index], nearest_obj) return states def execute_action(self, dummy=None): '''Starts the execution of the current action''' if (self.session.n_actions() > 0): if (self.session.n_frames() > 0): self.session.save_current_action() action = self.session.get_current_action() if (action.is_object_required()): if (self.world.update_object_pose()): self.session.get_current_action().update_objects( self.world.get_frame_list()) self.arms.start_execution(action) else: return [RobotSpeech.OBJECT_NOT_DETECTED, GazeGoal.SHAKE] else: self.arms.start_execution(action) return [RobotSpeech.START_EXECUTION + ' ' + str(self.session.current_action_index), None] else: return [RobotSpeech.EXECUTION_ERROR_NOPOSES + ' ' + str(self.session.current_action_index), GazeGoal.SHAKE] else: return [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE] def speech_command_cb(self, command): '''Callback for when a speech command is receieved''' if command.command in self.responses.keys(): rospy.loginfo('\033[32m Calling response for command ' + command.command + '\033[0m') response = self.responses[command.command] if (not self.arms.is_executing()): if (self._undo_function != None): response.respond() self._undo_function = None else: response.respond() else: if command.command == Command.STOP_EXECUTION: response.respond() else: rospy.logwarn('Ignoring speech command during execution: ' + command.command) else: switch_command = 'SWITCH_TO_ACTION' if (switch_command in command.command): action_no = command.command[ len(switch_command):len(command.command)] action_no = int(action_no) if (self.session.n_actions() > 0): self.session.switch_to_action(action_no, self.world.get_frame_list()) response = Response(Interaction.empty_response, [RobotSpeech.SWITCH_SKILL + str(action_no), GazeGoal.NOD]) else: response = Response(Interaction.empty_response, [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE]) response.respond() else: rospy.logwarn('\033[32m This command (' + command.command + ') is unknown. \033[0m') def gui_command_cb(self, command): '''Callback for when a GUI command is received''' if (not self.arms.is_executing()): if (self.session.n_actions() > 0): if (command.command == GuiCommand.SWITCH_TO_ACTION): action_no = command.param self.session.switch_to_action(action_no, self.world.get_frame_list()) response = Response(Interaction.empty_response, [RobotSpeech.SWITCH_SKILL + str(action_no), GazeGoal.NOD]) response.respond() elif (command.command == GuiCommand.SELECT_ACTION_STEP): step_no = command.param self.session.select_action_step(step_no) rospy.loginfo('Selected action step ' + str(step_no)) else: rospy.logwarn('\033[32m This command (' + command.command + ') is unknown. \033[0m') else: response = Response(Interaction.empty_response, [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE]) response.respond() else: rospy.logwarn('Ignoring GUI command during execution: ' + command.command) def update(self): '''General update for the main loop''' self.arms.update() if (self.arms.status != ExecutionStatus.NOT_EXECUTING): if (self.arms.status != ExecutionStatus.EXECUTING): self._end_execution() if (Interaction._is_recording_motion): self._save_arm_to_trajectory() is_world_changed = self.world.update() if (self.session.n_actions() > 0): action = self.session.get_current_action() action.update_viz() r_target = action.get_requested_targets(0) if (r_target != None): self.arms.start_move_to_pose(r_target, 0) action.reset_targets(0) l_target = action.get_requested_targets(1) if (l_target != None): self.arms.start_move_to_pose(l_target, 1) action.reset_targets(1) action.delete_requested_steps() states = self._get_arm_states() action.change_requested_steps(states[0], states[1]) if (is_world_changed): rospy.loginfo('The world has changed.') self.session.get_current_action().update_objects( self.world.get_frame_list()) time.sleep(0.1) def _end_execution(self): '''Responses for when the action execution ends''' if (self.arms.status == ExecutionStatus.SUCCEEDED): Response.say(RobotSpeech.EXECUTION_ENDED) Response.perform_gaze_action(GazeGoal.NOD) elif (self.arms.status == ExecutionStatus.PREEMPTED): Response.say(RobotSpeech.EXECUTION_PREEMPTED) Response.perform_gaze_action(GazeGoal.SHAKE) else: Response.say(RobotSpeech.EXECUTION_ERROR_NOIK) Response.perform_gaze_action(GazeGoal.SHAKE) self.arms.status = ExecutionStatus.NOT_EXECUTING def record_object_pose(self, dummy=None): '''Makes the robot look for a table and objects''' if (self.world.update_object_pose()): if (self.session.n_actions() > 0): self.session.get_current_action().update_objects( self.world.get_frame_list()) return [RobotSpeech.START_STATE_RECORDED, GazeGoal.NOD] else: return [RobotSpeech.OBJECT_NOT_DETECTED, GazeGoal.SHAKE] def save_experiment_state(self): '''Saves session state''' self.session.save_current_action() @staticmethod def empty_response(responses): '''Default response to speech commands''' return responses
def getDataFromSession(self,session,signalType,_json=True): _file = self._dataFolder +session _d = Session(_file) return _d.getData(signalType,_json)
def __init__(self): self._session = Session()
class MasterController(object): #import header and footer HEADER = open("header.html", "r").read() FOOTER = open("footer.html", "r").read() URL_BASE = '/~kou/3132GroupProject' _session = None def __init__(self): self._session = Session() def markup(self, posts): markup = '' markup += '<div id="wrap2">' markup += '<img border="0" src="' + self.URL_BASE + '/gglogo.png" alt="gogeo logo" width="250" height="125">' markup += '<img border="0" src="' + self.URL_BASE + '/banner.png" alt="banner" width="1000" height="125">' markup += '</div>' markup += '</br >' markup += '<div id="wrap">' markup += '<h3> Geo-Location </h3>' markup += '<div id="map">' markup += '</div>' markup += '</div>' markup += '<div id="wrap4">' print self._session._cookie if self._session.getState(): markup += '<form action="' + self.URL_BASE + '/post/create" method="GET" class="post-form">' markup += '<p>' markup += '<label for="post">Post</label><br />' markup += '<textarea name="post" rows="5" cols="80"></textarea><br />' markup += '<input type="submit" value="Post" class="post-form-submit"/>' markup += '</p>' markup += '<input type="hidden" name="user_id" value="' + self._session._user_id + '"/>' markup += '</form>' markup += '<div class="post-form-links"><a href="' + self.URL_BASE + '/user/logout">Logout</a></div>' else: markup += '<form action="' + self.URL_BASE + '/user/login" method="POST" class="login-form">' markup += '<p>' markup += '<label for="user_name">User Name</label><br />' markup += '<input name="user_name" />' markup += '</p>' markup += '<p>' markup += '<label for="password">Password</label><br />' markup += '<input type="password" name="password" />' markup += '</p>' markup += '<input type="submit" value="Login" class="login-form-submit"/>' markup += '</p>' markup += '</form>' for post_id in posts: markup += '<div class="post-wrapper">' markup += '<span class="post-author">Author: ' markup += posts[post_id]['user_id'] markup += '</span>' markup += '<span class="post-location" data-lat="' + posts[post_id]['lat'] + '" data-lng="' + posts[post_id]['lng'] + '">' markup += 'lat: ' + posts[post_id]['lat'] + ' lng: ' + posts[post_id]['lng'] markup += '</span>' markup += '<div class="post-content">' markup += posts[post_id]['post'] markup += '</div>' markup += '<span class="post-date"><em>' + posts[post_id]['created_at'] + '</em></span>' markup += '</div>' markup += '<div class="post-links">' if self._session._role == 'admin': markup += '<a href="' + self.URL_BASE + '/post/delete?post_id=' + str(post_id) + '">Delete this post</a>' markup += '</div>' markup += '<div class="comments_wrapper">' if posts[post_id]['comments']: markup += '<h4>Comments:</h4>' for comment_id in posts[post_id]['comments']: markup += '<div class="comment-wrapper">' markup += '<p>' + posts[post_id]['comments'][comment_id]['comment'] + '</p>' if self._session.getState(): markup += '<div class="comment-form">' markup += '<form action="' + self.URL_BASE + '/comment/create" method="POST">' markup += '<p>' markup += '<label for="comment">Comment</label><br />' markup += '<textarea name="comment" rows="3" cols="50"></textarea><br />' markup += '<input type="submit" value="Comment" class="comment-form-submit"/>' markup += '</p>' markup += '<input type="hidden" name="post_id" value="' + str(post_id) + '"/>' markup += '<input type="hidden" name="user_id" value="' + self._session._user_id + '"/>' markup += '</form>' #check permissions and add delete, comment, and edit links here # markup += '</div>' markup += '<hr />' markup += '</div>' return markup
#!/usr/bin/env python3 from Session import Session from getpass import getpass s = Session.login('*****@*****.**', getpass()) s.resume() s.listen()