コード例 #1
0
    def run(self):
        max_unit = 0
        for i in range(self.ran):
            print("Generation ", i)
            gen = Generation(self.p)
            #gen.hand.print_cards()
            gen.assign_unit_value(0)
            #gen.print_stats()
            gen.calc_fitness(self.step, 0)

            #for i in range(p.size):
            #    print(gen.population.units[i].fitness)

            if (i == self.ran - 1):
                break

            max_val = 0
            for i in range(gen.population.size):
                if (gen.population.units[i].fitness > max_val):
                    max_unit = gen.population.units[i]
                    max_val = gen.population.units[i].fitness

            print(max_unit.fitness)
            s = Step(gen)
            gen.population.units = s.generate_mating_pool()

        max_val = 0
        max_unit = 0
        for i in range(gen.population.size):
            if (gen.population.units[i].fitness > max_val):
                max_unit = gen.population.units[i]
                max_val = gen.population.units[i].fitness

        print(max_unit.weights)
        return max_unit.weights
コード例 #2
0
ファイル: planner.py プロジェクト: stanleywbwong/AI-projects
    def run_test2_steps(self):
        """
        Complete: True
        Consistent: True
        Solution: True
        Linearization :
	 start
	 move b a table2
	 move a table0 table1
	 move d c table0
	 move c table4 table3
	 finish        
        """
        steps, ordering_constraints, causal_links = self.get_parameters(
            "test8")

        # TODO
        steps.append(
            Step(2, "move b a table2", [
                Condition(True, "clear table2"),
                Condition(True, "on b a"),
                Condition(True, "clear b")
            ], [
                Condition(True, "on b table2"),
                Condition(True, "clear a"),
                Condition(True, "clear a")
            ]))
        steps.append(
            Step(3, "move c table4 table3", [
                Condition(True, "clear table3"),
                Condition(True, "on c table4"),
                Condition(True, "clear c")
            ], [
                Condition(True, "clear table4"),
                Condition(True, "on c table3")
            ]))
        steps.append(
            Step(4, "move d c table0", [
                Condition(True, "on d c"),
                Condition(True, "clear d"),
                Condition(True, "clear table0")
            ], [
                Condition(True, "on d table0"),
                Condition(True, "clear c"),
                Condition(True, "clear c")
            ]))
        steps.append(
            Step(5, "move a table0 table1", [
                Condition(True, "clear table1"),
                Condition(True, "on a table0"),
                Condition(True, "clear a")
            ], [
                Condition(True, "clear table0"),
                Condition(True, "on a table1")
            ]))

        return steps, ordering_constraints, causal_links
コード例 #3
0
 def load(self):
     self.steps = []
     result = mysql_connection.select(
         'SELECT * FROM profiles WHERE email = "%s" AND password = "******"' %
         (self.email, self.password))
     if result:
         self.from_dict(result)
         profile_steps = mysql_connection.select_all(
             'SELECT * FROM profile_steps WHERE profile = "%s"' %
             str(self.id))
         if profile_steps:
             for ps in profile_steps:
                 step = Step()
                 step.id = ps['step']
                 step.load()
                 step.date = ps['date']
                 step.time = ps['time']
                 step.due = ps['due']
                 step.status = Status(ps['status'])
                 self.steps.append(step)
         move_reasons = mysql_connection.select_all(
             'SELECT * FROM move_reasons WHERE profile = "%s"' %
             str(self.id))
         if move_reasons:
             self.move_reasons = [
                 MoveReason(r['reason']) for r in move_reasons
             ]
         return True
     return False
コード例 #4
0
ファイル: step_test.py プロジェクト: tomas-mm/MLPipeline
    def test_execute_should_save_stage(self):
        output = "resources/stages/Tokenizer"
        # TODO remove output

        params = {"path": output, "overwrite": "true"}

        stage = feature.Tokenizer(inputCol="text", outputCol="words")
        step = Step('save', params, stage)

        step.execute()
        self.assertTrue(os.path.exists(output))
