Пример #1
0
def processDecisionTree():
    
    global area # tell Python interpreter variable area is global
    skip = False
    
    if area == 'ERROR':
        return
    
    while True:
        
        if (not skip):
            nrOfOptions = JsonParser.loadDTData(area)
    
        sentence = Processing_Audio.getAudioToText()
        sentence = Various_Functions.normalize(sentence)

        if  (
            sentence.strip() == 'antwort 1' or
            sentence.strip() == 'antwort 2' or
            sentence.strip() == 'antwort 3' or
            sentence.strip() == 'antwort 4' or
            sentence.strip() == 'antwort 5' or
            sentence.strip() == 'antwort 6' or
            sentence.strip() == 'antwort 7' or
            sentence.strip() == 'antwort 8' or
            sentence.strip() == 'antwort 9' or
            sentence.strip() == 'antwort 10' or
            sentence.strip() == 'antwort 11' or
            sentence.strip() == 'antwort 12' or
            sentence.strip() == 'antwort 13'
            ):                             
                number = [int(s) for s in sentence.strip().split() if s.isdigit()][0]
                
                if(nrOfOptions >= number):
                    skip = False
                    area = JsonParser.goToNewArea(area, number)
                    #os.system("mpg321 -q /opt/QBO/catkin_ws/src/RoboGen-QBO/scripts/Python_Projects/EmotionAudio/mp3/SoundEffect_Confirm.mp3") # Bestätigungs-Sound abspielen
                else:
                    Various_Functions.qboSpeak('Diese Antwort ist leider nicht moeglich. Bitte schau dir die letzte Frage noch einmal genau an')
                    skip = True
        else:
            Various_Functions.qboSpeak('Diese Antwort ist leider nicht moeglich. Bitte schau dir die letzte Frage noch einmal genau an')
            skip = True
        
        
        if area == 'end':
            Various_Functions.qboSpeak('Dein Dialog ist nun zu Ende! Auf Wiedersehen!')
            break
Пример #2
0
 def exec_action(self):
     parser = JsonParser.JsonParser()
     actions = parser.parse_stream(sys.stdin)
     for action in actions:
         output = self.__parse_action__(action)
         encoded_output = json.dumps(output)
         print(encoded_output)
Пример #3
0
 def read_comands(self):
     parser = JsonParser.JsonParser()
     commands = parser.parse_stream(sys.stdin)
     for command in commands:
         op_name = command['operation-name']
         func = self.command_list[op_name]
         output = func()
         print json.dumps(output)
Пример #4
0
def main():
    files = []
    for i in range(1, len(sys.argv)):
        files.append(sys.argv[i])
    parser = jp.JsonParser(files)

    # Run program normally if output args not specified.
    if not check_for_output(parser):
        display = dis.CDisplay(parser)
Пример #5
0
def find_intrusion():

    current_time = 0

    # per_time: current working packet per time
    per_time = PacketPerTime({}, current_time)

    # pet_time_interval: PacketPerInterval - last 5 PacketsPerTime
    per_time_interval = PacketsPerInterval([])

    # Brain object, packets to run on.
    brain, packets, ip_intrusions = JsonParser.json_get_brain_chunks(
        JsonParser.write_intrusion_packet_chunk)
    brain.generate_ip_country_map()

    intrusions = []

    for packet in packets:

        # translate to our object
        packet_chunk = parse(packet)

        # OR: just use packet as it is if we are running on our data set
        # packet_chunk = packet

        if packet_chunk.time == current_time:
            per_time.add_packet(packet_chunk)
            # Detector.find_new_ips([packet_chunk.sender, packet_chunk.receiver], brain.ip_set, brain.malicious_ips)
            continue

        to_update = per_time_interval.update(per_time)
        if to_update is not None:
            brain.update(to_update)

        brain_interval = brain.get_interval(current_time,
                                            PacketsPerInterval.INTERVAL)
        intrusions += Detector.detect_intrusion(brain_interval,
                                                per_time_interval,
                                                brain.ip_set,
                                                brain.malicious_ips)
        current_time += 1
        per_time = PacketPerTime({}, current_time)

    display_intrusions(intrusions, ip_intrusions)
