def start_game(self): if (len(self.users) == 0): show_message("No User Registed", "", 2) return self.game_started = True for user_index, user in enumerate(self.users): self.step_index += 1 step = Step() step.user = user_index step.index = self.step_index step.action = "setup user" step.command = [ user.username, user.avatar, self.nodes_list[user_index] ] self.broad_cast(step) step = Step() step.action = "start game" self.process(step) self.get_initial_funding() step = Step() step.action = "next turn" self.process(step)
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
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
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']))
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))
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
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
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
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
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
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
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
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)
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
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'] ]
def addStep(self, number, stepDescription, expectedResult, expectedRunTime=None): self.steps.append( Step(number, stepDescription, expectedResult, expectedRunTime=expectedRunTime))
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
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))
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
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
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
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__}")
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 ) ]
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) """
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
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
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)
def create_step(spark, step_conf): name = step_conf["name"] params = step_conf["params"] stage = step_conf["stage"] if isinstance(stage, dict) and "stage" in stage: # Stage comes from an executed step stage = StepFactory.create_step(spark, stage).execute() else: # Create a stage stage = StageFactory.create_stage(spark, stage) if "dataset" in params and isinstance(params["dataset"], dict): # Create dataset if needed in step parameters dataset_conf = params["dataset"] params["dataset"] = DatasetFactory.create_dataset( spark, dataset_conf) return Step(name, params, stage)
def less_healthy(self): num_items_replaced = 0 for i in range(len(self.ingredients)): found = None for kind, matches in less_healthy_conversions.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 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, found)) self.ingredients[i] = new_ing new = self.ingredients[i].name num_items_replaced += 1 yield old, new if num_items_replaced == 0: # guess new ingredient ing_str, stp_str = random.choice(less_healthy_conversions) # add new ingredient new_ing = Ingredient(ing_str) self.ingredients.append(new_ing) # add new step new_stp = Step(stp_str, self.ingredients) self.steps.append(new_stp) yield None, new_ing.name
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__}")