コード例 #5
0
ファイル: step_test.py プロジェクト: tomas-mm/MLPipeline
    def test_execute_should_load_stage(self):
        params = {"path": "resources/stages/LogisticRegression"}

        stage = classification.LogisticRegression()
        step = Step('load', params, stage)

        loaded = step.execute()

        cls = classification.LogisticRegression
        self.assertIsInstance(
            loaded,
            cls,
            msg=f"Loaded stage {loaded} is not instance of {cls.__class__}")
コード例 #6
0
    def meatify(self):
        num_items_replaced = 0
        max_items_replaced = round((3 + (len(self.ingredients) * 0.2)) / 2)

        for i in range(len(self.ingredients)):
            if num_items_replaced > max_items_replaced:
                break

            found = None
            for kind, matches in veg_types.items():
                for match in matches:
                    if match in self.ingredients[i].name:
                        found = kind
                        break

            if found is None:
                continue

            old = self.ingredients[i].name
            new = random.choice(veg_to_meat[found])
            if self.ingredients[i].measure == 'item':
                self.ingredients[i].quantity /= 2.0
                self.ingredients[i].measure = 'cup'
            descs = ' '.join(self.ingredients[i].descriptors)
            descs = descs + ' ' + ' '.join(self.ingredients[i].preparations)
            descs.strip()
            new_ing = Ingredient('{} {} {} {}'.format(
                self.ingredients[i].quantity, self.ingredients[i].measure,
                descs, new))
            self.ingredients[i] = new_ing

            num_items_replaced += 1
            yield old, new

        if num_items_replaced == 0:
            # try to guess new meat
            ing_str, prep_str, comb_str = random.choice(meat_additions)

            # add ingredient
            new_ingredient = Ingredient(ing_str)
            self.ingredients.append(new_ingredient)

            # add step to cook ingredient
            cook_step = Step(prep_str, self.ingredients)
            self.steps.insert(0, cook_step)

            # add step to combine ingredient
            combine_step = Step(comb_str, self.ingredients)
            self.steps.append(combine_step)

            yield None, new_ingredient
コード例 #7
0
ファイル: sequencer.py プロジェクト: ljurk/launchpadSequencer
 def __init__(self,
              note,
              name,
              launchpadPorts,
              interfacePorts,
              outgoingCC,
              silent,
              new=False):
     print("init")
     self.launchpad = launchpadPorts
     self.interface = interfacePorts
     self.note = note
     self.name = name
     self.outgoingCC = outgoingCC
     self.silent = silent
     self.sequence = []
     if not new:
         return
     self.sequence.append(Step(9, 0, [21, 41], self.launchpad['out']))
     self.sequence.append(Step(10, 1, [22, 42], self.launchpad['out']))
     self.sequence.append(Step(11, 2, [23, 43], self.launchpad['out']))
     self.sequence.append(Step(12, 3, [24, 44], self.launchpad['out']))
     self.sequence.append(Step(25, 4, [25, 45], self.launchpad['out']))
     self.sequence.append(Step(26, 5, [26, 46], self.launchpad['out']))
     self.sequence.append(Step(27, 6, [27, 47], self.launchpad['out']))
     self.sequence.append(Step(28, 7, [28, 48], self.launchpad['out']))
コード例 #8
0
ファイル: test_step.py プロジェクト: tatyderb/course_deploy
def test_step_update(step_ids, ind=0):
    """ get text, increase counter++, put text with new counter"""
    print('----- test_step_update: TEXT')
    text_step_id = step_ids[ind]
    st = Step.get(text_step_id)
    new_text = text_next_counter(st.text)
    st.update(new_text)

    stu = Step.get(text_step_id)
    assert (st == stu)

    print('----- test_step_update: QUIZ')
    print('Not implemented yet')
    return st, ind + 1