Пример #6
0
    def __init__(self, name, x, y, standalone = None, standaloneDesc = None):

        if standalone != None and standaloneDesc != None:
            self.image = standalone
            self.desc = standaloneDesc
        else:
            parser = JsonParser.Parser()
            parser.parse("GameConfig/ItemDatabase.json")
            ss = Spritesheet.spritesheet("Sprites/Spritesheets/pixelArt.png")

            self.image = ss.image_at(tuple(parser.settings[name]["coords"]), (0, 0, 0, 0))
            self.desc = parser.settings[name]["desc"]

        self.consumable = True
        self.name = name
        self.pickedUp = False

        self.spriteImage = sprite(self.image, x, y, self.name)
        self.spriteImage.description = self.desc

        self.invSlot = ""
Пример #7
0
def LagouSpider(keyword):
    lagou_url = "http://www.lagou.com/jobs/positionAjax.json?px=default&first={tp}&kw={kw}&pn={pn}"

    # Preprocess keyword -- transfer it into utf-8 format and add it to lagou url
    kw_bytes = keyword.encode('utf-8')
    kw_bytes = str(kw_bytes).replace(r'\x', '%').replace(r' ', '')
    kw_in_url = re.sub(r'^b', '', kw_bytes)

    # count how many results by key "totalcount" << "positionResult" << "content" in json file
    page_num = 0
    first_url = lagou_url.format(tp='true', kw=kw_in_url, pn=str(page_num + 1))
    with request.urlopen(first_url) as uf:
        json_data = json.loads(
            str(uf.read(), encoding='utf-8', errors='ignore'))
        resultsCount = int(
            json_data.get('content', {}).get('positionResult',
                                             {}).get('totalCount', 0))
        print('本次搜索页面共计%d' % resultsCount)
    if resultsCount == 0:
        print("Query Keyword error or index key word error")
        return -1

    # Game is on, let's scrap
    for i in range(3):
        if i == 0:
            tp = 'true'
        else:
            tp = 'false'
        url = lagou_url.format(tp=tp, kw=kw_in_url, pn=str(i + 1))

        with request.urlopen(url) as uf:
            data = uf.read()
        try:
            totaldata = JsonParser.JsonParser(data)
        except Exception as e:
            continue
    #开始写入数据库
    print(totaldata)
    totaldata.to_excel('lagou.xls', sheet_name='sheet1')
Пример #8
0
def main():
    address = ('localhost', 8844)
    directory = os.getcwd()
    parser = JsonParser.JsonParser()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(address)
    s.listen(5)

    while True:
        print 'waiting for connection'
        (client, ip) = s.accept()
        try:
            while True:
                req = client.recv(1024)
                try:
                    parsedreq = json.loads(req)
                    print("sending " + parsedreq)
                    client.send(parsedreq + ' gotem\n')
                except:
                    client.send('not json bruh')
                    pass
        finally:
            client.close()
Пример #9
0
    # "{'a':1}"
    # '{1:1}'
    # '{true:1}'
    # '{"a":{}'
    # '{"a":-}'
    # '{"a":[,]}'
    # '{"a":.1}'
    # '{"a":+123}'
    # '{"a":"""}'
    # '{"a":"\\"}'
]

file_path = 'E:/jsonStringFile.txt'

for test_json_str in json_test:
    a1 = JsonParser.JsonParser()
    a2 = JsonParser.JsonParser()
    a3 = JsonParser.JsonParser()

    a1.load(test_json_str)
    # print a1.data
    d1 = a1.dumpDict()
    # print d1
    a2.loadDict(d1)
    a2.dumpJson(file_path)

    a3.loadJson(file_path)
    # print a3
    d3 = a3.dumpDict()
    # print d3
    assert d1 == d3, '解析错误%s:' % test_json_str
