def deserialize(self,buffer):

        reader=Reader()

        self.questype = reader.readByte(buffer)#print("questype = {0}".format(self.questype))

        self.mapid = math.floor(reader.readDouble(buffer))#print("mapid = {0}".format(self.mapid))

        self.knownStepsListLen = reader.readUnsignedShort(buffer)#print("knownStepsListLen = {0}".format(self.knownStepsListLen))

        for x in range(0, self.knownStepsListLen):
            typeindice = reader.readUnsignedShort(buffer)
            direction = reader.readByte(buffer)
            indice = reader.readVarShort(buffer)
            liste = [typeindice,direction,indice]
            self.liste1.append(liste)
        #print(self.liste1)
        if(typeindice != 462):
            self.totalStepCount = reader.readByte(buffer)#print("totalStepCount = {0}".format(self.totalStepCount))

            self.checkPointCurrent = reader.readVarUhInt(buffer)#print("checkPointCurrent = {0}".format(self.checkPointCurrent))

            self.checkPointTotal = reader.readVarUhInt(buffer)#print("checkPointTotal = {0}".format(self.checkPointTotal))

            self.availableRetryCount = reader.readInt(buffer)#print("availableRetryCount = {0}".format(self.availableRetryCount))

            self.flagsLen = reader.readUnsignedShort(buffer)#print("flagsLen = {0}".format(self.flagsLen))

            for x in range(0, self.flagsLen):
                self.liste2.append(math.floor(reader.readDouble(buffer)))
                self.liste3.append(reader.readByte(buffer))
 def parse_reviews(self, reviews):
     # tokenize each review, add to each review obj IN PLACE
     for obj in reviews:
         obj['tokens'] = Reader().tokens(obj['review'])
         obj['bigrams'] = list(nltk.bigrams(obj['tokens']))
         obj['trigrams'] = list(nltk.trigrams(obj['tokens']))
     return reviews
Example #3
0
 def __init__(self, path):
     read_calendars = Reader(path / "calendar.txt")
     self.calendars_list = defaultdict(list)
     line = read_calendars.get_line()
     while line:
         service = Calendar(line)
         service_info = {
             "start": service.start_date,
             "end": service.end_date,
             "id": service.service_id
         }
         if service.mon == "1":
             self.calendars_list["monday"].append(service_info)
         if service.tues == "1":
             self.calendars_list["tuesday"].append(service_info)
         if service.wed == "1":
             self.calendars_list["wednesday"].append(service_info)
         if service.thurs == "1":
             self.calendars_list["thursday"].append(service_info)
         if service.fri == "1":
             self.calendars_list["friday"].append(service_info)
         if service.sat == "1":
             self.calendars_list["saturday"].append(service_info)
         if service.sun == "1":
             self.calendars_list["sunday"].append(service_info)
         line = read_calendars.get_line()
     read_calendars.end()
Example #4
0
def main():

    # 标签文件路径
    LABEL_DIR = '/Users/jellyfive/Desktop/实验/Dataset/BuildingData/training/label_2'
    IMAGE_DIR = '/Users/jellyfive/Desktop/实验/Dataset/BuildingData/training/image_2'
    CALIB_DIR = '/Users/jellyfive/Desktop/实验/Dataset/BuildingData/training/calib'

    # 读取标签文件
    label_reader = Reader(IMAGE_DIR, LABEL_DIR, CALIB_DIR)
    show_indices = label_reader.indices

    for index in show_indices:
        data_label = label_reader.data[index]

        proj_matrix = data_label['camera_to_image']
        image = Image.open(data_label['image_path'])

        for tracklet in data_label['tracklets']:
            bbox, dim, loc, r_x, r_y, r_z = [
                tracklet['bbox'], tracklet['dimensions'], tracklet['location'],
                tracklet['rotation_x'], tracklet['rotation_y'],
                tracklet['rotation_z']
            ]

            # 画图
            draw(image, bbox, proj_matrix, dim, loc, loc, r_x, r_y, r_z, r_x,
                 r_y, r_z)

        # plt.show()
        plt.savefig(
            '/Users/jellyfive/Desktop/实验/3D-pose-estimation--translation/output_6/{}_proj'
            .format(index))