コード例 #9
0
def recordWalk(outputType: OutputType, refImage: Image, current: [] = None):
    global currentStep
    currentStep = currentStep + 1
    try:
        os.makedirs(".\\" + currentStageName)
    except:
        1
    refImageName = ".\\" + currentStageName + "\\" + str(
        currentStep) + "_" + '%05x' % random.randrange(16**5) + ".png"
    if (refImage):
        refImage.save(refImageName)
        setStep(Step(currentStep, outputType, refImageName, refImage, current))
    else:
        setStep(Step(currentStep, outputType, None, None, current))
コード例 #10
0
    def checkout(self, socket):
        #for socket in self.sockets:
        #    socket.write(steps[-1].to_string())
        print("checkout")
        print(self.active_user)
        print(self.active_socket)
        print(socket)

        if self.active_socket is socket:
            print("is")
            message = socket.readLine().data().decode()
            step = Step()
            step.from_string(message)
            self.process(step)
        """
コード例 #11
0
 def train(self, x: np.ndarray, answer: float):
     if type(answer) not in [int, float]:
         raise ValueError("La salida esperada answer debe ser un número")
     elif type(x) not in [list, np.ndarray]:
         raise ValueError("el input x debe ser un arreglo de floats")
     elif len(x) != self.__length:
         raise ValueError("Largo del arreglo incorrecto")
     else:
         for i in range(self.__length):
             if type(x[i]) != float:
                 raise ValueError(
                     "cada input del arreglo debe ser un float")
         old_w = self.get_weights()
         res = self.feed(x)  # obtenemos la salida de la neurona
         diff = float(answer) - res  # calculamos el error
         l_rate = self.__lrate
         old_b = self.__bias
         # Calculamos delta dependiendo del tipo de función de activación de la neurona
         if self.__acfunction == Step():
             delta = diff
         else:
             delta = diff * self.__acfunction.derivative(res)
         new_w = []  # Arreglo donde guardaremos los nuevos pesos
         # Calculamos los nuevos pesos
         for i in range(self.__length):
             new_w.append(old_w[i] + l_rate * x[i] * delta)
         self.set_weights(np.array(new_w))  # Actualizamos los pesos
         new_b = old_b + l_rate * delta  # Calculamos el nuevo sesgo
         self.set_bias(new_b)  # Actualizamos el sesgo
コード例 #12
0
def read_csv(file_name, print_info=False):
    """Reads data from input file (style 1).
    Returns list of jobs, number of jobs, number of machines.
    """
    with open(file_name, newline='') as csv_file:
        reader = csv.reader(csv_file)
        dimensions = next(reader)[0].split()
        jobs_no = int(dimensions[0])
        machines_no = int(dimensions[1])
        jobs = []
        for job_id, row in enumerate(reader):
            row = row[0].split()
            jobs.append([])

            # number of steps matches number of machines
            for i in range(machines_no):
                machine_id = int(row[2 * (i + 1) - 2])
                duration = int(row[2 * (i + 1) - 1])
                step = Step(job_id, i, machine_id, duration)
                jobs[job_id].append(step)

        if print_info:
            print_jobs(jobs)

        return jobs, jobs_no, machines_no
コード例 #13
0
def read_csv_2(file_name, print_info=False):
    """Reads data from input file (style 1).
    Returns list of jobs, number of jobs, number of machines.
    """
    with open(file_name, newline='') as csv_file:
        reader = csv.reader(csv_file)
        dimensions = next(reader)[0].split()
        jobs_no = int(dimensions[0])
        machines_no = int(dimensions[1])
        # skip the 'Times' string
        next(reader)
        jobs = []

        for job_id in range(jobs_no):
            jobs.append([])
            job_times = next(reader)[0].split()

            for step_no, job_time in enumerate(job_times):
                step = Step(job_id, step_no, math.inf, int(job_time))
                jobs[job_id].append(step)

        # skip the 'Machines' string
        next(reader)
        for job_id in range(jobs_no):
            job_machines = next(reader)[0].split()

            for step_no, step_machine_id in enumerate(job_machines):
                jobs[job_id][step_no].machine_id = int(
                    step_machine_id) - 1  # cause they are encoded from 1

        if print_info:
            print_jobs(jobs)

        return jobs, jobs_no, machines_no
コード例 #14
0
 def set_steps(self, steps):
     new_steps = []
     for step in steps:
         new_step = Step(**step)
         new_steps.append(new_step)
     self.steps = new_steps
     return self.steps
コード例 #15
0
    def __init__(self, content, pois_ids, profile):
        self.profile = profile

        status_code = content['code']

        if status_code == 3:
            raise RuntimeError('Routing failed!')
        elif status_code > 0:
            raise RuntimeError('Error code: {}'.format(status_code))

        unassigned_nr = len(content['unassigned'])

        if unassigned_nr > 0:
            log('Warning: {} unassigned targets'.format(unassigned_nr))

        route = content['routes'][0]

        self.visit_time = i2dt(route['service'])
        self.travel_time = i2dt(route['duration'])
        self.waiting_time = i2dt(route['waiting_time'])
        self._computing_times = content['summary']['computing_times']

        raw_steps = route['steps']
        self.steps = []
        for s in raw_steps:
            step = Step(s, pois_ids)
            self.steps.append(step)

        log(self, indent=0, verbose=True)
コード例 #16
0
def moveAndClick(step, currentMov, postMoveDelay, midClickDelay,
                 postMoveAlways):
    global timedDelays
    global newStepList
    moved = False
    if step.clickPos:
        moved = moveMouse(step.clickPos[0] - currentMov[0],
                          (step.clickPos[1] - currentMov[1]))
    if postMoveAlways > 0.0:
        time.sleep(postMoveAlways)

    if moved:
        time.sleep(postMoveDelay)
        timedDelays += postMoveDelay
    if moved and step.imageName is not None and step.imageName != "":
        img = loopAndGrabImage()
        imageName = step.imageName.replace(".png", "_move.png")
        img.save(imageName, "png")
        newStepList.append(
            Step(-1, OutputType.MOVE, imageName, img, step.clickPos))

    mouse.press(Button.left)
    time.sleep(midClickDelay)
    timedDelays += midClickDelay
    mouse.release(Button.left)
    pass
コード例 #17
0
    def loadSequences(self):
        fileCount = 0
        for seqfile in sorted(os.listdir(self.sequenceDir)):
            print(seqfile)
            if fileCount == 4:
                return
            fileCount += 1

            with open(os.path.join(self.sequenceDir, seqfile), 'r', encoding='utf-8') as fp:
                data = json.load(fp)
            sequence = []
            for step in data['sequence']:
                sequence.append(Step(step['note'],
                                     step['led'],
                                     step['incommingCC'],
                                     self.launchpad['out'],
                                     step['active']))
                for cc in step['cc']:
                    sequence[-1].addCc(cc["cc"], cc["value"])
                temp = {}

            self.sequences.append(Sequencer(data['note'],
                                            data['name'],
                                            self.launchpad,
                                            self.interface,
                                            outgoingCC=data['outgoingCC'],
                                            silent=data['silent']))
            self.sequences[-1].sequence = sequence
コード例 #18
0
ファイル: test_step.py プロジェクト: tatyderb/course_deploy
def test_get_step_ids(lesson_id=expected_lesson_ids[0],
                      expected=expected_step_ids):
    print('----- test_get_step_ids')
    step_ids = Step.get_step_ids_for_lesson(lesson_id)
    print(f'lesson = {lesson_id} -> steps={step_ids}')

    assert (step_ids == expected)
    return step_ids
コード例 #19
0
ファイル: test_step.py プロジェクト: tatyderb/course_deploy
def test_get_step(step_ids, ind=0, expected=expected_step_text):
    print('----- test_get_step')
    step_id = step_ids[ind]
    st = Step.get(step_id)
    print('TEXT =', st.text)

    assert (st.text == expected)
    return st, ind + 1
コード例 #20
0
ファイル: guide.py プロジェクト: agiddings/MyPyFixIt
    def refresh(self):
        '''Refetch instance data from the API.
      '''
        response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id))
        attributes = response.json()

        self.category = Category(attributes['category'])
        self.url = attributes['url']

        self.title = attributes['title']
        if attributes['image']:
            self.image = Image(attributes['image']['id'])
        else:
            self.image = None
        self.locale = attributes['locale']
        self.introduction = WikiText(attributes['introduction_raw'],
                                     attributes['introduction_rendered'])
        self.conclusion = WikiText(attributes['conclusion_raw'],
                                   attributes['conclusion_rendered'])
        if (attributes['tools']):
            self.tools = attributes['tools']
        else:
            self.tools = None
        self.parts = attributes['parts']
        self.subject = attributes['subject']
        self.modifiedDate = datetime.utcfromtimestamp(
            attributes['modified_date'])
        self.createdDate = datetime.utcfromtimestamp(
            attributes['created_date'])
        self.publishedDate = datetime.utcfromtimestamp(
            attributes['published_date'])
        #self.documents = attributes['documents']
        author = attributes['author']
        #self.author = User(author['userid'], name=author['text'])
        if (attributes['time_required_min']):
            self.time_required_min = attributes['time_required_min']
        else:
            self.time_required_min = -1
        if (attributes['time_required_max']):
            self.time_required_max = attributes['time_required_max']
        else:
            self.time_required_max = -1
        self.steps = [
            Step(step['guideid'], step['stepid'], data=step)
            for step in attributes['steps']
        ]
        self.type = attributes['type']
        self.public = attributes['public']
        self.revision = attributes['revisionid']
        self.difficulty = attributes['difficulty']
        self.prerequisites = [
            Guide(guide['guideid']) for guide in attributes['prerequisites']
        ]
        #                     attributes['prereq_modified_date']
        #self.summary = attributes['summary']
        self.flags = [
            Flag.from_id(flag['flagid']) for flag in attributes['flags']
        ]
コード例 #21
0
 def change_step_ingredients(self, changes):
     for old, new in changes:
         if old is not None:
             for s in range(len(self.steps)):
                 for i in range(len(self.steps[s].ingredients)):
                     if old in self.steps[s].ingredients[i]:
                         self.steps[s] = Step(
                             self.steps[s].raw.replace(old, new),
                             self.ingredients)
                         break
コード例 #22
0
ファイル: testscript.py プロジェクト: CwbhX/HPQC-Processor
 def addStep(self,
             number,
             stepDescription,
             expectedResult,
             expectedRunTime=None):
     self.steps.append(
         Step(number,
              stepDescription,
              expectedResult,
              expectedRunTime=expectedRunTime))
コード例 #23
0
 def load(self):
     result = mysql_connection.select(
         'SELECT * FROM cities WHERE name LIKE "%s"' % str(self.name))
     if result:
         self.id = result['id']
         self.steps = []
         self.location = Location(result['location_lat'],
                                  result['location_lng'])
         if result['buildings'] != '' and result['buildings'] is not None:
             self.buildings = json.loads(result['buildings'])
         steps_result = mysql_connection.select_all(
             'SELECT id FROM steps WHERE city LIKE "%s"' % str(self.name))
         print steps_result
         if steps_result:
             for s in steps_result:
                 step = Step()
                 step.id = s['id']
                 step.load()
                 self.add_step(step)
コード例 #24
0
ファイル: userjourney.py プロジェクト: bobev18/stujeditor
    def import_uj(self, filename):
        with open(filename, 'r') as f:
            raw = f.readlines()

        self.first_import_line = raw[0]

        ET.register_namespace('', SCHEME_PREFIX[1:-1])
        tree = ET.parse(filename)
        root = tree.getroot()
        self.name = root.attrib['NAME']
        self.app_name = root.attrib['APPNAME']
        self.version = root.attrib['VERSION']

        created = root.find(SCHEME_PREFIX+'CREATED')
        self.created = created.text

        self.uj_global_settings = []
        for nvp in root.findall(SCHEME_PREFIX+'NVP'):
            self.uj_global_settings.append({'NAME': nvp.attrib['NAME'], 'PLUGIN': nvp.attrib['PLUGIN'], 'TYPE': nvp.attrib['TYPE'], 'text': nvp.text})

        #### Dynamic Data Items ###
        dditems_element = root.find(SCHEME_PREFIX+'DYNAMICDATA')
        self.dditems = []

        for ddi in dditems_element.findall(SCHEME_PREFIX+'DDITEM'):
            ddi_type = ddi.find(SCHEME_PREFIX+'SOURCE').attrib['TYPE']
            self.dditems.append(TYPE_TO_CLASS_MAP[ddi_type](ddi))

        #### Steps & Step-Groups ####
        # stepgroups are not defined in the XML, so to construct a stepgroup, we need list of all the steps
        steps_element = root.find(SCHEME_PREFIX+'STEPS')
        stepgroups = []
        stepgroup_steps = []
        lead_step = None
        last_step_stepgroup_id = -1
        for step in steps_element.findall(SCHEME_PREFIX+'STEP'):
            current_step = Step(step)

            if last_step_stepgroup_id == -1: # adjust for starting element
                lead_step = current_step
                last_step_stepgroup_id = current_step.stepgroup_id

            if current_step.stepgroup_id != last_step_stepgroup_id:
                stepgroups.append(StepGroup(lead_step, stepgroup_steps))
                lead_step = current_step
                stepgroup_steps = [current_step]
                last_step_stepgroup_id = current_step.id
            else:
                stepgroup_steps.append(current_step)

        # finalize after last step
        stepgroups.append(StepGroup(lead_step, stepgroup_steps))

        self.stepgroups = stepgroups
コード例 #25
0
ファイル: step_test.py プロジェクト: tomas-mm/MLPipeline
    def test_execute_should_fit_stage(self):
        cls = Model

        dataset = self.spark.createDataFrame([(0, Vectors.dense([1, 2]), 1),
                                              (1, Vectors.dense([1, 3]), 1),
                                              (2, Vectors.dense([2, 3]), 0),
                                              (3, Vectors.dense([4, 5]), 1)],
                                             ["id", "features", "label"])

        params = {"dataset": dataset}

        stage = classification.LogisticRegression()
        step = Step('fit', params, stage)

        model = step.execute()

        self.assertIsInstance(
            model,
            cls,
            msg=f"Result {model} is not instance of {cls.__class__}")
コード例 #26
0
def create_steps(journey_dict):
    """
    Extract the coordinates of each step in the journey.

    """
    steps = []
    for step in journey_dict['steps']:
        origin = get_coord_from_step(step, 'start_location')
        destination = get_coord_from_step(step, 'end_location')
        duration = step['duration']['value']
        steps.append(Step(origin, destination, duration=duration))
    return steps
コード例 #27
0
ファイル: car.py プロジェクト: fadi721994/AI_Lab_assignment1
 def find_direction_steps(self, board_row, direction, steps):
     count = False
     i = 1
     for col in board_row:
         if col == self.name:
             count = True
         if col != "." and col != self.name and count:
             break
         if col == "." and count:
             step = Step(self.name, direction, i)
             steps.append(step)
             i = i + 1
コード例 #28
0
def get_all_steps(username: str) -> list:
    """
    Returns a list of Step objects corresponding to the given user.
    """

    with Database(DATABASE_PATH) as db:
        return [
            Step(row['description'], not not row['completed'])
            for row in db.query(
                "SELECT description, completed FROM STEPS WHERE username=%s ORDER BY step_num ASC",
                username
            )
        ]
コード例 #29
0
ファイル: test_step.py プロジェクト: tatyderb/course_deploy
def test_step_push(lesson_id, text='New step by scripts'):
    step_ids = Step.get_step_ids_for_lesson(lesson_id)
    position = len(step_ids) + 1
    step = Step()
    step.lesson_id = lesson_id
    step.position = position
    step.text = text

    id = step.create()
    assert (id == step.id)

    st1 = step.get(id)
    assert (st1.text == text)
    assert (step == st1)

    return id
コード例 #30
0
ファイル: utils.py プロジェクト: fadi721994/AI_2
def from_steps_str_to_object(steps):
    steps_strs = steps.split(' ')[:-1]
    steps_objs = []
    for step in steps_strs:
        if step[1] == 'R':
            direction = Direction.RIGHT
        elif step[1] == 'L':
            direction = Direction.LEFT
        elif step[1] == 'D':
            direction = Direction.DOWN
        else:
            direction = Direction.UP
        step_obj = Step(step[0], direction, int(step[2]))
        steps_objs.append(step_obj)
    return steps_objs
コード例 #31
0
def main():
	#excluded_dirs = ["log","resources","conf"]
	# parse command-line arguments
	script_main_dir = os.path.dirname(os.path.realpath(__file__))
	args = parse_args(script_main_dir)
	#supported_vendors = config.read_supported_vendors(script_main_dir + path_sep + "config")
	os.environ["BASE_DIR"] = script_main_dir
	log_dir = args.log
	if not os.path.isdir(log_dir):
		os.mkdir(log_dir)

	step = args.step
	vendor = args.cloud
	mode = args.mode
	dry_run = args.dry_run
	# set logger
	dt = datetime.datetime.now()
	
	log_name = step + "_" + vendor + "_" + dt.strftime("%Y%m%d_%H%M") + ".log"
	setup_logging(args,args.log_level,log_name)
	
	#Check input
	if not config.is_configuration_supported(supported_vendors,vendor):
		logging.error("No support for provided 'cloud' value : {}".format(vendor))
		exit(1)
	elif not config.is_configuration_supported(supported_steps,step):
		logging.error("No support for provided 'step' value : {}".format(step))
		exit(1)

	full_log = 	log_dir  + log_name	
	logging.info("Starting running step : {} for vendor {} see log file : {} ".format(step,vendor,full_log))
	
	#Create step object
	current_step = Step(step,vendor,logging,script_main_dir,script_main_dir + path_sep + "config",script_main_dir + path_sep + "resources",mode)
	
	#Read the input data and verify it
	current_step.read_input_data()
	
	#Copy sources from source directory
	current_step.copy_sources()
	
	#Intialize the db components with all running necessary configs
	current_step.intialize_db_components()
	
	#Replace all placeholders accoridng to <db.compnenet.name>.plcholders file
	current_step.replace_placeholders()
	
	if dry_run:
		try:
			logging.info("Dry run instructions :")
			current_step.print_script_order()
		finally:
			logging.info("Finished running step : {} for vendor {} see log file : {}".format(step,vendor,full_log))
	else:
		try:
			# Execute Scripts
			current_step.run_sql_scripts()
		except DbException as e:
			logging.error("Running scripts for step {} failed with error : {}".format(step,e.value))
			exit(2)
		finally:
			logging.info("Finished running step : {} for vendor {} see log file : {}".format(step,vendor,full_log))
コード例 #32
0
ファイル: test.py プロジェクト: astrxlegaulois/RaspBrewerPy
import datetime
from brewer import Brewer
from receipe import Receipe
from globalthings import *
from step import Step

print "Test begging"
mon_step1=Step("monStep",TRANSITION,10)
mon_step2=Step("monStep2",LEVEL,60,67)
mon_step3=Step("monStep3",TRANSITION,10)
mon_step4=Step("monStep4",LEVEL,1,90)
mon_step1.print_self()
mon_step2.print_self()
mon_step3.print_self()
mon_step4.print_self()

mon_step1.interpolation(0, datetime.datetime.now(), 50, datetime.datetime.now()+ datetime.timedelta(minutes=5, seconds=0))

ma_receipe=Receipe("Ma premiere recette")
ma_receipe.add_step(mon_step1)
ma_receipe.add_step(mon_step2)
ma_receipe.add_step(mon_step3)
ma_receipe.add_step(mon_step4)

ma_receipe.print_self()

ma_receipe.start(20)
ma_receipe.print_self()

ma_receipe.get_current_temperature_instruction()