Пример #10
0
        while(undone):
            try:
                producer.send_messages(topic, msg)
                undone=False
            except LeaderNotAvailableError:
                sleep(10)
                print("LeaderNotAvailableError")
                pass

    def keyedProduce(self,topic, key, value):
        kafka=KafkaClient(self.configs["broker_list"].split(","))
        keyedProducer=KeyedProducer(kafka,async=True)
        undone=True
        while(undone):
            try:
                keyedProducer.send_messages(topic, key, value)
                undone=False
            except LeaderNotAvailableError:
                sleep(10)
                print("LeaderNotAvailableError")
                pass
            #keyedProducer.send_messages(topic, key, value)


if __name__=="main":
    args=sys.argv
    topic=args[0]
    msg=args[1]
    configs=JsonParser.parseJson("config.json")
    producer=DemoProducer(configs)
    producer.produce(topic,msg)
Пример #11
0
# -*- coding: utf-8 -*-
# Author: Bin LI ([email protected])
# All rights reserved.

# 本文件用于测试JsonParser.py

from JsonParser import *
import sys
import pdb

testcases = [
'{}',
'{"number":1}',
'{"string":"string"}',
'{"true": true}',
'{"false": false}',
'{"null": null}',
'{"array": []}',
'{"array":[1, "s" , true, false, null]}',
'{"array":[[1, 2, 3], [true, false], [null] ]}',
'{"array":[{"number":1}, {"string":"string"} ]}',
'{"object": {}}',
'{"object": {"array": [1, true, {"object": "object"}]}}'
]

print "Start testing..."
p = JsonParser()
for s in testcases:
	p.load(s)
print "End testing..."
Пример #12
0
        return list(map(lambda x: self.compile(x), ast.getAttr('items')))
      elif ast.name == 'NameValuePair':
        return (self.compile(ast.getAttr('name')), self.compile(ast.getAttr('value')))
    elif isinstance(ast, JsonToken):
      if ast.id == Parser.TERMINAL_STRING:
        return ast.string.replace('"', '')
      if ast.id == Parser.TERMINAL_NUMBER:
        return float(ast.string)
      if ast.id == Parser.TERMINAL_TRUE:
        return True
      if ast.id == Parser.TERMINAL_FALSE:
        return False
      if ast.id == Parser.TERMINAL_NULL:
        return None
    else:
      print("AST %s is not a valid type" % (ast))
      
if len(sys.argv) < 2:
  print("missing JSON file(s)")
  sys.exit(-1)

for filename in sys.argv[1:]:
  try:
    lexer = JsonLexer(open(filename).read())
    tree = JsonParser.parse( lexer, 'object' )
    compiler = JsonToPythonCompiler()
    object = compiler.compile( tree.toAst() )
    print('%s is valid JSON:\n' % filename)
    print(object)
  except Exception as e:
    print('Error:', e)
Пример #13
0
def produceDemo(configs):
    producer=ProducerDemo.DemoProducer(configs)
    keys=["CPU","MEM"]
    while(True):
        topic="computer"+str(random.randint(0,1))
        key=keys[random.randint(0,1)]
        pec=str(random.randint(0,100))
        producer.keyedProduce(topic,key,pec)
        #producer.produce(topic,pec)
        print("Produced: "+topic+"."+key+"="+pec)

def consumeDemo(configs):
    consumer=ConsumerDemo.DemoConsumer(configs)
    t1=threading.Thread(target=consumer.consume,args=("computer1",))
    t2=threading.Thread(target=consumer.consume, args=("computer0",))
    t1.start()
    t2.start()
args=sys.argv
if args[1]=="producer":
    configs=JsonParser.parseJson("producer.json")
    produceDemo(configs)
