Esempio n. 1
0
    def onDrop(self, event):
        dt = event.dataTransfer

        item = dt.getData("Text")
        data = json.decode(item)
        if 'name' in data and 'age' in data:
            age = data['age']
            name = data['name']
            self.removeStyleName('dragover')
            if self.age_is_ok(age):
                self.addStudent(name, age)
                dt.dropEffect = 'copy'

                self.addStyleName('flash')

                def removeFlash(timer):
                    self.removeStyleName('flash')

                Timer(250, notify=removeFlash)
            else:
                dt.dropEffect = 'none'
                self.addMessage('student could not be added')
                # setting dropEffect to 'none' should be sufficient to notify
                # that the drop failed, but
                # we need to cheat a bit for now...
                # this is the only reason for parent id in data
                item_parent_id = data['parent']
                item_parent = self.parent.containerFromId(item_parent_id)
                item_parent.addStyleName('drop_fail')
            # prevent default allows onDragEnd to see the dropEffect we set here
        DOM.eventPreventDefault(event)
Esempio n. 2
0
def lookup_address(street, city, state, zip):
    #get the params ready for encoding
    params = {
        'street': street,
        'city': city,
        'state': state,
        'zip': zip,
        'benchmark': 'Public_AR_Current',
        'format': 'json'
    }

    #encode the params
    params = urllib.parse.urlencode(params)

    url = 'https://geocoding.geo.census.gov/geocoder/locations/address'

    #append the params to the URL
    url = url + '?' + params

    try:
        #make the request and catch if an error occurs
        json = urllib.request.urlopen(url, context=ctx).read()
    except:
        print(
            'An error occurred while looking up the address! Please check your internet connection and try again.'
        )
        exit()

    #decode the response and return the json back
    json = json.decode()
    return json
Esempio n. 3
0
 def get_payment_request(self, sum, desc="just pay!"):
     id = str(rand_data())
     resp = self.make_rpc_request(self.clightning, self.clightning_auth,
                                  "invoice", [sum, id, desc])
     data = decode(resp.text)
     data.update({'id': id, 'content': data["bolt11"]})
     return data
Esempio n. 4
0
def get(json, key):
    """Provides the element at the specified key in the given JSON.
    If the json object is a dict and the key is valid, returns that element.
    If it's a list and has an element at json[0], it calls itself with json[0]
    as its first argument (recursive).
    If it's a unicode or normal string, it returns the unicode representation.
    In all other cases, it returns an empty unicode string.

    Example:
    To access json['refseq']['protein'][0], you would write:
    get(get(get(root, 'refseq'), 'protein'), 0))

    Arguments:
    - `json`: The JSON tree to parse from
    - `node`: The top-level node to attempt to return.
    """
    result = u''
    if isinstance(json, dict):
        result = json[key] if key in json else u''
    elif isinstance(json, list):
        result = get(json[0], key) if (len(json) > 0) else u''
    elif isinstance(json, unicode):
        result = json
    elif isinstance(json, str):
        result = json.decode('utf8')
    return result
Esempio n. 5
0
 def __get_json_or_error(self, data):
     if isinstance(data, tuple):
         raise TwitterTransportError("%s: %s" % (data[0], data[1]))
     if "loads" in dir(json): # for simplejson
         return json.loads(data)
     else:
         return json.decode(data)
Esempio n. 6
0
File: DNDTest.py Progetto: Afey/pyjs
    def onDrop(self, event):
        dt = event.dataTransfer

        item = dt.getData("Text")
        data = json.decode(item)
        if 'name' in data and 'age' in data:
            age = data['age']
            name = data['name']
            self.removeStyleName('dragover')
            if self.age_is_ok(age):
                self.addStudent(name, age)
                dt.dropEffect = 'copy'

                self.addStyleName('flash')
                def removeFlash(timer):
                    self.removeStyleName('flash')

                Timer(250, notify=removeFlash)
            else:
                dt.dropEffect = 'none'
                self.addMessage('student could not be added')
                # setting dropEffect to 'none' should be sufficient to notify
                # that the drop failed, but
                # we need to cheat a bit for now...
                # this is the only reason for parent id in data
                item_parent_id = data['parent']
                item_parent = self.parent.containerFromId(item_parent_id)
                item_parent.addStyleName('drop_fail')
            # prevent default allows onDragEnd to see the dropEffect we set here
        DOM.eventPreventDefault(event)