Example #5
0
    def __init__(self):
        self.clearScreen()
        self.theConnection = None
        self.readThe = Reader().theReader

        try:
            theUser = input(">>Enter the username:\n")
            self.clearScreen()
            thePassword = getpass.getpass(
                ">>Password for {}: ".format(theUser))
            self.clearScreen()

            theServer = self.readThe['server']
            thePort = self.readThe['port']
            theDriver = self.readThe['driver']

            theDBName = input(">>Enter the database you want to connect to:\n")
            self.clearScreen()
            if theDBName == " " or "":
                theDBName = self.readThe['defaultDB']
            theConnectionString = "DRIVER={};SERVER={};PORT={};DATABASE={};UID={};PWD={}".format(
                theDriver, theServer, thePort, theDBName, theUser, thePassword)
            self.theConnection = pyodbc.connect(theConnectionString,
                                                autocommit=True)
            print(theConnectionString)
            self.theCursor = self.theConnection.cursor()
            self.chooseTheOption()
        except (Exception, pyodbc.DatabaseError) as error:
            print("Something happened")
            print(self.formatTheError(error))
            sys.exit()
Example #6
0
def serializing():
    #f3 = open('', 'wb');
    new_reader = Reader('Sergey', 'K.', 18)
    #f3.write(library2.pickle)
    pickle.dump(new_reader,
                open('C:\EX4serializing.pkl', 'wb'),
                protocol=pickle.HIGHEST_PROTOCOL)
Example #7
0
    def run_hr_monitor(self):
        """ The heart of the program. This function runs the while loop that calls all other classes that are part of
        this assignment. It calls the classes that read the data in, find the instant heart rate, and find the average
        heart rates.
        Calls the method to destroy the display and finish running the script.
        """
        reader = Reader(self.data_filename, self.update_time_seconds,
                        self.data_bit_length)
        beat_detector = BeatDetector(self.update_time_seconds,
                                     self.signal_choice)
        processor_hr = HRProcessor(self.update_time_seconds, self.tachycardia,
                                   self.bradycardia, self.multi_min_avg_1,
                                   self.multi_min_avg_2)

        [data_array_ecg, data_array_ppg] = reader.get_next_data_instant()
        while reader.still_reading():
            instant_hr = beat_detector.find_instant_hr(data_array_ecg,
                                                       data_array_ppg)
            visualization_info = processor_hr.add_inst_hr(
                instant_hr, self.time_passed_string)
            self.render_information_display(visualization_info)
            [data_array_ecg, data_array_ppg] = reader.get_next_data_instant()
            time.sleep(self.seconds_between_readings)

        print("DONE")
        self.clean_up()
Example #8
0
    def __init__(self,
                 ParrentScreenManager,
                 Data_Source,
                 Doc_Source,
                 Scroll_TargetHeight="Bottom"):
        if Scroll_TargetHeight == "Bottom":
            Screen.__init__(self, name='Scr_View_Hidden')
        else:
            Screen.__init__(self, name='Scr_View')

        self.ParrentScreenManager = ParrentScreenManager
        self.Data_Source = Data_Source
        self.Doc_Source = Doc_Source

        #Reader         ########################
        self.Reader = Reader(
            Doc_Source=self.Doc_Source,
            Scroll_TargetHeight=Scroll_TargetHeight,
            on_DoubleClick=self.ParrentScreenManager.Swich_Screen)
        self.Reader.Update()

        #Slider         ########################
        self.View_Slider = View_Slider(self.Data_Source, self.Reader.Update)

        self.Layout = BoxLayout(orientation='vertical')
        self.Layout.add_widget(self.Reader)
        self.Layout.add_widget(self.View_Slider)

        self.add_widget(self.Layout)
        #绑定事件
        self.bind(on_pre_enter=self.on_pre_enter)