elif args[1]=="consumer":
    configs1= JsonParser.parseJson("consumer1.json")
    configs2= JsonParser.parseJson("consumer2.json")
    consumeDemo(configs1)
    consumeDemo(configs2)
elif args[1]=="ingest":
    configs=JsonParser.parseJson("producer.json")
    LogIngester.LogIngester(args[2],configs).ingest()
else:
    print("Choose a Mode, producer or consumer")
Пример #14
0
 def __init__(self):
     self.parser = JsonParser.JsonParser()
     self.card = 10
Пример #15
0
 def setUp(self):
     super(TestJsonParser,
           self).setUp(JsonParser.JsonParser(gp=mock.Mock()))
     self.tcp_server = TcpServer.TcpServer(gp=mock.Mock())
     self.tcp_server.addReceiver("JsonParser", self.test_object)
def Servers(accessKey,secretKey):
    totalAccountCost = 0
    # Generate list of servers  
    for region in boto.ec2.regions():
        if region.name != 'us-gov-west-1':            

            regionConnection = get_region_connection(region.name,accessKey,secretKey)
            reservations = regionConnection.get_all_instances()
#            print ('\n')
#            print('Region: ' + str(regionConnection).replace("EC2Connection:ec2.","") )
#
#            file2write.writelines('\n')
#            file2write.writelines('Region: ' + str(regionConnection).replace("EC2Connection:ec2.",""))
#            file2write.writelines('\n')
            
            serverTable = PrettyTable (["Server Name", "Owner/Creator","InstanceType","LaunchTime","Hours Running","Cost/Hour","Running Cost","Architecture","OS","ID","Public_dns_name","IP","State","Label"])
            serverTable = PrettyTable (["Server Name", "Owner/Creator","InstanceType","Launch Date","Cost/Hour","Running Cost"])
            serverTable.align["Server Name"] = "l"
            serverTable.padding_width = 1
            regionCost = 0
            itemCount = 0
            
            if reservations:
                #print reservations
                for reservation in reservations:
                    instance = reservation.instances
                    for instDetails in instance:
                        serverState = str(instDetails.__dict__['_state'])
                        if (serverState != 'stopped(80)' and serverState != 'terminated(48)'):
                            serverName = str(instDetails.__dict__['tags']['Name'])
                            ownerCreator = str(instDetails.__dict__['tags']['es:Owner'])
                            instanceType = str(instDetails.__dict__['instance_type'])
                            launchTime = (str(instDetails.__dict__['launch_time']).replace('T',' ')).replace ('.000Z','')
                            runningTime = str(timeRunning(launchTime))
                            imageID = str(instDetails.__dict__['image_id'])
                            architecture =  str(instDetails.__dict__['architecture'])
                            OS = str(instDetails.__dict__['platform'])
                            if (OS == "None"):
                                OS = str(instanceImagesOS(region.name,imageID,accessKey,secretKey))
#                                osOfInstance = str(instanceOS(region.name,imageID))
                            ID = str(instDetails.__dict__['id'])
                            public_dns_name = str(instDetails.__dict__['public_dns_name'])
                            IP = str(instDetails.__dict__['ip_address'])
                            state = str(instDetails.__dict__['_state']).replace('(16)','')
                            label = str(instDetails.__dict__['tags']['es:Label'])
                            regionForCosting = str(region.name)
                            running_OS = JsonParser.instanceOS(OS)
                            regionToCosting = JsonParser.regionDecoder(regionForCosting)
                            costPerHour = JsonParser.getCostPerHour(regionToCosting,running_OS.lower(),(instanceType.lower()))
                            totalRunningCost = CostCalculation.CostCalulation(int(runningTime),costPerHour)
#                            serverTable.add_row([serverName,ownerCreator,instanceType,launchTime,runningTime,costPerHour,totalRunningCost,architecture,OS,ID,public_dns_name,IP,state,label])
                            serverTable.add_row([serverName,ownerCreator,instanceType,launchTime,costPerHour,round(totalRunningCost,2)])
                            regionCost = regionCost + totalRunningCost
                            itemCount = itemCount + 1
                            #accountCost(regionCost)