Esempio n. 7
0
def load_friendfb(friendfbID):
    now = int(time.time())
    if if_boss(friendfbID):
        friendfb = {}
        campaign = get_boss_campaign(friendfbID)
        if campaign:
            friendfb.update(**{
                'friendfbID': friendfbID,
                'ownerID': 0,  # 发现者
                'fbID': campaign.config.fbID,
                'owner': '',
                'activists': [],
                'createtime': now,
                'remain': max(campaign.config.end - now, 0),
                'desc': campaign.config.desc,
            })
            friendfb.update(**campaign.get_boss())
    else:
        rs = convert_list_to_dict(pool.execute("HGETALL", friendfbID))
        logger.debug("%r", rs)
        if not rs:
            return rs
        friendfb = {k: decode(v) for k, v in rs.items()}
        friendfb.setdefault('friendfbID', friendfbID)
        friendfb['activists'] = load_friendfb_activists(friendfbID)
        friendfb['invitees'] = load_friendfb_invitees(friendfbID)
        logger.debug("%r", friendfb)
        friendfb['remain'] = \
            FRIENDFB_INTERVAL - (now - friendfb['createtime'])
        friendfb['hp'] = max(friendfb['hp'], 0)
    return friendfb
Esempio n. 8
0
 def to_python(self, value):
     if isinstance(value, dict):
         return value
     elif value is None or value == '':
         return Storage()
     else:
         return Storage(json.decode(value))
Esempio n. 9
0
 def format_response_data(self, data):
     # 获取 returnJSON
     return_json = json.loads(data)['returnJson']
     raw_json_data = json.decode(return_json)
     fun_data = raw_json_data['Func%s' % raw_json_data['function_id']]
     header_index = 1
     remove_header_data = fun_data[header_index:]
     return self.format_response_data_type(remove_header_data)
Esempio n. 10
0
def parse_dw(json_object):
    """Read a Myth-Weavers.com sheet and turn it into a usable representation.

    :json_object: json object from myth-weavers.com
    :returns: a Character object

    """
    import json
    return Character(json.decode(json_object)['sheetdata']['sheetdata'])
Esempio n. 11
0
def parse_dw(json_object):
    """Read a Myth-Weavers.com sheet and turn it into a usable representation.

    :json_object: json object from myth-weavers.com
    :returns: a Character object

    """
    import json
    return Character(json.decode(json_object)['sheetdata']['sheetdata'])
Esempio n. 12
0
def tobuff(type, command, json):
    #取消左右的{}
    leng = len(json.decode())
    # 将数据转化为buffer格式
    if leng <= 2:
        _str = struct.pack('iii', type, 0, command)
    else:
        _str = struct.pack('iii', type, leng, command)
    return _str
Esempio n. 13
0
def postRequest(api, authToken=None, **kwds):
  opener = urllib2.build_opener(CreatedHandler)
  data=encode(kwds)
  request = urllib2.Request(call(api, authToken))
  request.add_data(data)
  request.get_method = lambda: 'POST'
  request.add_header("Content-Type", "application/x-www-form-urlencoded")
  request.add_header("Content-Length", str(len(data)))
  response = opener.open(request)
  return decode(response.read())
Esempio n. 14
0
 def getter(path):
   url = "http://{conn_str}/{path}".format(conn_str=conn_str, path=path)
   try:
     resp = get(url)
     if not resp.ok:
       resp.raise_for_status()
     else:
       return decode(resp.content)
   except Exception as e:
     raise e
Esempio n. 15
0
    def import_json(self, file_path):
        """ import json data from a file """

        file_path = os.path.join(self.import_dir, file_path)

        with open(file_path) as fh:
            all_data = json.decode(fh.read())

        print "\nfile imported: %s" % file_path

        return (all_data, file_path)
Esempio n. 16
0
def _unicodify(json):
    """Makes all strings in the given JSON-like structure unicode."""
    if isinstance(json, str):
        return json.decode("utf-8")
    elif isinstance(json, dict):
        for name in json:
            json[name] = _unicodify(json[name])
    elif isinstance(json, list):
        for part in json:
            _unicodify(part)
    return json
Esempio n. 17
0
def get(json, key):
    result = u''
    if isinstance(json, dict):
        result = json[key] if key in json else u''
    elif isinstance(json, list):
        result = get(json[0], key) if (len(json)>0) else u''
    elif isinstance(json, unicode):
        result = json
    elif isinstance(json, str):
        result = json.decode('utf8')
    return result
Esempio n. 18
0
def _unicodify(json):
    """Makes all strings in the given JSON-like structure unicode."""
    if isinstance(json, str):
        return json.decode("utf-8")
    elif isinstance(json, dict):
        for name in json:
            json[name] = _unicodify(json[name])
    elif isinstance(json, list):
        for part in json:
            _unicodify(part)
    return json
Esempio n. 19
0
 def jsonify(self):
     toDump = {}
     for x in self.__dict__:
         if isinstance(self.__dict__[x], JsonObject):
             toDump[x] = self.__dict__[x].jsonify()
         elif isinstance(self.__dict__[x], list):
             print("list detected")
             toDump[x] = json.decode(self.jsonifyList(self.__dict__[x]))
         else:
             toDump[x] = self.__dict__[x]
     #print(toDump)
     return json.dumps(toDump)
