def __loadDefaults(): global __defaultLangDict global __defaultCountryDict global __defaultLocale pos = __defaultLocale.find("-") if pos > -1: lang = __defaultLocale[:pos] langPath = os.path.join(Plugin.BundlePath, "Contents/Strings/%s.json" % lang) if os.path.exists(langPath): __defaultLangDict = JSON.DictFromFile(langPath) Log.Add("(Framework) Loaded %s strings" % lang) else: Log.Add("(Framework) Couldn't find %s strings" % lang) locPath = os.path.join(Plugin.BundlePath, "Contents/Strings/%s.json" % __defaultLocale) if os.path.exists(locPath): __defaultCountryDict = JSON.DictFromFile(locPath) Log.Add("(Framework) Loaded %s strings" % __defaultLocale) else: Log.Add("(Framework) Couldn't find %s strings" % __defaultLocale) else: langPath = os.path.join(Plugin.BundlePath, "Contents/Strings/%s.json" % __defaultLocale) if os.path.exists(langPath): __defaultLangDict = JSON.DictFromFile(langPath) Log.Add("(Framework) Loaded %s strings" % __defaultLocale) else: Log.Add("(Framework) Couldn't find %s strings" % __defaultLocale)
def __loadLocale(loc): global CurrentLocale global __langDict global __countryDict pos = loc.find("-") if pos > -1: lang = loc[:pos] langPath = os.path.join(Plugin.BundlePath, "Contents/Strings/%s.json" % lang) if os.path.exists(langPath): __langDict = JSON.DictFromFile(langPath) Log.Add("(Framework) Loaded %s strings" % lang) else: Log.Add("(Framework) Couldn't find %s strings" % lang) locPath = os.path.join(Plugin.BundlePath, "Contents/Strings/%s.json" % loc) if os.path.exists(locPath): __countryDict = JSON.DictFromFile(locPath) Log.Add("(Framework) Loaded %s strings" % loc) else: Log.Add("(Framework) Couldn't find %s strings" % loc) else: langPath = os.path.join(Plugin.BundlePath, "Contents/Strings/%s.json" % loc) if os.path.exists(langPath): __langDict = JSON.DictFromFile(langPath) Log.Add("(Framework) Loaded %s strings" % loc) else: Log.Add("(Framework) Couldn't find %s strings" % loc) CurrentLocale = loc
def create_user(data, message): data[message.from_user.id] = { 'name': message.from_user.first_name, 'username': message.from_user.username, 'last_name': message.from_user.last_name, 'wantable_presents': [], 'recipient': None } JSON.write_to_json(users_json, data)
def set_presents(message): data = JSON.read_from_json(users_json) if data.get(str(message.from_user.id), None) is not None: update_presents(data, message) else: create_user(data, message) update_presents(data, message) bot.send_message( message.chat.id, f'Привет, {normalize_string(message.chat.first_name)} {normalize_string(message.chat.last_name)}, я тебя добавил в список гостей' ) bot.reply_to(message, 'Добавил Ваши желание в свой список))') JSON.write_to_json(users_json, data)
def getApplicationBody(self): """ According to Content-Encoding and Content-Type, tries to decode the body. Returns the raw body if the content encoding or type were unknown. """ contentType = self.getContentType() contentEncoding = self.getContentEncoding() # Raw body body = self.getBody() # First handle the encoding part if contentEncoding == self.ENCODING_UTF8: body = body.decode('utf-8') elif contentEncoding == self.ENCODING_BASE64: body = base64.decodestring(body) # Other encodings are not decoded/supported # Then turn the content type into something higher level if contentType == self.CONTENT_TYPE_JSON: ret = JSON.loads(self.getBody()) return ret elif contentType == self.CONTENT_TYPE_PYTHON_PICKLE: ret = pickle.loads(self.getBody()) return ret elif contentType == self.CONTENT_TYPE_GZIP: ret = zlib.decompress(body) return ret else: # No application decoding, but encoding decoding done. return body
async def new_message_event(client, message): try: #my_json_string=JSON.stringify(message) #to_python = JSON.loads(my_json_string) #print(to_python['sticker']) dicted = dict(message) with open(JSON.stringify(message)) as file: # data=json.load(file) #print(len(data["sticker"])) #print(data_dict["message"][0]["file_id"]) await message.reply_text( f"<code>{message}</code>", quote=True, disable_web_page_preview=True, disable_notification=True, ) except (PeerIdInvalid, UserIsBlocked): pass except Exception as e: LOGGER.info(str(e)) with BytesIO(str.encode(str(message))) as out_file: out_file.name = "json.text" await message.reply_document( document=out_file, caption=str(e), disable_notification=True, quote=True )
def startPaxos(): global sendQueue global sendMap global localIP global initialVal me = localIP ballot[0] += 1 proposingBool = True phaseTwoList = [] acceptVal = "" while True: if MY_PI == 1: initialVal = str(MY_PI) + ":" + str(network.getRSSI()) for dest in sendMap.keys(): sendMessage = JSON.jsonMsg(me, dest, state="PREPARE", ballot=ballot) sendQueue.put(sendMessage) #sock = sendMap[dest] #sock.send(sendMessage.encode('utf-8')) time.sleep(random.randint(3, 7))
def SetDefaultLocale(loc="en-us"): global defaultLangDict global defaultCountryDict global __defaultLocale global CurrentLocale if loc == __defaultLocale: return __defaultLocale = loc pos = __defaultLocale.find("-") if pos > -1: lang = __defaultLocale[:pos] langPath = os.path.join(Plugin.__bundlePath, "Contents/Strings/%s.json" % lang) if os.path.exists(langPath): f = open(langPath, "r") defaultLangDict = JSON.ObjectFromString(f.read()) f.close() PMS.Log("(Framework) Loaded %s strings" % lang) else: PMS.Log("(Framework) Couldn't find %s strings" % lang) locPath = os.path.join(Plugin.__bundlePath, "Contents/Strings/%s.json" % __defaultLocale) if os.path.exists(locPath): f = open(locPath, "r") defaultCountryDict = JSON.ObjectFromString(f.read()) f.close() PMS.Log("(Framework) Loaded %s strings" % __defaultLocale) else: PMS.Log("(Framework) Couldn't find %s strings" % __defaultLocale) else: langPath = os.path.join(Plugin.__bundlePath, "Contents/Strings/%s.json" % __defaultLocale) if os.path.exists(langPath): f = open(langPath, "r") defaultLangDict = JSON.ObjectFromString(f.read()) f.close() PMS.Log("(Framework) Loaded %s strings" % __defaultLocale) else: PMS.Log("(Framework) Couldn't find %s strings" % __defaultLocale) if CurrentLocale == None: CurrentLocale = loc
def __loadLocale(loc): global CurrentLocale if loc == CurrentLocale: return None global langDict global countryDict pos = loc.find("-") if pos > -1: lang = loc[:pos] langPath = os.path.join(Plugin.__bundlePath, "Contents/Strings/%s.json" % lang) if os.path.exists(langPath): f = open(langPath, "r") langDict = JSON.ObjectFromString(f.read()) f.close() PMS.Log("(Framework) Loaded %s strings" % lang) else: PMS.Log("(Framework) Couldn't find %s strings" % lang) locPath = os.path.join(Plugin.__bundlePath, "Contents/Strings/%s.json" % loc) if os.path.exists(locPath): f = open(locPath, "r") countryDict = JSON.ObjectFromString(f.read()) f.close() PMS.Log("(Framework) Loaded %s strings" % loc) else: PMS.Log("(Framework) Couldn't find %s strings" % loc) else: langPath = os.path.join(Plugin.__bundlePath, "Contents/Strings/%s.json" % loc) if os.path.exists(langPath): f = open(langPath, "r") langDict = JSON.ObjectFromString(f.read()) f.close() PMS.Log("(Framework) Loaded %s strings" % loc) else: PMS.Log("(Framework) Couldn't find %s strings" % loc) CurrentLocale = loc
def traceRoute(meuIP, JSONmsg): msg = json.loads(JSONmsg) msg["hops"].append(meuIP) resultJSON = json.dumps(msg) if (meuIP == msg["destination"]): dataMsg = JSON.Data(meuIP, msg["source"], resultJSON) print("Enviar Data:", dataMsg) # Enviar mensagem como data aqui else: print("Enviar trace:", resultJSON) #enviar mensagem como trace aqui
def list_themes(): if(request.args.get("submit",None)): arg={} arg["RECAPTCHA_PUBLIC_KEY"]=RECAPTCHA_PUBLIC_KEY arg["RECAPTCHA_KEY"]=RECAPTCHA_KEY return render_template('submittheme.html',**arg) elif(request.args.get("name",None)): themename=request.args.get("name") themedata=Theme.get_by_key_name(themename) if(themedata==None): return 'Theme not found',404 thedict=dict() thedict["name"]=themedata.name thedict["submitter"]=themedata.submitter thedict["email"]=themedata.email thedict["data"]=JSON.loads(themedata.data) return JSON.dumps(thedict) else: themelist=Theme.all() return render_template( 'themegallery.html' , themes=themelist)
def list_themes(): if (request.args.get("submit", None)): arg = {} arg["RECAPTCHA_PUBLIC_KEY"] = RECAPTCHA_PUBLIC_KEY arg["RECAPTCHA_KEY"] = RECAPTCHA_KEY return render_template('submittheme.html', **arg) elif (request.args.get("name", None)): themename = request.args.get("name") themedata = Theme.get_by_key_name(themename) if (themedata == None): return 'Theme not found', 404 thedict = dict() thedict["name"] = themedata.name thedict["submitter"] = themedata.submitter thedict["email"] = themedata.email thedict["data"] = JSON.loads(themedata.data) return JSON.dumps(thedict) else: themelist = Theme.all() return render_template('themegallery.html', themes=themelist)
def the_new_year(message): if str(message.from_user.id) != '531184087': return data = JSON.read_from_json(users_json) users = list(data.keys()) random.shuffle(users) for i, ID in enumerate(users): data[ID]['recipient'] = users[(i + 1) % len(users)] data_keys = list(data.keys()) for ID in data_keys: try: bot.send_message( ID, f"Ты даришь подарок человечку с именем {normalize_string(data[data[ID]['recipient']]['name'])} {normalize_string(data[data[ID]['recipient']]['last_name'])}: " ) for present in data[data[ID]['recipient']]['wantable_presents']: bot.send_message(ID, f'Он(а) хочет {present}') except: del data[ID] JSON.write_to_json(users_json, data)
def recvThread(recvSock): global recvQueue while True: recvMessage = recvSock.recv(1024).decode('utf-8') for message in JSON.splitDualMessage(recvMessage): processNetworkData(message) #print("recvThread()::59 Received", recvMessage) return
def __loadDefaults(): global __dict __dict = {} path = "%s/Contents/DefaultDict.json" % Plugin.__bundlePath if os.path.exists(path): f = open(path, "r") string = f.read() f.close() __dict = JSON.ObjectFromString(string) PMS.Log("(Framework) Loaded the default dictionary file") Plugin.__callNamed("CreateDict", addToLog=False) Set("Framework.LastCompatibilityVersion", PMS.FrameworkCompatibilityVersion, addToLog=False)
def TraceCommand( self, ipDest): # Formata o 1o trace e envia para o proximo servidor msg = JSON.Trace(self.myIP, ipDest, [self.myIP]) proxServ = FuncoesApoio.GetMenorRota( self.myIP, ipDest, self.myRouteTable ) # retorna o proximo servidor a repassar a mensagem # print("PROXSERVTRACE:",proxServ) if (proxServ != 0): self.SendMsgTo(msg, proxServ) # print("Enviar 1o Trace:",msg) else: print( "ERROR - Server nao esta na lista, aguarde os updates, ou adicione uma rota" )
def sendPeriodic(self, ipDest): dicAux = {} for i in self.myRouteTable: aux1 = FuncoesApoio.GetMenorPesoRota(self.myIP, i, self.myRouteTable) aux2 = FuncoesApoio.GetMenorPesoRota(self.myIP, ipDest, self.myRouteTable) if (i != self.myIP and i == aux1[1] ): # Não enviar a rota do meu ip e de rotas aprendidas if (aux1 != aux2): pesoDist = aux1[0] + aux2[0] dicAux[i] = pesoDist else: dicAux[self.myIP] = aux1[0] msg = JSON.Update(self.myIP, ipDest, dicAux) self.SendMsgTo(msg, ipDest)
def recvThread(listenSock, socketMap): """ param1 listenSock: socket that should be continously listened on param2 msgQueue: global queue that is shared between sockets that will contain all messages received on the process brief: Continuously listens on the socket and once received places the message in the global message queue """ global TOTAL_PIS_CONNECTED global recvQueue while True: message = listenSock.recv(1024).decode('utf-8') print("Received message", message) for msg in JSON.splitDualMessage(message): #check that message has mapping, if not, we map in socketMapping _json = json.loads(msg) messageSender = int(_json["src"]) #print("recvThread 116: from", messageSender, "msg", msg) #First time we receive a message from a different process we need to map it if messageSender not in socketMap.keys(): #Get the remote IP talking to listen port then map our send socket to that IP ipSender = listenSock.getpeername()[0] #If we have yet to connect to this, we just set the corresponding socket to None while we wait to connect to this port if ipSender not in ipToSock.keys(): ipToSock[ipSender] = None socketMap[messageSender] = ipToSock[ipSender] print("NEW SOCKET ADDED WITH IP", listenSock.getpeername()) recvQueue.put(msg)
def handle_get_runtime_log(self, jobId, lastLogEventId=0): """ Called via an ajax-like call. Returns the new log elements for a particular job (id'd by jobId) since the lastLogElementId. If the jobId is currently registered in our current monitoring threads, returns them as XML elements Otherwise returns a null object. """ elements = self._jobMonitorManager.getEvents(jobId) if not elements: time.sleep(1) # force a wait to avoid a requery. Normally we should wait until a new event arrives instead. logElements = [dict(eventId=lastLogEventId + x[0], data=x[1]) for x in elements] self._sendContent(JSON.dumps(logElements), contentType=JSON_CONTENT_TYPE)
def handle_get_runtime_log(self, jobId, lastLogEventId = 0): """ Called via an ajax-like call. Returns the new log elements for a particular job (id'd by jobId) since the lastLogElementId. If the jobId is currently registered in our current monitoring threads, returns them as XML elements Otherwise returns a null object. """ elements = self._jobMonitorManager.getEvents(jobId) if not elements: time.sleep(1) # force a wait to avoid a requery. Normally we should wait until a new event arrives instead. logElements = [ dict(eventId = lastLogEventId + x[0], data = x[1]) for x in elements ] self._sendContent(JSON.dumps(logElements), contentType = JSON_CONTENT_TYPE)
def setApplicationBody(self, body, profile = CONTENT_TYPE_JSON): """ Convenience function: encode the body, sets both Content-Encoding ad Content-Type as JSON or pickle encoding. """ if profile == self.CONTENT_TYPE_JSON: self.body = JSON.dumps(body) self.setContentEncoding(self.ENCODING_UTF8) self.setContentType(self.CONTENT_TYPE_JSON) elif profile == self.CONTENT_TYPE_PYTHON_PICKLE: self.body = pickle.dumps(body) self.setContentEncoding(self.ENCODING_NONE) self.setContentType(self.CONTENT_TYPE_PYTHON_PICKLE) elif profile == self.CONTENT_TYPE_GZIP: self.body = base64.encodestring(zlib.compress(body)) self.setContentEncoding(self.ENCODING_BASE64) self.setContentType(self.CONTENT_TYPE_GZIP) else: raise Exception("Invalid application body encoding profile (%s)" % str(profile))
def call(request): """ Process request :param request: :return: """ ret_data=None data=json.loads(request.body) if not data.has_key("path"): raise (Exception("'path' was not found in request.body")) path=data["path"] items=path.split("/"); if items.__len__()<2: raise (Exception("'path' in request.body is invalid")) mdl=None fn=None try: mdl=importlib.import_module(items[0]) except Exception as ex: raise (ex) if mdl==None: raise (Exception("'{0}' was not found".format(items[0]))) if not hasattr(mdl,items[1]): raise (Exception("'{0}' was not found in '{1}'".format(items[1],items[0]))) else: fn=getattr(mdl,items[1]) if not callable(fn): raise (Exception("'{0}' in '{1}' is not a function".format(items[1], items[0]))) from quicky import extens extens.apply(request, "", request.app) param=caller_param(request) param.language=request.LANGUAGE_CODE param.user=request.user param.app=request.app if data.has_key("view"): param.view=data["view"] if data.has_key("data"): param.data=data["data"] if fn!=None: ret_data=fn(param) ret_json=JSON.to_json(ret_data) return ret_json
def traceRoute( self, JSONmsg ): # Funcao a se usar quando recebe uma mensagem do tipo trace msg = json.loads(JSONmsg) msg["hops"].append(self.myIP) resultJSON = json.dumps(msg) if (self.myIP == msg["destination"]): dataMsg = JSON.Data(self.myIP, msg["source"], resultJSON) self.SendMsgTo( dataMsg, msg["source"] ) # Aqui eles se invertem uma vez q o ultimo trace q recebeu e chegou ao destino precisa repassar ao de origem # print("Enviar Data:",dataMsg,"para:",msg["source"]) # Enviar mensagem como data aqui else: proxServ = FuncoesApoio.GetMenorRota( self.myIP, msg["destination"], self.myRouteTable ) # retorna o proximo servidor a repassar a mensagem self.SendMsgTo( resultJSON, proxServ) # Caso nao seja o ultimo, repassar para o prox serv
def handle_get_job_info(self, jobId, lastKnownState = None): """ Called via an ajax-like call. Returns the job status, either the current one if lastKnownState is different from the current one, or subscribes and waits for a state change to return it. """ jobInfo = self._jobMonitorManager.getJobInfo(jobId, lastKnownState) result = {} if jobInfo: for (k, v) in jobInfo.items(): result[k.replace('-', '')] = v result["finished"] = (jobInfo["state"] in [ "complete", "cancelled", "killed", "error" ]) else: result = None self._sendContent(JSON.dumps(result), contentType = JSON_CONTENT_TYPE)
def setApplicationBody(self, body, profile=CONTENT_TYPE_JSON): """ Convenience function: encode the body, sets both Content-Encoding ad Content-Type as JSON or pickle encoding. """ if profile == self.CONTENT_TYPE_JSON: self.body = JSON.dumps(body) self.setContentEncoding(self.ENCODING_UTF8) self.setContentType(self.CONTENT_TYPE_JSON) elif profile == self.CONTENT_TYPE_PYTHON_PICKLE: self.body = pickle.dumps(body) self.setContentEncoding(self.ENCODING_NONE) self.setContentType(self.CONTENT_TYPE_PYTHON_PICKLE) elif profile == self.CONTENT_TYPE_GZIP: self.body = base64.encodestring(zlib.compress(body)) self.setContentEncoding(self.ENCODING_BASE64) self.setContentType(self.CONTENT_TYPE_GZIP) else: raise Exception("Invalid application body encoding profile (%s)" % str(profile))
def handle_get_job_info(self, jobId, lastKnownState=None): """ Called via an ajax-like call. Returns the job status, either the current one if lastKnownState is different from the current one, or subscribes and waits for a state change to return it. """ jobInfo = self._jobMonitorManager.getJobInfo(jobId, lastKnownState) result = {} if jobInfo: for (k, v) in jobInfo.items(): result[k.replace("-", "")] = v result["finished"] = jobInfo["state"] in ["complete", "cancelled", "killed", "error"] else: result = None self._sendContent(JSON.dumps(result), contentType=JSON_CONTENT_TYPE)
def start_message(message): data = JSON.read_from_json(users_json) if data.get(str(message.from_user.id), None) is not None: bot.send_message( message.chat.id, f'{normalize_string(message.chat.first_name)} {normalize_string(message.chat.last_name)}, а я тебя знаю уже!' ) else: create_user(data, message) bot.send_message( message.chat.id, f'Привет, {normalize_string(message.chat.first_name)} {normalize_string(message.chat.last_name)}, я тебя добавил в список гостей' ) bot.send_message( message.chat.id, 'Для этого, присылайте дедушке, что бы Вы хотели на Новый Год.') bot.send_message( message.chat.id, 'Дедушка молодой, прогрессивный, так что присылайте дедушке ссылки на ' 'подарки, так дедушке будет легче разобраться. ' 'Можете присылать по одной или несколько ссылок. Я все запишу))')
def __load(): global __prefs global __prefsPath path = "%s/Contents/DefaultPrefs.json" % Plugin.__bundlePath if os.path.exists(path): f = open(path, "r") string = f.read() f.close() __prefs = JSON.ObjectFromString(string) PMS.Log("(Framework) Loaded the default preferences file") Plugin.__callNamed("CreatePrefs", addToLog=False) if os.path.exists(__prefsPath): try: f = open(__prefsPath, "r") userPrefs = XML.ElementFromString(f.read()) f.close() for userPref in userPrefs: for pref in __prefs: if pref["id"] == userPref.tag: pref["value"] = userPref.text PMS.Log("(Framework) Loaded the user preferences file") except: PMS.Log("(Framework) Exception when reading preferences")
def save_theme(): error=False errormessage=None themename=request.form.get("name") submitter=request.form.get("submitter",None) template=request.form.get("template",None) data=request.form.get("data",None) email=request.form.get("email",None) rendered=request.form.get("rendered",None) if(not error): if(themename==None): error=True errormessage="You must enter a theme name" if(not error): recaptchallange=request.form.get("recaptcha_challenge_field") if(not error): recaptresponse=request.form.get("recaptcha_response_field") if(not error): if(submitter==None or submitter==""): error=True errormessage="Please enter your name" if(not error): if(email==None or email==""): error=True errormessage="Please enter your email" if(not error and not re.match(r"[^@]+@[^@]+\.[^@]+",email)): error=True errormessage="Please enter a valid email address" if(not error): if(data==None or data==""): error=True errormessage="The no data found" if(not error): themedata=Theme.get_by_key_name(themename) if(themedata): error=True errormessage="A theme with the same name already exist" if(not DEBUG): validation=recaptcha.submit(recaptchallange,recaptresponse,RECAPTCHA_KEY,request.remote_addr) if(not validation.is_valid): error=True errormessage="Please reenter the recaptcha." if((DEBUG or validation.is_valid) and not error): newtheme=Theme() newtheme.name=themename newtheme.submitter=submitter newtheme.email=email newtheme.data=data newtheme.counter=0 newtheme.rendered=rendered newtheme.generate_photo() newtheme.put() return 'success',200 elif(not error): return 'Something went wrong',400 else: return JSON.dumps({ "error": errormessage }),400
def processNetworkData(msg): #print("processNetworkData()::84 - Processing", msg) global lock lock.acquire() global ackCount global ballot global phaseTwoList global acceptBallot global acceptVal global acceptCountDict global sendQueue global transactions global proposingBool global initialVal global me #Load json msg and get state _json = json.loads(msg) state = _json["state"] debugSrc = _json["src"] print("SRC", debugSrc, "STATE", state) if state == "PREPARE": receivedBal = _json["ballot"] #Cannot accept smaller ballots in the future if receivedBal >= ballot: #print("processNetworkData()::111 - Responding to prepare!") ballot[0] = receivedBal[0] dest = _json["src"] _json = JSON.jsonMsg(me, dest, state="ACK", ballot=receivedBal, acceptBallot=acceptBallot, acceptVal=acceptVal) sendQueue.put(_json) #print("processNetworkData()::121 - sendQueue", list(sendQueue.queue)) #If bal smaller than myBal --> Don't respond else: lock.release() return elif state == "ACCEPT": receivedBal = _json["ballot"] receivedV = _json["x_y_coord"] #Check if we received the ballot before #if first time receiving ballot --> set ballot count to 1 #else --> increment ballot count if str(receivedBal) not in acceptCountDict.keys(): acceptCountDict[str(receivedBal)] = 1 else: acceptCountDict[str(receivedBal)] += 1 acceptCount = acceptCountDict[str(receivedBal)] if acceptCount == 1: #case (not leader) #received ballot >= currentballot number, then we "commit" to that value if receivedBal[0] >= ballot[0]: acceptBallot = receivedBal acceptVal = receivedV src = _json["src"] _json = JSON.jsonMsg(me, src, ballot=receivedBal, x_y_coord=acceptVal, state="ACCEPT") print("case: receivedBal[0] >= ballot[0] ... ballot", ballot, "x_y_coord", acceptVal) sendQueue.put(_json) lock.release() return #TODO: CHECK WHAT THIS COUNT SHOULD BE - I'M NOT ENTIRELY SURE USED TO BE 2 if acceptCount == MAJORITY: #case (leader) for dest in ipAddrs: _json = JSON.jsonMsg(me, dest, ballot=receivedBal, x_y_coord=receivedV, state="DECIDE") sendQueue.put(_json) #remove block from transaction queue #only pop if proposing own value!!!!!!!!!! #reset the value?? if (receivedV == initialVal): pass #set proposing to false proposingBool = False #We have decided the value and will append the block to the blockchain elif state == "DECIDE": # _variable indicates variable from the received JSON x_y_coord = _json["x_y_coord"] #TODO: WRITE TO FILE with open('log.paxos', 'a+') as f: f.write(x_y_coord + "\n") f.close() #reset paxos vals for next round proposingBool = False acceptBallot = [0, 0] acceptVal = "" ackCount = 0 #call paxos to see if it should run #startPaxos() elif state == "ACK": ackCount += 1 if ackCount == 2: threading.Thread(target=startTimer, args=()).start() #Received from acceptor phase I --> leader phase II receivedVal = _json["acceptVal"] receivedBal = _json["acceptBallot"] print("receivedVal", receivedVal) print("receivedBal", receivedBal) #acceptPair <-- acceptBallot , acceptval acceptPair = [receivedBal, receivedVal] phaseTwoList.append(acceptPair) #Received from majority if len(phaseTwoList) == MAJORITY: #Vars to hold highest ballot and checking flags myValChosen = True highestBal = [-1, -1] myVal = None for pair in phaseTwoList: #case acceptor node has accepted value pairVal = pair[1] if (pairVal != ""): myValChosen = False #We were not accepted as the leader. Need to restart #find highestBallot if (pair[0] > highestBal): pairBal = pair[0] highestBal = pairBal myVal = pairVal if myValChosen == True: myVal = initialVal #send accept, ballot,myVal to all print("case: len(phaseTwoList)==MAJORITY", ipAddrs) for dest in ipAddrs: _json = JSON.jsonMsg(me, dest, x_y_coord=myVal, acceptVal=myVal, ballot=ballot, state="ACCEPT") print("case: len(phaseTwoList)==MAJORITY", ballot, "x_y_coord", acceptVal) sendQueue.put(_json) elif state == "ABORT": #Reset paxos values proposingBool = False acceptBallot = [0, 0] acceptVal = "" ackCount = 0 lock.release() '''
def themes(): themelist=Theme.all() return JSON.dumps([x.simple_to_hash() for x in themelist.all()])
def sendData(source,destination,payload): udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) dest = (destination, 55151) msg = JSON.Data(source,destination,payload) udp.sendto(msg.encode(),dest)
import pandas as pd import JSON as json print(json.stringify(pd))
def _options_to_json(self, options={}): return 'null' return JSON.dumps({'bare': options.get('bare', False)})
def _options_to_json(self, options={}): return 'null' return JSON.dumps({ 'bare': options.get('bare', False) , 'literate': options.get('literate', False) })
def __run(_bundlePath): # # Initializes the framework, verifies the plug-in & extracts information, then enters a # run loop for handling requests. # global Identifier global Debug global __bundlePath global __pluginModule global __logFilePath global __requestHandlers global LastPrefix FirstRun = False random.seed() # Set up the support file paths pmsPath = "%s/Library/Application Support/Plex Media Server" % os.environ[ "HOME"] supportFilesPath = "%s/Plug-in Support" % pmsPath frameworkSupportFilesPath = "%s/Framework Support" % pmsPath logFilesPath = "%s/Library/Logs/PMS Plugin Logs" % os.environ["HOME"] # Make sure framework directories exist def checkpath(path): try: if not os.path.exists(path): os.makedirs(path) except: pass checkpath("%s/Preferences" % supportFilesPath) checkpath("%s/Databases" % supportFilesPath) checkpath(logFilesPath) checkpath(frameworkSupportFilesPath) # Set the bundle path __bundlePath = _bundlePath.rstrip('/') # Add the bundle path to the system path, including any libraries if os.path.isdir("%s/Contents" % __bundlePath): sys.path.append("%s/Contents" % __bundlePath) if os.path.isdir("%s/Contents/Libraries" % __bundlePath): sys.path.append("%s/Contents/Libraries" % __bundlePath) else: print "Couldn't find bundle directory" return None # Open the Info.plist file f = open("%s/Contents/Info.plist" % __bundlePath, "r") infoplist = XML.ElementFromString(f.read()) f.close() if infoplist is None: print "Couldn't load Info.plist file from plug-in" return # Get the plug-in identifier Identifier = infoplist.xpath( '//key[text()="CFBundleIdentifier"]//following-sibling::string/text()' )[0] if Identifier is None: print "Invalid Info.plist file in plug-in" return None # Set up the log file __logFilePath = "%s/%s.log" % (logFilesPath, Identifier) if os.path.exists(__logFilePath): if os.path.exists("%s.old" % __logFilePath): os.remove("%s.old" % __logFilePath) os.rename(__logFilePath, "%s.old" % __logFilePath) # Now we can start logging PMS.Log("(Framework) Bundle verification complete", False) # Check whether debugging is enabled try: _debug = infoplist.xpath( '//key[text()="PlexPluginDebug"]//following-sibling::string/text()' )[0] if _debug == "1": Debug = True PMS.Log("(Framework) Debugging is enabled") except: pass # Log the system encoding (set during bootstrap) PMS.Log("(Framework) Default encoding is " + sys.getdefaultencoding()) # Set up framework paths Prefs.__prefsPath = "%s/Preferences/%s.xml" % (supportFilesPath, Identifier) Data.__dataPath = "%s/Data/%s" % (supportFilesPath, Identifier) Data.__dataItemPath = "%s/DataItems" % Data.__dataPath if not os.path.isdir(Data.__dataItemPath): FirstRun = True os.makedirs(Data.__dataItemPath) Resource.__resourcePath = "%s/Contents/Resources" % __bundlePath Helper.__helperPath = "%s/Contents/Helpers" % __bundlePath Resource.__sharedResourcePath = "%s/Plug-ins/Framework.bundle/Contents/Resources/Versions/1/Resources" % pmsPath Database.__databasePath = "%s/Databases/%s.db" % (supportFilesPath, Identifier) os.chdir(Data.__dataItemPath) Locale.SetDefaultLocale() PMS.Log("(Framework) Configured framework modules") # Attempt to import the plug-in module - if debugging is enabled, don't catch exceptions if Debug: import Code as _plugin PMS.Log("(Framework) Imported plug-in module") else: try: import Code as _plugin PMS.Log("(Framework) Imported plug-in module") except ImportError: PMS.Log("(Framework) Couldn't import plug-in from bundle") __exit() return # Load the list of trusted plug-ins _trusted = [] try: _trustedJSON = Resource.LoadShared("trust.json") if _trustedJSON: _trusted = JSON.ObjectFromString(_trustedJSON) except: pass # Populate the permission lists __setupPermissionLists() # Register the plug-in with the framework __pluginModule = _plugin # Check the imported module to make sure nothing untoward is happening! if Identifier in _trusted: PMS.Log("(Framework) Plug-in is trusted, skipping module check") else: __scanModules() _allowed = [] for n in PMS.__dict__: if n[0] != "_": if type(PMS.__dict__[n]).__name__ == "module": _allowed.append(n) for n in __modWhitelist: _allowed.append(n) __checkModule(_plugin, _allowed) PMS.Log("(Framework) Checked module imports") # Initialize the framework modules Dict.__load() if not FirstRun: __checkFrameworkCompatibility() Prefs.__load() HTTP.__loadCookieJar() HTTP.__loadCache() PMS.Log("(Framework) Initialized framework modules") # Call the plug-in's Start method PMS.Log("(Framework) Attempting to start the plug-in...") __call(__pluginModule.Start) PMS.Log("(Framework) Plug-in started", False) # Start timers __startCacheManager(firstRun=FirstRun) PMS.Log("(Framework) Entering run loop") # Enter a run loop to handle requests while True: try: # Read the input path = raw_input() path = path.lstrip("GET ").strip() LastPrefix = None # Read headers headers = {} stop = False while stop == False: line = raw_input() if len(line) == 1: stop = True else: split = string.split(line.strip(), ":", maxsplit=1) if len(split) == 2: headers[split[0].strip()] = split[1].strip() # Set the locale if headers.has_key("X-Plex-Language"): loc = headers["X-Plex-Language"].lower() Locale.__loadLocale(loc) # Set the version if headers.has_key("X-Plex-Version"): Client.__setVersion(headers["X-Plex-Version"]) # Extract arguments kwargs = {} mpath = path if path.find("?") >= 0: parts = path.split("?") mpath = parts[0] args = parts[1].split("&") for arg in args: kwarg = arg.split("=") if len(kwarg) == 2: name = urllib.unquote(kwarg[0]) value = urllib.unquote(kwarg[1]) kwargs[name] = value if mpath[-1] == "/": mpath = mpath[:-1] # Split the path into components and decode. pathNouns = path.split('/') pathNouns = [urllib.unquote(p) for p in pathNouns] # If no input was given, return an error if len(pathNouns) <= 1: __return("%s\r\n\r\n" % PMS.Error['BadRequest']) # Otherwise, attempt to handle the request else: result = None pathNouns.pop(0) count = len(pathNouns) if pathNouns[-1] == "": pathNouns.pop(len(pathNouns) - 1) PMS.Log("(Framework) Handling request : %s" % path, False) # Check for a management request if pathNouns[0] == ":": result = __handlePMSRequest(pathNouns, path, **kwargs) else: handler = None isPrefixHandler = False # See if there's a prefix handler available for key in __prefixHandlers: if mpath.count(key, 0, len(key)) == 1: LastPrefix = key if mpath in __prefixHandlers: handler = __prefixHandlers[mpath]["handler"] isPrefixHandler = True else: # Check each request handler to see if it handles the current prefix popped = False for key in __requestHandlers: if handler is None: if path.count(key, 0, len(key)) == 1: # Remove the prefix from the path keyNounCount = len(key.split('/')) - 1 for i in range(keyNounCount): pathNouns.pop(0) count = count - keyNounCount # Find the request handler handler = __requestHandlers[key]["handler"] LastPrefix = key popped = True # If no path request handler was found, make sure we still pop the prefix so internal requests work for key in __prefixHandlers: if popped == False: if mpath.count(key, 0, len(key)) == 1: keyNounCount = len(key.split('/')) - 1 for i in range(keyNounCount): pathNouns.pop(0) popped = True # Check whether we should handle the request internally handled = False if count > 0: if pathNouns[0] == ":": handled = True result = __handleInternalRequest( pathNouns, path, **kwargs) # Check if the App Store has flagged the plug-in as broken if os.path.exists( os.path.join(frameworkSupportFilesPath, "%s.broken" % Identifier)): #TODO: Localise this bit, use message from the App Store if available handled = True result = PMS.Objects.MessageContainer( "Please try again later", "This plug-in is currently unavailable") PMS.Log("(Framework) Plug-in is flagged as broken") # If the request hasn't been handled, and we have a valid request handler, call it else: if not handled and handler is not None: if isPrefixHandler: result = handler(**kwargs) else: result = handler(pathNouns, path, **kwargs) # If the request wasn't handled, return an error if result == None: PMS.Log("(Framework) Request not handled by plug-in", False) response = "%s\r\n\r\n" % PMS.Error['NotFound'] # If the plugin returned an error, return it to PMS elif result in PMS.Error.values(): PMS.Log( "(Framework) Plug-in returned an error : %s" % result, False) response = "%s\r\n" % result # Otherwise, check if a valid object was returned, and return the result elif __objectManager.ObjectHasBase(result, Objects.Object): PMS.Log("(Framework) Response OK") resultStr = result.Content() resultStatus = result.Status() resultHeaders = result.Headers() if resultStr is not None: resultLen = len(resultStr) if resultLen > 0: resultHeaders += "Content-Length: %i\r\n" % resultLen resultStr = "\r\n%s" % resultStr else: resultStr = "" response = str("%s\r\n%s" % (resultStatus, resultHeaders)) + str( resultStr) + str("\r\n") __return(response) # If a KeyboardInterrupt (SIGINT) is raised, stop the plugin except KeyboardInterrupt: # Save data & exit __saveData() __exit() except EOFError: # Save data & exit __saveData() __exit() # If another exception is raised, deal with the problem except: __except() __return("%s\r\n\r\n" % PMS.Error['InternalError']) # Make sure the plugin's data is saved finally: __saveData()
def traceCommand(meuIP, ipDest): msg = JSON.Trace(meuIP, ipDest, [meuIP]) print("Enviar 1o Trace", msg)