#            print itemCount
            if (itemCount > 0):
                print ('\n')
                print('Region: ' + str(regionConnection).replace("EC2Connection:ec2.","") )

                file2write.writelines('\n')
                file2write.writelines('Region: ' + str(regionConnection).replace("EC2Connection:ec2.",""))
                file2write.writelines('\n')
                print serverTable
                print "Cost for region "+ str(regionConnection).replace("EC2Connection:ec2.","") + ": $" + str(round(regionCost,2))
                file2write.writelines(str(serverTable))
                file2write.writelines('\n')
                file2write.writelines("Cost for region " + str(regionConnection).replace("EC2Connection:ec2.","") + ": $" + str(round(regionCost,2)))
                file2write.writelines('\n')
            #file2write.close()
            #print "Account Cost: " + str(totalAccountCost)
            totalAccountCost = totalAccountCost + regionCost
            #print "TotalAccountCost: " + str(totalAccountCost)
    return totalAccountCost
Пример #17
0
    "east": "hero.x + hero.width >= 960",
    "north": "hero.y <= 1",
    "west": "hero.x <= 1",
    "south": "hero.y + hero.height >= 895"
}

oppDir = {"east": "west", "west": "east", "south": "north", "north": "south"}

startPositions = {
    "east": (20, 440),
    "north": (440, 800),
    "west": (930, 440),
    "south": (440, 80)
}

parser = JsonParser.Parser()
parser.parse("GameConfig/config.json")
musicActive = parser.settings['musicSettings']['music']
sfxActive = parser.settings['musicSettings']['SFX']
character = parser.settings['levelSettings']['player']
currentLevel = parser.settings['levelSettings']['starting_level']

previousLevel = 0
toExit = None

ss = Spritesheet.spritesheet("Sprites/" + character + "/character.png")
alpha = (0, 0, 0, 0)

parser.parse("Sprites/" + character + "/walkCycle.json")

charWalkCycleDown = parser.settings['Down']
Пример #18
0
def __main__():
    #Declaring variables
    global OUTPUT_FILE
    global ERROR_FILE
    current_dir = os.path.dirname(os.path.realpath(__file__))
    output_file_path = current_dir + "\getJsonString_OUTPUT_FILE.txt"
    error_file_path = current_dir + "\getJsonString_ERROR_FILE.txt"
    resp = ""

    #Open the file to write result into it
    try:
        OUTPUT_FILE = open(output_file_path, 'w', encoding='utf-8')
    except:
        Report("Cannot open file " + output_file_path + " for write")
        Finalise()

    #Open the file to write ERROR_FILEors into it
    try:
        ERROR_FILE = open(error_file_path, 'w', encoding='utf-8')
    except:
        Report("Cannot open file " + error_file_path + " for write")
        Finalise()

    #Importing support libraries
    try:
        import requests
        import base64
        import binascii
        import gzip
        import json
        import JsonParser
        #from xml2json import json2xml
    except Exception as e:
        Report("Error when importing some libs. Error message: " + str(e))
        Finalise()

    #Getting data from url request
    try:
        requests.packages.urllib3.disable_warnings()
        result = requests.get(sys.argv[1], verify=False)
        resp = result
    except Exception as e:
        Report(
            "Error when getting data from url request. Check the internet connection and URL's.\n"
            + "Error message: " + str(e))
        Finalise()

    #Deleting managed symbol '\' from received string
    result_string = result.text.replace("\\", "")

    #Decoding data from base64
    try:
        result_string = base64.b64decode(result_string)
    except Exception as e:
        Report("Error when decoding incoming data from base64 encoding.\n" +
               " Error message: " + str(e))
        Finalise()

    #Unzipping data from archive
    try:
        result_string = gzip.decompress(result_string)
    except Exception as e:
        Report("Error when unzipping data from archive.\n" +
               " Error message: " + str(e))
        Finalise()

    #Converting byte array to utf-8 string
    try:
        result_string = result_string.decode("utf-8", "ignore")
    except Exception as e:
        Report("Error when converting byte array to utf-8 string.\n" +
               " Error message: " + str(e))
        Finalise()

    #Parsing a json string to the array of items
    try:
        if sys.argv[2] == '1':
            result_dict = JsonParser.ParseUom(result_string)
        if sys.argv[2] == '2':
            result_dict = JsonParser.ParseGoodsCategories(result_string)
        if sys.argv[2] == '3':
            result_dict = JsonParser.ParseGoodsItems(result_string)
    except Exception as e:
        Report("Error when parsing json data to a text file.\n" +
               " Error message: " + str(e))
        Finalise()

    for item in result_dict:
        OUTPUT_FILE.write(str(item))
        OUTPUT_FILE.write('\n')

    #Close the file
    OUTPUT_FILE.close()
    ERROR_FILE.close()