Esempio n. 20
0
def inbox(request, username):
    messages_dict = []
    messages_inbox = message_table.find({"to": username})
    for messages in messages_inbox:
        message_map = {
            "From - ": messages["from"],
            "Title - ": messages["title"],
            "Body - ": messages["body"],
        }
        messages_dict.append(message_map)
    messages_dict = json.decode(messages_dict)
    return HttpResponse(messages_dict)
Esempio n. 21
0
def getFavourites():
    items=[]
    try:
        dbcon=database.connect(db.file)
        dbcur=dbcon.cursor()
        dbcur.execute("SELECT * FROM faves")
        faves=dbcur.fetchall()
        for a_row in faves:
            items.append(json.decode(a_row[1].encode("utf-8")))
    except:
        pass
    return items
Esempio n. 22
0
    def post(self):
        # ficx hier de json decode!
        data = request.get_json(force=True)
        key, document = json.decode(data)
        print(key, document)

        db = Database(name, max_size=50)

        db[key] = document
        db.commit()
        db.compact()
        db.close()
        return "Inserted: "+str({i: document})
    def validate_content(self, value):
        content = json.decode(value)
        if len(content) == 2:
            message = base64.b64decode(content['message'])
            signature = base64.b64decode(content['signature'])

            public_key = b64decode(self.request.user.public_key)
            public_key = rsa.PublicKey.load_pkcs1(public_key)

            if not rsa.verify(message, signature, public_key):
                raise serializers.ValidationError("User key does not match")
            return value

        raise serializers.ValidationError("Incorrectly formatted request")
Esempio n. 24
0
    def consume_stomp_message(self, message):
        from moksha.hub.reactor import reactor

        topic = message['headers'].get('destination')
        if not topic:
            log.debug("Got message without a topic: %r" % message)
            return

        # FIXME: only do this if the consumer wants it `jsonified`
        try:
            body = JSON.decode(message['body'])
        except Exception, e:
            log.warning('Cannot decode message from JSON: %s' % e)
            #body = {}
            body = message['body']
Esempio n. 25
0
    def consume_stomp_message(self, message):
        from moksha.hub.reactor import reactor

        topic = message['headers'].get('destination')
        if not topic:
            log.debug("Got message without a topic: %r" % message)
            return

        # FIXME: only do this if the consumer wants it `jsonified`
        try:
            body = JSON.decode(message['body'])
        except Exception, e:
            log.warning('Cannot decode message from JSON: %s' % e)
            #body = {}
            body = message['body']
Esempio n. 26
0
 def dequeue(cls):
     """ 将消息出队,如果队列为空,则阻塞直到有消息可弹出为止。
     
     Args:
         cls
     Time:
         O(1)
     Return:
         msg
     Raises:
         none
     """
     queue_name, encoded_msg = cls.client.brpop(cls.name())
     msg = decode(encoded_msg)
     return msg
Esempio n. 27
0
 def dequeue(cls):
     """ 将消息出队,如果队列为空,则阻塞直到有消息可弹出为止。
     
     Args:
         cls
     Time:
         O(1)
     Return:
         msg
     Raises:
         none
     """
     queue_name, encoded_msg = cls.client.brpop(cls.name())
     msg = decode(encoded_msg)
     return msg
 def on_message(ws, message):
     data = json.decode(message)
     if "sched_current" in data:
         now_play = Activity(
             type=ActivityType.listening,
             name=self.format_song(data["sched_current"]),
         )
         if client.ws:
             await client.change_presence(activity=now_play)
     elif "wserror" in data:
         raise RuntimeError("Bad user ID/API key")
     elif "wsok" in data:
         ws.send({
             "action": "check_sched_current_id",
             "sched_id": 1,
         })
Esempio n. 29
0
	def getFacebookFriends( self ):
		if self.external_accounts is None:
			return [];

		from google.appengine.api import urlfetch
		from webapp2_extras import json
		url = 'https://graph.facebook.com/me/friends?fields=name&access_token='+ self.external_accounts.token +"&locale=ja_JP"
		result = urlfetch.fetch( url )
		if result.status_code != 200:
			logging.error( "tokenが不正です。"+ result.content )
			return []
		result_obj = json.decode( result.content )

		data_list = result_obj["data"]

		return data_list;
Esempio n. 30
0
def jsonToString(json, printing = True, decoding = 'unicode-escape', separator = ' ', lmbda = lambda k: 'zzz' if k in ['title', 'subTitle'] else k, sort = True, deep = 0):
    if type(json) == bytes:
        v = fixQuotes(json.decode('utf8'))
        return '\"' + v + '\"'
    if type(json) == str:
        return '\"' + fixQuotes(json) + '\"'
    text = ''
    if type(json) is dict:
        text = '{' + separator
        keys = list(json.keys())
        for k in keys:
            json[k] = jsonToString(json[k], False, decoding, ' ', sort = sort, deep = deep+1)
        keys.sort(key=lmbda)
        for k in keys:
            strK = '' 
            strV = '' 
            if type(json[k]) is str:
                #print('I am an unicode!', json[k]) 
                strV = json[k].encode('utf-8')
            else:
                strV = json[k] 
            if type(k) is bytes:
                strK = fixQuotes(k)
            elif type(k) is str:
                strK = k.encode('utf-8')
            else:
                strK = bytes(k)
            line = ('\"' +  strK.decode('utf-8') + '\": ' + strV.decode('utf-8') + ',' + separator)
            text += line
        text = (text[:-2] if len(json) > 0 else text) + separator + '}'
    elif type(json) is list:
        if deep == 0 or (deep > 0 and sort):
            json.sort()
        text = '[' + separator
        for v in json: 
            text += jsonToString(v, False, decoding, sort = sort, deep = deep+1) + ',' + separator
        text = (text[:-2] if len(json) > 0 else text) + separator + ']'
    elif json is None:
        text += 'null'
    elif type(json) is bool:
        text += 'true' if json else 'false'
    else:
        text += str(json)
    if printing: print_(text)
    return text