Example #9
0
 def _parse_config_file(self, file_name):
     lines = Reader(file_name, 100).lines
     # Checks if read of config file was successful
     if lines:
         # Array of attribute names for below Loop.
         array = [
             "left_bracket", "right_bracket", "op_not", "op_and", "op_or",
             "op_xor", "implies", "bicondition", "initial_fact", "query",
             "implies_sub", "bicondition_sub", "max_lines"
         ]
         # Loop through parsed config, to overwrite default config.
         for line in lines:
             # Remove comment and new line
             line = line.replace("\n", "").split("#")[0]
             # Check for 'set' keyword
             if line.count("set "):
                 line = line.split("set")[1]
             else:
                 line = ""
             # Remove white spaces and tabs
             line = line.replace(" ", "").replace("\t", "")
             # Loops through array of attribute names
             for x in array:
                 # Checks if modification attribute is valid.
                 tmp = self._match_attr(line, x)
                 # Checks if line contains only "value", sets attribute
                 if line != tmp and self._is_value_valid(array, x, tmp):
                     setattr(self, x, tmp)
         self.max_lines = int(self.max_lines)
Example #10
0
def generate_rete(filename):
    rule_processor = RuleProcessor()
    reader = Reader(filename, rule_processor, 1)
    rule_processor.reader = reader
    reader.read_clips_command()
    buffer = \
        "from graphviz import Digraph\n" + \
        "from pyknow import *\n" + \
        "import os\n\n"
    buffer += rule_processor.facts_classes
    buffer += "class Engine(KnowledgeEngine):\n"
    buffer += rule_processor.rules
    buffer += "engine=Engine()\n"
    buffer += "engine.reset()\n"
    buffer += rule_processor.facts
    buffer += "graph=engine.matcher.print_network()\n"
    buffer += "fd=open(\"graph.vd\",\"w\")\n"
    buffer += "fd.write(graph)\n"
    buffer += "dirpath = os.getcwd()\n"
    buffer += "graph_path = dirpath +"
    buffer += '"\\graph.vd"\n'
    buffer += "output_path = dirpath +"
    buffer += '"\\graph.png"\n'

    ################  create examples ##############
    #buffer += '"\\example1.png"\n'
    #buffer += '"\\example2.png"\n'

    buffer += "command_to_execute=\"dot -T png \"+graph_path +\" -o \"+output_path\n"
    buffer += "os.popen(command_to_execute)\n"
    fd = open("result_script.py", "w")
    fd.write(buffer)
    dirpath = os.getcwd()
    command_to_execute = "py " + dirpath + "\\result_script.py"
    os.popen(command_to_execute)
def test_get_next_data_instant():
    for filename in filename_list:
        my_reader = Reader(filename)  # opens up a new instance of the Reader
        [array_1, array_2] = my_reader.get_next_data_instant()
        assert len(array_1) == len(array_2)

        assert array_1 == array_2
def main():
    reader = Reader()
    reader._init_("mediumF.txt")
    net = reader.readNetwork()

    gaParam = {"popSize": 500, "noGen": 500}
    problParam = {
        'function': roadValue,
        'noNodes': net['noNodes'],
        'net': net['mat']
    }

    ga = GA(gaParam, problParam)
    ga.initialisation()
    ga.evaluation()

    stop = False
    g = -1
    solutions = []

    while not stop and g < gaParam['noGen']:
        g += 1
        ga.oneGenerationElitism()
        bestChromo = ga.bestChromosome()
        solutions.append(bestChromo)
        print('Best solution in generation ' + str(g) + ' is: x = ' +
              str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness))

    heapify(solutions)
    print(str(solutions[0]))
Example #13
0
 def __init__(self, path):
     read_trips = Reader(path / "trips.txt")
     self.trip_list = []
     line = read_trips.get_line()
     while line:
         self.trip_list.append(Trip(line))
         line = read_trips.get_line()
     read_trips.end()
Example #14
0
def createValidIDs():
    #add more IDs if necessary
    IDs = set()
    IDs.add("062301632603431110")

    reader_ = Reader(IDs)

    return reader_
Example #15
0
def main(argv):

    rd = Reader() 
    ev = Evaluator()
    pr = Printer()
    program = rd.read(argv[1])
    pr.prnt(program)
    value = ev.eval(program)
    pr.prnt(value)
    def deserialize(self,buffer):

        reader=Reader()
        print("84 is here")
        self.questype = reader.readByte(buffer)
        print("questype = {0}".format(self.questype))

        self.result = reader.readByte(buffer)
        print("result = {0}".format(self.result))