Пример #19
0
# encoding: utf-8
__author__ = 'lgl'

import JsonParser
import unittest

encode_string_utf8 = JsonParser.encode_python_string('utf8')
encode_string_unicode = JsonParser.encode_python_string()
parse_string = JsonParser.parse_json_string

class PyTest(unittest.TestCase):
    pyjson = JsonParser.JsonParser()
    pyjson_gbk = JsonParser.JsonParser('gbk')
    load = pyjson.load
    dump = pyjson.dump
    loadJson = pyjson.loadJson
    dumpJson = pyjson.dumpJson
    loadDict = pyjson.loadDict
    dumpDict = pyjson.dumpDict
    update = pyjson.update
    dict_id = pyjson.dict_id
    # def __init__(self):
    #     self.pyjson = JsonParser()
    #     self.load = self.pyjson.load
    #     self.dump = self.pyjson.dump
    #     self.loadJson = self.pyjson.loadJson
    #     self.dumpJson = self.pyjson.dumpJson
    #     self.loadDict = self.pyjson.loadDict
Пример #20
0
 elif obj['instruction'] == 'add_note':
     result = DBHelper.insert_note(obj['userid'], obj['passwd'],
                                   obj['noteid'], obj['title'],
                                   obj['folderid'], obj['value'])
     new_conn.send(result.encode())
 elif obj['instruction'] == 'del_note':
     result = DBHelper.delete_note(obj['userid'], obj['passwd'],
                                   obj['noteid'])
     new_conn.send(result.encode())
 elif obj['instruction'] == 'sel_note':
     result = DBHelper.select_single_note(obj['userid'], obj['passwd'],
                                          obj['noteid'])
     if isinstance(result, str):
         new_conn.send(result.encode())
     else:
         new_conn.send(JsonParser.dump_single_note(result).encode())
 elif obj['instruction'] == 'up_note':
     result = DBHelper.update_note(obj['userid'], obj['passwd'],
                                   obj['noteid'], obj['title'],
                                   obj['folderid'], obj['value'])
     new_conn.send(result.encode())
 elif obj['instruction'] == 'add_folder':
     result = DBHelper.insert_folder(obj['userid'], obj['passwd'],
                                     obj['folderid'], obj['foldername'],
                                     obj['parentid'])
     new_conn.send(result.encode())
 elif obj['instruction'] == 'del_folder':
     result = DBHelper.delete_folder(obj['userid'], obj['passwd'],
                                     obj['folderid'])
     new_conn.send(result.encode())
 elif obj['instruction'] == 'up_folder':
Пример #21
0
 def __init__(self):
     self.urls = UrlManger.UrlManger()
     self.downloader = JsonDownloader.JsonDownloader()
     self.parser = JsonParser.JsonParser()
     self.outputer = JsonOutputer.JsonOutputer()