Esempio n. 31
0
	def lineReceived(self, line):
		line = json.decode(line)
		uid = line["uid"]
		if uid in self.actors:
			# self.actors[uid].messages.append(line["message"])
			self.actors[uid].tags = line["tags"]
		else:
			actor = Actor()
			actor.uid = line["uid"]
			actor.listen = line["listen"]
			actor.send = send["listen"]
			actor.actortype = send["actortype"]
			actor.tags = line["tags"]
			mesage = Mesage()
			mesage.cargo = send["cargo"]
			actor.messages.append(mesage)
			
			self.actors.append(actor)
Esempio n. 32
0
    def lineReceived(self, line):
        line = json.decode(line)
        uid = line["uid"]
        if uid in self.actors:
            # self.actors[uid].messages.append(line["message"])
            self.actors[uid].tags = line["tags"]
        else:
            actor = Actor()
            actor.uid = line["uid"]
            actor.listen = line["listen"]
            actor.send = send["listen"]
            actor.actortype = send["actortype"]
            actor.tags = line["tags"]
            mesage = Mesage()
            mesage.cargo = send["cargo"]
            actor.messages.append(mesage)

            self.actors.append(actor)
Esempio n. 33
0
    def put(self):
        open(name, 'w').close()
        data = request.get_json(force=True)
        key, document = json.decode(data)

        # create array of document
        keys = [x.strip() for x in keys.split(',')]
        documents = [x.strip() for x in documents.split(',')]

        db = Database(name, max_size=50)

        # check of dit werkt
        for key, document in keys, documents:
            db[key] = document

        db.commit()
        db.compact()
        db.close()
        return 'Database successfully replaced'
Esempio n. 34
0
def requestNews(symbol):
    url = buildNewsUrl(symbol)
    print "url: ", url
    req = Request(url)
    resp = urlopen(req)
    content = resp.read()

    content_json = json.decode(content)

    #print "total news: ", content_json['total_number_of_news']

    article_json = []
    news_json = content_json['clusters']
    for cluster in news_json:
        for article in cluster:
            if article == 'a':
                article_json.extend(cluster[article])

    return article_json
    def create(self, request, format=None):

        entry = self.getEntryFromPost(request.data)

        incoming_request = {
            'source': 'HC',
            'incoming_url': request.META.get('HTTP_REFERER'),
            'payload': request.data,
            'user': entry['user']
        }

        serializer = IncomingRequestSerializer(data=incoming_request)

        if serializer.is_valid():
            serializer.save()

            entry['day'] = datetime.datetime.now().date().strftime("%Y-%m-%d")
            entry['status'] = "Open"

            try:
                headers = {
                    'Authorization': 'Token 5e971505f6901ec76bfb53c990b2ab488d2d08e6',
                    'Content-Type': 'application/json'
                }

                response = requests.post("http://hoursservice.staging.tangentmicroservices.com/api/v1/entry/", headers=headers, data=json.dumps(entry))

                if response.status_code == requests.codes.accepted:

                    hipchat_response = {"color": "green","message": "It's going to be sunny tomorrow! (yey)","notify": False,"message_format": "text"}
                    return Response(json.decode(hipchat_response), status=status.HTTP_200_OK)
                else:
                    return Response(response.text, status=status.HTTP_400_BAD_REQUEST)

            except requests.HTTPError as e:
                print ('HTTP ERROR %s occured' % e.code)
                print (e)

            except Exception as e:
                raise e

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 36
0
def build_feedparser_cache(update=False):
    """Build a feedparser cache."""
    from multiprocessing import Pool, cpu_count

    paths = []
    for path in glob('feeds/*.dat'):
        if not update and os.path.exists(path.replace('dat', 'json')):
            continue
        paths.append(path)

    parser_pool = Pool(cpu_count())
    results = []
    for path in paths:
        results.append(parser_pool.apply_async(feedparse, (path, )))
    for result in results:
        value = result.get()
        if value is None: continue
        path, json = value
        json = json.decode('base64')
        update_cache(path, json)