Example #17
0
 def __init__(self, path, trips):
     read_stop_codes = Reader(path / "stops.txt")
     line = read_stop_codes.get_line()
     self.stop_codes = {}
     while line:
         stop = StopCode(line, trips)
         self.stop_codes[stop.stop_id] = stop
         line = read_stop_codes.get_line()
     read_stop_codes.end()
Example #18
0
	def getReaders(self):
		readerList = []
		for reader in self.readers:
			readerList.append(Reader(reader["id"],
									 reader["bus"],
									 reader["subbus"],
									 reader["reset"],
									 reader["activated"]))
		return readerList
Example #19
0
    def test_https_A(self):
        user = '******'
        repo = 'Shell.Github.Commiter.20180316160244'
        git_config = """
[remote "origin"]
	url = https://github.com/{}/{}.git
""".format(user, repo)
        reader = Reader(self.__make_file_config(git_config))
        self.assertEqual(user, reader.RemoteOriginUser)
        self.assertEqual(repo, reader.RemoteOriginRepo)
Example #20
0
	def test_reader_allow_incomplete_on(self):
		print "Test zur Darstellung des Demo-Inputs in einer Objektstruktur, bei der unvollstaendige Properties erlaubt sind"
                a_reader = Reader("./example_input.py")
		a_reader.allowIncompleteProperties(1)
                a_reader.analyze()
		a_reader.printdata()
		self.assertEquals(len(a_reader.listOfSets), 5)
		for index in range(len(a_reader.listOfSets)):
                        propset = a_reader.listOfSets[index]
                        self.assertEquals(len(propset.properties), 5)
Example #21
0
    def test_https_B(self):
        user = '******'
        password = '******'
        repo = 'Shell.Github.Commiter.20180316160244'
        git_config = """
[remote "origin"]
	url = https://{0}:{1}@github.com/{0}/{2}.git
""".format(user, password, repo)
        reader = Reader(self.__make_file_config(git_config))
        self.assertEqual(user, reader.RemoteOriginUser)
        self.assertEqual(repo, reader.RemoteOriginRepo)
Example #22
0
def read():
    path = os.path.join(os.getcwd(), 'novels')
    novels = os.listdir(path)
    for index, novel in enumerate(novels):
        print("{}. {}".format(index + 1, novel))
    choice = int(input("Choose a title: "))
    title = novels[choice - 1]
    numOfChapters = int(input("How many chapters do you want me to read?"))
    reader = Reader(title)
    for i in range(numOfChapters):
        reader.read_page()
Example #23
0
    def __init__(self):
        reader = Reader()  # Reader object

        path = "1150haber"  # A corpus of documents

        # Dictionaries which will contain words
        adj_dict = {}
        noun_dict = {}
        verb_dict = {}

        # Key counters of the dictionaries
        adj_key_counter = 1
        noun_key_counter = 1
        verb_key_counter = 1

        # It will store the words
        wordList = reader.readWords(path)

        # Stores the words inside appropriate dictionaries
        adj_dict, noun_dict, verb_dict, adj_key_counter, noun_key_counter, verb_key_counter = reader.storeWords(
            adj_dict, noun_dict, verb_dict, adj_key_counter, noun_key_counter,
            verb_key_counter, wordList)

        sentenceCounter = 0  # Counts the number of generated sentences which has the requested value

        numOfSentences = int(input("Enter the number of the sentences: "))
        sentenceTotal = int(input("Enter the value of the sentences: "))
        print("---------------------------------------")

        #  'break' and random statements is added to vary the words in the sentences
        for noun in noun_dict:  # Traverses the noun_dict dictionary
            noun = randint(1, noun_key_counter)
            for adj in adj_dict:
                adj = randint(1, adj_key_counter)
                for verb in verb_dict:
                    if sentenceCounter < numOfSentences:  # Generates sentences until the given number of sentences is reached
                        sentence = str(
                            noun_dict[noun][0]).capitalize() + " " + str(
                                adj_dict[adj][0]) + " " + str(
                                    verb_dict[verb][0])  # Concatenation
                        mySum = noun_dict[noun][1] + adj_dict[adj][
                            1] + verb_dict[verb][
                                1]  # Computes the value of the sentence
                        if mySum == sentenceTotal:  # If the value of the current sentence is equal to the input value
                            print(sentenceCounter + 1, ": ", sentence, " | ",
                                  mySum)
                            sentenceCounter += 1
                            break
                    elif sentenceCounter == numOfSentences:  # If the number of sentences is reached to the input value, exit
                        exit(1)
                    else:
                        print("No matches found!")
                break