Esempio n. 37
0
def add_rank(p, fbID, friendfbID, damage):
    key = "%s_ranklist" % friendfbID
    with pool.ctx() as conn:
        info = conn.execute("HGET", key, p.entityID)
    if not info:
        info = {
            'entityID': p.entityID,
            'name': p.name,
            'damage': damage,
            'prototypeID': p.prototypeID,
            "borderID": p.borderID,
            "faction_name": p.faction_name,
            "level": p.level,
        }
    else:
        info = decode(info)
        info["damage"] += damage
    if info["damage"] > p.friendfb_damages.get(fbID, 0):
        p.friendfb_damages[fbID] = info["damage"]
    with pool.ctx() as conn:
        return conn.execute("HSET", key, p.entityID, encode(info))
Esempio n. 38
0
    def recv(self, topic, payload, qos, retain):
        data = decode(payload)
        value = data["value"]

        _LOGGER.debug(f"Received message on topic: {topic} {data['value']}")

        # parse serial topic
        if re.search("^N/[0-9a-f]+/system/0/Serial$", topic):
            self.__on_serial(value)

        # parse auto discovery topics
        match = re.search(rf"^N/{self.serial}/(.+?)/[0-9]+/DeviceInstance$",
                          topic)
        if match:
            self.__on_device(match.group(1), value)

        # parse state messages
        match = re.search(rf"^N/{self.serial}/(.+?)/([0-9]+)/(.+)$", topic)
        if match:
            self.__on_state(match.group(1), match.group(2), match.group(3),
                            value)
    def __call__(self):
        """Reads notifications from stdin and triggers replication"""

        options = self.options
        wait_counter = time.time()

        while True:
            # non-blocking readline(), raises IOErrors
            fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK)

            try:
                line = sys.stdin.readline()

                # poor man's validation. If we get garbage, we sys.exit
                if not line.endswith('}\n'):
                    sys.exit(0)
                note = json.decode(line)

                log.debug('Received %r', note)

                # we don't care for deletes
                if note['type'] == 'delete' and not options.ignore_deletes:
                    continue

                self.databases.append((note['type'], note['db']))

                # if there are more docs that we want to batch, flush
                if len(self.databases) >= int(options.batch_threshold):
                    self.sync_databases()
                    continue

            except IOError:
                # if we waited longer that we want to wait, flush
                if (time.time() - wait_counter) > int(options.wait_threshold):
                    self.sync_databases()
                    wait_counter = time.time()

                time.sleep(float(options.wait_threshold))
Esempio n. 40
0
def constantly_pay(wallet, server_addr, myid):
    addr = server_addr + "/should_pay/" + myid
    print(addr)
    all_paid = 0
    while is_running:
        try:
            res = get(addr)
            if res.status_code != 200:
                print("error: " + str(res.status_code) + res.text)
                break
            req = res.text
            if req and len(req) > 10:
                resp = wallet.pay(req)
                try:
                    res = decode(resp)
                    c = int(res["result"]["msatoshi"])
                    all_paid += c
                    print("\r" + str(c) + "\t\ttotal paid: " + str(all_paid),
                          end="")
                except Exception as e:
                    print("pay failed " + str(e))
        except Exception as e:
            print("failed to pay! " + addr + str(e))
        ev.wait(10)
Esempio n. 41
0
 def __get_json__(self):
   json = urllib2.urlopen(self.url).read()
   return json.decode("utf-8")
Esempio n. 42
0
def parse(path,filepath,con,args,config):
	pagecon=con
	try:
		f=open(os.path.join(os.path.dirname(filepath),"WEB-INF","info.json"))
		servlets=json.decode(f.read())
		name=path[-1]
		arr=name.split(".")
		ext=arr[-1]
		for servlet in servlets:
			if servlet["ext"]==ext or servlet["all"]:
				svt=open(os.path.join(os.path.dirname(filepath),"WEB-INF",servlet["file"]))
				code=svt.read()
				svt.close()
				f.close()
				oldout=sys.stdout
				tmp=tempfile.mkstemp(dir=config["tmp"])
				sys.stdout=open(tmp[1],'w')
				safeeval(code,Request(path=path,filepath=filepath,contents=con,args=args,config=config))
				sys.stdout.close()
				sys.stdout=oldout
				f=open(tmp[1])
				stuff=f.read()
				f.close()
				os.remove(tmp[1])
				return stuff
			
		
		f.close()
	except IOError: pass
	if con.find("#python script")==0:
		oldout=sys.stdout
		tmp=tempfile.mkstemp(dir=config["tmp"])
		sys.stdout=open(tmp[1],'w')
		safeeval(con,Request(path=path,filepath=filepath,con=con,args=args,config=config))#os.popen("%s '%s'"%(config["python"],filepath)).read()
		sys.stdout.close()
		sys.stdout=oldout
		f=open(tmp[1])
		stuff=f.read()
		f.close()
		os.remove(tmp[1])
		return stuff
	elif con.find("//java script")==0:
		jcachedir=os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),config["java"]["cachedir"])
		at2=path
		at2[-1]=at2[-1].replace(".java",".class")
		try:
			open(os.path.join(jcachedir,",".join(at2))).close()
		except IOError:
			comp=os.popen("%s '%s' -d '%s'"%(config["java"]["javac"],filepath,jcachedir))
			err=comp.read()
			if comp.close():
				raise cherrypy.HTTPError(500,err)
			
		
		#os.rename(os.path.join(jcachedir,path[-1]),os.path.join(jcachedir,",".join(path)))
		arr=path
		arr[-1]=arr[-1].replace(".java","")
		print os.path.join(jcachedir,path[-1].replace(".java","").replace(".class",""))#DEBUG
		os.rename(os.path.join(jcachedir,path[-1].replace(".java","").replace(".class","")),os.path.join(jcachedir,",".join(at2))+".class")
		pagecon=os.popen("%s '%s'"%(config["java"]["java"],os.path.join(jcachedir,",".join(arr))))
		if not config["java"]["cacheon"]:
			os.remove(os.path.join(jcachedir,",".join(path)))
		
	elif con.find("#shell script")==0:
		f=open(filepath)
		code=f.read()
		prefix=""
		f.close()
		fp=tempfile.mkstemp(dir=config["tmp"])[1]
		tmps=[fp]
		fp_tmp=""
		f_tmp=None
		for arg in args:
			fp_tmp=tempfile.mkstemp(dir=config["tmp"])[1]
			f_tmp=open(fp_tmp,'w')
			f_tmp.write(args[arg])
			f_tmp.close()
			tmps.append(fp_tmp)
			prefix=prefix+"$%s=`cat '%s'`\n"%(arg,fp_tmp)
		
		f=open(fp,'w')
		f.write("%s\n%s"%(prefix,code))
		f.close()
		cde=os.popen("%s '%s'"%(config["sh"],fp)).read()
		for tmp in tmps: os.remove(tmp)
		return cde
	
	return pagecon
Esempio n. 43
0
	def request (self, data):

		# Check JSON syntax.
		try: request = decode(data)
		except: return self.makeError('Request is not JSON')

		# Check sender.
		try: client = request[FROM]
		except: return self.makeError('No "' + FROM + '" value')

		# Check command.
		try:
			command = request[COMMAND]

			if command == 'addRealHost':
				name = request[NAME]
				ip = request[IP]
				mac = request[MAC]
				latitude = float(request[LATITUDE])
				longitude = float(request[LONGITUDE])
				available = bool(request[AVAILABLE])
				self.realHosts[name] = {
					IP: ip,
					MAC: mac,
					LATITUDE: latitude,
					LONGITUDE: longitude,
					AVAILABLE: available
				}
				return self.makeConfirmation('Real host added', client)

			elif command == 'addVirtualHost':
				name = request[NAME]
				ip = request[IP]
				mac = request[MAC]
				available = bool(request[AVAILABLE])
				self.virtualHosts[name] = {
					IP: ip,
					MAC: mac,
					AVAILABLE: available
				}
				return self.makeConfirmation('Virtual host added', client)

			elif command == 'removeRealHost':
				name = request[NAME]
				if name not in self.realHosts:
					return self.makeError('Invalid host', client)
				del self.realHosts[name]
				return self.makeConfirmation('Real host removed', client)

			elif command == 'removeVirtualHost':
				name = request[NAME]
				if name not in self.virtualHosts:
					return self.makeError('Invalid host', client)
				del self.virtualHosts[name]
				return self.makeConfirmation('Virtual host removed', client)

			elif command == 'getRealHosts':
				hostList = []
				for host in self.realHosts:
					name = host
					ip = self.realHosts[host][IP]
					mac = self.realHosts[host][MAC]
					latitude = self.realHosts[host][LATITUDE]
					longitude = self.realHosts[host][LONGITUDE]
					available = self.realHosts[host][AVAILABLE]
					hostList.append({
						NAME: name,
						IP: ip,
						MAC: mac,
						LATITUDE: latitude,
						LONGITUDE: longitude,
						AVAILABLE: available
					})
				return encode({TO: client, REAL_HOSTS: hostList})

			elif command == 'getVirtualHosts':
				hostList = []
				for host in self.virtualHosts:
					name = host
					ip = self.virtualHosts[host][IP]
					mac = self.virtualHosts[host][MAC]
					available = self.virtualHosts[host][AVAILABLE]
					hostList.append({
						NAME: name,
						IP: ip,
						MAC: mac,
						AVAILABLE: available
					})
				return encode({TO: client, VIRTUAL_HOSTS: hostList})

			elif command == 'setRealHostAvailability':
				name = request[NAME]
				if name not in self.realHosts:
					return self.makeError('Invalid host', client)
				available = request[AVAILABLE]
				self.realHosts[name][AVAILABLE] = available
				return self.makeConfirmation('Availability set', client)

			elif command == 'setVirtualHostAvailability':
				name = request[NAME]
				if name not in self.virtualHosts:
					return self.makeError('Invalid host', client)
				available = request[AVAILABLE]
				self.virtualHosts[name][AVAILABLE] = available
				return self.makeConfirmation('Availability set', client)

			else:
				raise ValueError

		except (KeyError, ValueError):
			return self.makeError('Invalid command', client)

		except:
			return self.makeError('Unexpected error', client)