Example #24
0
    def __init__(self):
        states = ['q0','q1','q2','q3']
        transitions = {
            'q0':{'"':'q1',"'":'q2',super().ASCII:'q0'},
            'q1':{'"':'q3',super().ASCII:'q1'},
            'q2':{"'":'q3',super().ASCII:'q2'},            
            'q3':{'"':'q1',"'":'q2',super().ASCII:'q0'},
        }
        finalstate = {'q3':'COMMENT'}

        super().__init__(states, transitions, 'q0',finalstate)
        self.reader = ( Reader() ).read()
Example #25
0
    def test_ssh_A(self):
        # git@{SSH_HOST}:{user}/{repo}.git
        host = 'ytyaru.github.com'
        user = '******'
        repo = 'Shell.Github.Commiter.20180316160244'
        git_config = """
[remote "origin"]
	url = git@{}:{}/{}.git
""".format(host, user, repo)
        reader = Reader(self.__make_file_config(git_config))
        self.assertEqual(user, reader.RemoteOriginUser)
        self.assertEqual(repo, reader.RemoteOriginRepo)
Example #26
0
    def test_ssh_B(self):
        # ssh://[email protected]:22/kyanny/hello.git
        user = '******'
        password = '******'
        repo = 'Shell.Github.Commiter.20180316160244'
        git_config = """
[remote "origin"]
	url = ssh://[email protected]:22/{}/{}.git
""".format(user, repo)
        reader = Reader(self.__make_file_config(git_config))
        self.assertEqual(user, reader.RemoteOriginUser)
        self.assertEqual(repo, reader.RemoteOriginRepo)
Example #27
0
 def test_gdemo(self):
     print "Einlesen des Example Input und als Json-Datei schreiben in pretty-Format"
     a_reader = Reader(Test_test_GesamtDemo.PATH_IN)
     a_reader.analyze()
     print a_reader.printdata()
     listOfSets = []
     listOfSets.append(a_reader.getdata())
     composer = PropertySetToJsonComposer()
     composer.doFile(listOfSets, 1, Test_test_GesamtDemo.PATH_OUT)
     actual = hashlib.md5(open(Test_test_GesamtDemo.PATH_OUT,
                               'rb').read()).hexdigest()
     self.assertEquals(Test_test_GesamtDemo.EXPECTED, actual)
Example #28
0
    def __init__(self, cwd, inputFilePath):
        """create utilities required by the program,
        i.e. a registry checker, reader and module list
        """
        self.cwd = cwd
        self.inputFilePath = inputFilePath

        self._registryChecker = RegistryChecker()
        self._inputReader = Reader()
        self.moduleList = ModuleList()

        self.__prepModuleResult = DataContainer()
        return
Example #29
0
    def reset(self):
        filename = FileChooser().get_filename()
        questions = Reader(filename).get_questions()
        if questions is None:
            return False

        self.partie = Partie(questions)
        # reset game
        self.partie.reset()
        self.plateau.reset()
        self.sound_manager.reset()
        self.sound_manager.play_generic()
        return True
Example #30
0
def read() -> P_Expr:
    """
    Reads a line from the IP and instantiates a Reader using the IP
    and returns the resulting p-expression
    :return: p_expr
    """
    # try:
    ip = read_lines().line
    if not ip:
        return P_Expr(False)
    r = Reader(ip)
    p_expr = r.reader()
    return P_Expr(p_expr)