Esempio n. 44
0
def json_decode(data):
    return json.decode(data)
Esempio n. 45
0
#-*- coding:utf-8 -*-

import json
from youtube_search import YoutubeSearch
import requests
            
url='https://raider.io/api/v1/characters/profile?region=kr&realm=불타는 군단&name=왕츤츤&fields=gear%2Cmythic_plus_weekly_highest_level_runs%2Cmythic_plus_best_runs%2Cguild'
r=requests.get(url)
r=json.decode(r)

print(r)

q='미려적신화 조매력'
res = YoutubeSearch(q, max_results=1).to_json()
res=res.replace('\\','')
d=json.loads(res)
e=res.json()
print(d)
print(e)
Esempio n. 46
0
try:
    from sqlite3 import dbapi2 as database
except:
    from pysqlite2 import dbapi2 as database

import json, os.path
import xbmc, xbmcaddon

ADDON_ID='plugin.video.javstream2'
addon = xbmcaddon.Addon(id=ADDON_ID)
profileDir = addon.getAddonInfo('profile')
profileDir = xbmc.translatePath(profileDir).decode("utf-8")
dbFile = os.path.join(profileDir, 'database.db')  

try:
    dbcon=database.connect(db.file)
    dbcur=dbcon.cursor()
    dbcur.execute("SELECT * FROM faves")
    faves=dbcur.fetchall()
    for a_row in faves:
        items.append(json.decode(a_row[1].encode("utf-8")))
except:
    pass
Esempio n. 47
0
 def __deserialize(self, json):
     content = json.loads(json.decode('utf-8'))
     return content
Esempio n. 48
0
 def json(self):
     """returns JSON string containing all EXIF tags and values from exiftool"""
     json, _, _ = self.run_commands("-json")
     json = unescape_str(json.decode("utf-8"))
     return json
Esempio n. 49
0
 def _parse_json(self, response):
     return json.decode(response)
rootNode.cmd("service network-manager restart")

print "Linking root namespace to switch ..."
rootLink = virtualNetwork.addLink(rootNode, switch)
rootLink.intf1.setIP("10.254", "8")

print
raw_input("Please connect Android devices now. Press Enter when done: ")
print

print "Getting list of real hosts ..."
realHostRequestJSON = encode({"from": "root", "command": "getRealHosts"})
realHostRequestCommand = TCP_REQUEST_COMMAND + "'" + realHostRequestJSON + "'"
realHostResponse = rootNode.cmd(realHostRequestCommand).strip()
# print "realHostResponse:", realHostResponse
realHosts = decode(realHostResponse)["realHosts"]

print "Adding virtual hosts to Mininet based on real hosts"
i = 0
for host in realHosts:
    i += 1
    hostName = "h" + str(i)
    print " Creating virtual host for", hostName, "..."
    numberOfCpuCores = 1
    cpuUsageFraction = 1.0 / len(realHosts)
    virtualIP = "10.0.0." + str(i)
    virtualHost = virtualNetwork.addHost(name=hostName,
                                         core=numberOfCpuCores,
                                         cpu=cpuUsageFraction,
                                         ip=virtualIP)
    virtualNetwork.addLink(node1=virtualHost, node2=switch)
Esempio n. 51
0
    def request(self, data):

        # Check JSON syntax.
        try:
            request = decode(data)
        except:
            return self.makeError('Request is not JSON')

        # Check sender.
        try:
            client = request[FROM]
        except:
            return self.makeError('No "' + FROM + '" value')

        # Check command.
        try:
            command = request[COMMAND]

            if command == 'addRealHost':
                name = request[NAME]
                ip = request[IP]
                mac = request[MAC]
                latitude = float(request[LATITUDE])
                longitude = float(request[LONGITUDE])
                available = bool(request[AVAILABLE])
                self.realHosts[name] = {
                    IP: ip,
                    MAC: mac,
                    LATITUDE: latitude,
                    LONGITUDE: longitude,
                    AVAILABLE: available
                }
                return self.makeConfirmation('Real host added', client)

            elif command == 'addVirtualHost':
                name = request[NAME]
                ip = request[IP]
                mac = request[MAC]
                available = bool(request[AVAILABLE])
                self.virtualHosts[name] = {
                    IP: ip,
                    MAC: mac,
                    AVAILABLE: available
                }
                return self.makeConfirmation('Virtual host added', client)

            elif command == 'removeRealHost':
                name = request[NAME]
                if name not in self.realHosts:
                    return self.makeError('Invalid host', client)
                del self.realHosts[name]
                return self.makeConfirmation('Real host removed', client)

            elif command == 'removeVirtualHost':
                name = request[NAME]
                if name not in self.virtualHosts:
                    return self.makeError('Invalid host', client)
                del self.virtualHosts[name]
                return self.makeConfirmation('Virtual host removed', client)

            elif command == 'getRealHosts':
                hostList = []
                for host in self.realHosts:
                    name = host
                    ip = self.realHosts[host][IP]
                    mac = self.realHosts[host][MAC]
                    latitude = self.realHosts[host][LATITUDE]
                    longitude = self.realHosts[host][LONGITUDE]
                    available = self.realHosts[host][AVAILABLE]
                    hostList.append({
                        NAME: name,
                        IP: ip,
                        MAC: mac,
                        LATITUDE: latitude,
                        LONGITUDE: longitude,
                        AVAILABLE: available
                    })
                return encode({TO: client, REAL_HOSTS: hostList})

            elif command == 'getVirtualHosts':
                hostList = []
                for host in self.virtualHosts:
                    name = host
                    ip = self.virtualHosts[host][IP]
                    mac = self.virtualHosts[host][MAC]
                    available = self.virtualHosts[host][AVAILABLE]
                    hostList.append({
                        NAME: name,
                        IP: ip,
                        MAC: mac,
                        AVAILABLE: available
                    })
                return encode({TO: client, VIRTUAL_HOSTS: hostList})

            elif command == 'setRealHostAvailability':
                name = request[NAME]
                if name not in self.realHosts:
                    return self.makeError('Invalid host', client)
                available = request[AVAILABLE]
                self.realHosts[name][AVAILABLE] = available
                return self.makeConfirmation('Availability set', client)

            elif command == 'setVirtualHostAvailability':
                name = request[NAME]
                if name not in self.virtualHosts:
                    return self.makeError('Invalid host', client)
                available = request[AVAILABLE]
                self.virtualHosts[name][AVAILABLE] = available
                return self.makeConfirmation('Availability set', client)

            else:
                raise ValueError

        except (KeyError, ValueError):
            return self.makeError('Invalid command', client)

        except:
            return self.makeError('Unexpected error', client)
Esempio n. 52
0
 def _get_props(self):
     props = bdb.get(self._props_db_key) or ''
     props = props and decode(props) or {}
     return props
Esempio n. 53
0
 def _getPersons(self):
     from MaKaC.services.interface.rpc import json
     allowedUsersDict = json.decode(self._params.get("allowedUsers") or "[]") or []
     return UserListModificationBase.retrieveUsers({"userList": allowedUsersDict})[0] if allowedUsersDict else []
Esempio n. 54
0
def postRequestJSON(api, **kwds):
  data = urllib.urlencode(kwds)
  response = urllib2.urlopen(call(api), data)
  return decode(response.read())
Esempio n. 55
0
                  "--server",
                  dest="server",
                  help="server to use",
                  default=None)
(options, args) = parser.parse_args()

config = ConfigParser()
config.read(options.config_file)

wallet = remote_wallet(config["wallet"])
ovpn_conf = None
myid = str(rand_data())
if options.server:
    ovpn_conf = get(options.server + "/generateNewClient/" + myid).text
    base_addr = options.server
servers = decode(get(config['netninja']['server'] + "/get_servers/2").text)
while not ovpn_conf:
    for server in servers:
        base_addr = "http://" + server
        addr = ""
        try:
            addr = base_addr + "/generateNewClient/" + myid
            resp = get(addr)
            if resp.status_code != 200:
                continue
            if len(resp.text) > 1000 and resp.text.startswith("client"):
                ovpn_conf = resp.text
            # else:
            #     addr = base_addr + "/download/" + myid + ".ovpn"
            #     ovpn_conf = get(addr).text
            # break
Esempio n. 56
0
 def decode(str):
     t, n = json.decode(str)
     return (VisitStat(t, n))
Esempio n. 57
0
        got_error = False
        for button in BUTTONS:
            button_config = pj.config.GetButtonConfiguration(button)
            config['button'][button] = button_config.get('data')

    if args.dump:
        if args.verbose:
            pprint(config)
        print(json.dumps(config))

    if args.load:
        encoded_settings = ''
        for line in fileinput.input():
            encoded_settings = encoded_settings + line.rstrip()
        ns = json.decode(encoded_settings)

        # Address has to be set first
        for i, addr in enumerate(['i2c_addr', 'i2c_addr_rtc']):
            if config['general'][addr] != ns['general'][addr]:
                value = config['general'][addr]
                try:
                    new_value = int(str(ns['general'][addr]), 16)
                    if new_value >= 8 and new_value <= 0x77:
                        value = ns['general'][addr]
                except:
                    pass
                pj.config.SetAddress(i + 1, value)

        if config['general']['run_pin'] != ns['general']['run_pin']:
            pj.config.SetRunPinConfig(RUN_PIN_VALUES[ns['general']['run_pin']])