def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.field = Field() self.buttons = {} self.next_btn = None self.init_visual()
def start_game(): os.system('cls' if os.name == 'nt' else 'clear') print('\nHello my friend! Let\'s play a game!') field = Field('new') print( 'So, to play a game you need to call your friend and say me your names!\n' ) p1_name = input('Tell me the name of the first player: ') p2_name = input('Tell me the name of the second player: ') player1 = Player(p1_name, 1) player2 = Player(p2_name, 1) os.system('cls' if os.name == 'nt' else 'clear') # turn = get_turn(player1,player2) print( '\nNow it\'s time to place your ships on a game field! And the first player will be {}\n' .format(player1.name)) os.system('cls' if os.name == 'nt' else 'clear') #field.print_field('') p1_ships = create_ships(field) os.system('cls' if os.name == 'nt' else 'clear') print( '\nNow it\'s time to place its ships For the second player {}'.format( player2.name)) input('\n\npress Enter to continue...') os.system('cls' if os.name == 'nt' else 'clear') field.print_field('') p2_ships = create_ships(field)
def editor(request): world = _get_current_world(request) if request.method == 'GET': return render_to_response('world/editor.html', { 'field_classes': FieldClass.objects.all(), 'world': world, 'field_size': FIELD_SIZE, }) elif request.method == 'POST': # TODO : secure! world = World.objects.get(id=request.POST['world_id']) for f in world.fields.all(): f.delete() fields_str = request.POST['fields'] fields = fields_str.split('|'); for field_str in fields: x, y, z, class_id = field_str.split(',') field = Field(x=int(x), y=int(y), z=int(z), field_class=FieldClass.objects.get(id=int(class_id)), world=world) field.save(); return HttpResponse('World saved');
class View(Model): table_name = "views" id = Field(int, modifiable=False) date = Field(datetime, default=datetime.now()) viewer_id = Field(int) viewee_id = Field(int) @staticmethod def get_viewed_by(self, user_id): connection = pool.get_conn() with connection.cursor() as c: date_format = '%e %b %Y' c.execute( """ SELECT v.id, v.viewer_id, u.fname AS 'viewer_first_name', u.lname AS 'viewer_last_name', u.username AS 'viewer_username', v.viewee_id, DATE_FORMAT(v.date, %s) as date FROM views v INNER JOIN users u ON v.viewer_id = u.id WHERE v.viewee_id = %s AND v.viewer_id <> %s """, (date_format, user_id, user_id)) pool.release(connection) return c.fetchall() pool.release(connection) return None @staticmethod def get_views(self, user_id): connection = pool.get_conn() with connection.cursor() as c: date_format = '%e %b %Y' c.execute( """ SELECT v.id, v.viewer_id, v.viewee_id, u.fname AS 'viewee_first_name', u.lname AS 'viewee_last_name', u.username AS 'viewee_username', DATE_FORMAT(v.date, %s) as date FROM views v INNER JOIN users u ON v.viewee_id = u.id WHERE v.viewer_id = %s AND v.viewee_id <> %s """, (date_format, user_id, user_id)) pool.release(connection) return c.fetchall() pool.release(connection) return None
def __init__(self, target=None, observer=None): self._sql = SQLInsertRequest() self._db = Database() self._convert = Convert() if target: self._entry = TableEntry(target) if observer: self._observer = observer self._field = Field()
def get_primary_image(self): if self.id: try: connection = pool.get_conn() with connection.cursor() as c: c.execute("""SELECT image64, image_type FROM images WHERE user_id=%s ORDER BY id DESC LIMIT 1""", (self.id,)) result = c.fetchone() image64 = None if not result else result["image64"] image_type = None if not result else result["image_type"] self.append_field("image64", Field(str, image64)) self.append_field("image_type", Field(str, image_type)) except Exception as e: raise finally: pool.release(connection)
def _get_possible_value_tier_1(field: Field, cell: Cell) -> Set[int]: """ Simply intersect all the missing values of a containing Column, Row and Square """ if cell.value is not None: return set() row_missing_values = field.get_row(cell.row).get_missing_values() column_missing_values = field.get_column( cell.column).get_missing_values() square = field.get_square_from_coordinates(cell.column, cell.row) square_missing_values = square.get_missing_values() possible_values = row_missing_values & column_missing_values & square_missing_values return possible_values
def New_form(): if request.method == 'POST': nameF = request.form['form_name'] nameA = request.form['area'] print(nameF) print(nameA) #f = Form(name=request.form['form_name'],detail=request.form['area']) f = Form(name=request.form['form_name'], detail=request.form['detail'], estatus="I") db.session.add(f) db.session.commit() datos = request.form['area'] print(datos) campos = datos.split(';') for campo in campos: info = campo.split(':') if len(info) > 1: listado = f.id camp = Field(form_id=f.id, name=info[0].replace(' ', '_'), tipe=info[1], label=info[2], detail=info[3].replace(' ', '_')) db.session.add(camp) db.session.commit() return redirect('/plantilla')
def parse_field(f): name = f.name.strip('_') description = ' '.join(f.description.split()) if f.description else '' return Field(name=name, bit_offset=f.bit_offset, bit_width=f.bit_width, description=description)
def create_field(): while True: # user_input = input('Введите размеры игрового поля через пробел или нажмите Enter для поля 10x10: ') user_input = '10 10' if not user_input: return Field() else: try: x, y = (int(i) for i in user_input.split()) if x > 20 or y > 20: print('Слишком большой размер поля. Попробуйте ещё раз') continue break except ValueError: print('Введите целые числа для длины и ширины игрового поля, например 10 10') return Field(x, y)
def post(self, request, *args, **kwargs): self.id = kwargs.get('id', '') data = get_form_data(request) doc = create_rtf_document(data) Field.objects.filter(resume__id=self.id).delete() r = Resume.objects.get(id=self.id) file_name = r.name.replace(' ', '_') file_name = file_name + '.rtf' write_file(doc, file_name) r.date_created = datetime.now() r.save() for k in data.keys(): field_type = 'T' if len(data[k][1]) < 50 else 'A' f = Field(order=k, label=data[k][0], value=data[k][1], checked=data[k][2], field_type=field_type, resume=r) f.save() return HttpResponseRedirect(reverse_lazy('cv_list_url'))
def register(FieldID): field = FieldID datapoints = [] timestamps = [] entry = Field(number=field, datapoints=datapoints, timestamps=timestamps) db.session.add(entry) db.session.commit() return {"Status": f"Successfully created {field} channel"}
def step_impl(context): context.fields = {} for row in context.table: name = row['name'] field = Field(name=name, ) context.fields[name] = field db.session.add(field) db.session.commit()
def get_full_user(user_id): user = User.get(id=user_id) images = Image.get_many(user_id=user_id) # Get the images for that user user.append_field("images", Field(list, images)) return user
def __init__(self, field, *args, **kwargs): super().__init__(*args, **kwargs) self.user_field = field self.ai_field = Field.randomize() self.user_buttons = {} self.ai_buttons = {} self.help_text = None self.lock = False self.init_visual()
def randomize_field(self): self.field = Field.randomize() for button in self.buttons.values(): button.setText('') for ship in self.field.ships: for row, col in ship.coordinates: self.buttons[(row, col)].setText(str(ship.length)) self.next_btn.setEnabled(True)
def _add_fields(self, table, schema): """adds fields to the table""" for schema_info in schema: field = Field(schema_info) arcpy.AddField_management(table.location, field.field_name, field.field_type, field_length=field.field_length, field_alias=field.field_alias)
def _getDbFields(self, cur, table_id): fields = [] db_fields = cur.execute( """ SELECT * from dbd$fields WHERE table_id = :id""", { "id": table_id }).fetchall() field_metadata = self._getMetadata(cur, "dbd$fields") for field in db_fields: field_dictionary = dict(zip(field_metadata, list(field))) tmp = Field(field_dictionary) if field_dictionary["domain_id"] is not None: tmp.domain = self._getDbDomainName( cur, domain_id=field_dictionary["domain_id"]) fields.append(tmp) return fields
def addField(user): is_valid = True if len(request.form['newfield']) < 1: is_valid = False flash("Please enter a field!") if not is_valid: return redirect("/addtoDB") if is_valid: new_field = Field(field_name=request.form['newfield']) db.session.add(new_field) db.session.commit() return redirect("/addtoDB")
class Image(Model): table_name = "images" id = Field(int, modifiable=False) user_id = Field(int) image64 = Field(str) is_primary = Field(bool) image_type = Field(str) def before_save(self): connection = self.pool.get_conn() with connection.cursor() as c: c.execute( """SELECT COUNT(*) as image_count FROM images WHERE user_id=%s""", (self.user_id)) result = c.fetchone() if result.get("image_count", 0) >= 5 and not self.id: self.pool.release(connection) raise Exception( "Cannot upload image, you already have 5. Please delete an image and reupload." ) self.pool.release(connection) @classmethod def check_images(cls, user_id): temp = cls() connection = temp.pool.get_conn() with connection.cursor() as c: c.execute( """ SELECT EXISTS(SELECT * FROM images WHERE user_id=%s AND image64!=%s) AS has_images from images """, (user_id, " ")) temp.pool.release(connection) return c.fetchone() temp.pool.release(connection) return None
class Post(Model): title = Field("") content = Field("") channel = Field("") create_ts = Field(0) view_num = Field(0) upvote = Field(0)
def setUp(self): # create classifcation self.classification = create_classification('Men\'s Open') # create an Address and a Field self.address = Address(street='ABC Street') self.address.save() self.field = Field(name='Field 1', address=self.address) self.field.save() # create teams self.team_1 = create_team('Team 1', self.classification) self.team_2 = create_team('Team 2', self.classification) # create some players self.player_1 = create_player('One', '1') self.player_2 = create_player('Two', '2') self.player_3 = create_player('Three', '3') # assign the players self.playfor_1 = PlayFor(player=self.player_1, team=self.team_1, from_date=datetime.date.today()) self.playfor_1.save() self.playfor_2 = PlayFor(player=self.player_2, team=self.team_1, from_date=datetime.date.today()) self.playfor_2.save() self.playfor_3 = PlayFor(player=self.player_3, team=self.team_1, from_date=datetime.date.today()) self.playfor_3.save() # create referee person = Person(first_name='Ref', last_name='Ref') person.save() self.referee = Referee(person=person) self.referee.save() # create two seasons self.season_1 = create_season(self.classification, 'Division 1', '2014-2015', datetime.date.today(), datetime.date.today()) self.season_2 = create_season(self.classification, 'Division 2', '2015-2016', datetime.date.today(), datetime.date.today()) # create some games self.matchday_season_1 = Matchday(season=self.season_1, label='1', date=datetime.date.today()) self.matchday_season_1.save() self.game_season_1 = Game(matchday=self.matchday_season_1, date=datetime.date.today(), away_team=self.team_1, home_team=self.team_2, referee=self.referee, played=True, field=self.field) self.game_season_1.save() self.matchday_season_2 = Matchday(season=self.season_2, label='2', date=datetime.date.today()) self.matchday_season_2.save() self.game_season_2 = Game(matchday=self.matchday_season_2, date=datetime.date.today(), away_team=self.team_1, home_team=self.team_1, referee=self.referee, played=True, field=self.field) self.game_season_2.save()
def build_schema_map(schema): schema_index_items = OrderedDict() if isinstance(schema, basestring): if schema == 'Stations': schema = Schema().station elif schema == 'Results': schema = Schema().result for item in schema: schema_index_items.update({item['destination']: Field(item)}) return OrderedDict(schema_index_items)
def solve(field: Field, with_brute_force: bool = False): counter = 0 updates_found = True while updates_found: counter += 1 updates_found = False for cell in field.cells: if cell.value is not None: continue possible_values = SudokuSolver.get_possible_values(field, cell) if len(possible_values) == 1: cell.value = next(iter(possible_values)) updates_found = True if field.is_valid: print(f"Solved in {counter} cycles:") field.print() else: print(f"Not solved with logic, state after {counter} cycles:") field.print() if with_brute_force: SudokuSolver.brute_force(field)
def post(self, request, *args, **kwargs): data = get_form_data(request) # stvaranje rtf dokumenta i spremanje životopisa doc = create_rtf_document(data) r = Resume() file_name = request.POST.get('save', '') if file_name: r.name = file_name file_name = file_name.replace(' ', '_') file_name = file_name + '.rtf' write_file(doc, file_name) r.date_created = datetime.now() r.user = request.user r.save() # spremanje životopisa za kasnije uređivanje for k in data.keys(): field_type = 'T' if len(data[k][1]) < 50 else 'A' f = Field(order=k, label=data[k][0], value=data[k][1], checked=data[k][2], field_type=field_type, resume=r) f.save() return HttpResponseRedirect(reverse_lazy('cv_list_url'))
class Message(Model): table_name = "messages" id = Field(int, modifiable=False) to_id = Field(int) from_id = Field(int) timestamp = Field(datetime, default=datetime.now()) message = Field(str) seen = Field(bool)
class Creator: """Create records""" YES = re.compile(r'o|y|oui|yes', re.IGNORECASE) ADD_A = re.compile(r'^(.*ajouter un[e]? )(.*)$', re.IGNORECASE) CHOOSE = re.compile(r'.*\[(.*)\].*', re.IGNORECASE) def __init__(self, target=None, observer=None): self._sql = SQLInsertRequest() self._db = Database() self._convert = Convert() if target: self._entry = TableEntry(target) if observer: self._observer = observer self._field = Field() @property def entry(self): """Property entry""" return self._entry def _create_simple(self, arg): """ask for fields entry and record, then return id""" id = [] entry = arg if isinstance(arg, TableEntry) else arg["entry"] while not id: values = self._get_fields_values_for(entry.fields) request = entry.request if self._observer: self._observer.add_debug_message( f"request: {request}\n ==> values: {values}") id = self._db.request(request, tuple(values), ask=True) return int(id[0][0]) def _create_maybe(self, relation, **kwargs): """ask from a list of records to choose one (exist=yes) or (exist=maybe) possibly create a new one or STOP link recording""" id = 0 while id == 0: if relation["exist"]: choices = self._show_existing_records(relation["table"], relation["show"], relation["exist"], **kwargs) answer = input("Faites un choix: ") if relation["exist"] == "maybe" and answer == choices[-1]: Record(relation["table"]) elif 1 <= int(answer) < len(choices): id = choices[int(answer)] elif int(answer) >= len(choices): print("re-essayez: vous avez fait un choix qui n'existe " "pas.") else: # Choice is 0 ==> STOP id = None return id def _record_through(self, through, values): """Record relational table""" request = self._sql.table(through, "script") if self._observer: self._observer.add_debug_message( f"request: {request}\n ==> values: {values}") success = self._db.request(request, tuple(values)) return success def _get_fields_values_for(self, fields, exception=[]) -> list: """Return field parser factories result list values""" values = list() for field in fields: if field["name"] not in exception: value = None if field["type"] == "varchar": if field["test"] == "file": value = self._field.file_(field) elif field["test"] == "image": value = self._field.image_(field) else: value = self._field.varchar_(field) if field["type"] == "int": value = self._field.int_(field) if field["type"] == "enum": value = self._field.enum_(field) if field["type"] == "bytea": value = self._field.bytea_(field, values) if field["type"] == "bool": value = self._field.bool_(field) if field["type"] == "date": value = self._field.date_(field) if field["type"] == "date_time": value = self._field.date_time_(field) if field["type"] == "numeric": value = self._field.numeric_(field) values.append(value) return values @staticmethod def _get_an_other(string) -> str: """Add 'autre ' inside string at precise point""" match = Creator.ADD_A.match(string) question = match.group(1) + "autre " + match.group(2) return question def _show_existing_records(self, table, fields, exist, **kwargs): """Print enumerated list of fields 'field' existing 'table' records and return a list of id and 'n': [id,.....,'n']""" choices = ["STOP"] print(" 0) -- RIEN --") sql = SQLShowRequest() sub_request = sql.table(table) request = re.sub(r'\*', f"id, {fields}", sub_request) \ if "request" not in kwargs or kwargs["request"] is None\ else kwargs["request"] records = self._db.request(request, ask=True)\ if "values" not in kwargs \ else self._db.request(request, kwargs["values"], ask=True) if self._observer: self._observer.add_debug_message( f"request: {request}\n ==> answer: {records}") for n, record in enumerate(records): choices.append(int(record[0])) string = "%3s) " % str(n + 1) for i_field in range(1, len(record)): string += f" %s - " % record[i_field] print(string) if exist == "maybe": choices.append("n") print(" n) -- Nouveau --") return choices def ask_for_choice(self, question): """Ask a question and return the answer depend of the validation of choices""" correct = False answer = "" choices = self.CHOOSE.match(question).group(1).split(", ") while not correct: answer = input(question) correct = bool((answer in choices) or "fin") return answer
class SeasonTest(TestCase): def setUp(self): # create classifcation self.classification = create_classification('Men\'s Open') # create an Address and a Field self.address = Address(street='ABC Street') self.address.save() self.field = Field(name='Field 1', address=self.address) self.field.save() # create teams self.team_1 = create_team('Team 1', self.classification) self.team_2 = create_team('Team 2', self.classification) # create some players self.player_1 = create_player('One', '1') self.player_2 = create_player('Two', '2') self.player_3 = create_player('Three', '3') # assign the players self.playfor_1 = PlayFor(player=self.player_1, team=self.team_1, from_date=datetime.date.today()) self.playfor_1.save() self.playfor_2 = PlayFor(player=self.player_2, team=self.team_1, from_date=datetime.date.today()) self.playfor_2.save() self.playfor_3 = PlayFor(player=self.player_3, team=self.team_1, from_date=datetime.date.today()) self.playfor_3.save() # create referee person = Person(first_name='Ref', last_name='Ref') person.save() self.referee = Referee(person=person) self.referee.save() # create two seasons self.season_1 = create_season(self.classification, 'Division 1', '2014-2015', datetime.date.today(), datetime.date.today()) self.season_2 = create_season(self.classification, 'Division 2', '2015-2016', datetime.date.today(), datetime.date.today()) # create some games self.matchday_season_1 = Matchday(season=self.season_1, label='1', date=datetime.date.today()) self.matchday_season_1.save() self.game_season_1 = Game(matchday=self.matchday_season_1, date=datetime.date.today(), away_team=self.team_1, home_team=self.team_2, referee=self.referee, played=True, field=self.field) self.game_season_1.save() self.matchday_season_2 = Matchday(season=self.season_2, label='2', date=datetime.date.today()) self.matchday_season_2.save() self.game_season_2 = Game(matchday=self.matchday_season_2, date=datetime.date.today(), away_team=self.team_1, home_team=self.team_1, referee=self.referee, played=True, field=self.field) self.game_season_2.save() def test_player_season(self): # add team to season self.season_1.enrolled.add(self.team_1) self.assertItemsEqual((self.team_1,), self.player_1.teams_per(self.season_1)) def test_goals_by_season(self): # 2 goals in season 1 by player 1 goal_1 = Goal(scored_by=self.playfor_1, scored_for=self.team_1, game=self.game_season_1) goal_1.save() goal_2 = Goal(scored_by=self.playfor_1, scored_for=self.team_1, game=self.game_season_1) goal_2.save() # 1 goal by player 1 in season 2 goal_x = Goal(scored_by=self.playfor_1, scored_for=self.team_1, game=self.game_season_2) goal_x.save() # 1 goal in season 2 by player 2 goal_3 = Goal(scored_by=self.playfor_2, scored_for=self.team_1, game=self.game_season_2) goal_3.save() # 1 own goal in season 1 by player 3 goal_4 = Goal(scored_by=self.playfor_3, scored_for=self.team_2, game=self.game_season_1) goal_4.save() self.assertIn(self.player_1, self.season_1.scorers()) self.assertNotIn(self.player_2, self.season_1.scorers()) self.assertNotIn(self.player_3, self.season_1.scorers()) self.assertEqual(3, self.season_1.count_goals()) self.assertEqual(2, self.season_1.scorers()[0].num_scored) def test_disciplinary(self): yellow_card_1 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_1) yellow_card_1.save() yellow_card_2 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_1) yellow_card_2.save() yellow_card_3 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_2) yellow_card_3.save() red_card_1 = Card(color='R', play_for=self.playfor_3, in_game=self.game_season_1) red_card_1.save() self.assertItemsEqual((self.playfor_1, self.playfor_3), self.season_1.booked_playfors()) self.assertEqual(2, self.season_1.booked_playfors()[0].num_of_cards) self.assertEqual(2, self.season_1.yellow_booked_playfors()[0].num_of_cards) self.assertItemsEqual((self.playfor_3,), self.season_1.red_booked_playfors()) self.assertEqual(1, self.season_1.red_booked_playfors()[0].num_of_cards) num_of_yellows = self.\ playfor_1.count_yellow_cards_per(self.season_1) self.assertEqual(num_of_yellows, 2) def test_get_season(self): # create two seasons classification = Classification(label='test mens') classification.save() competition = Competition( name='div 1', mode='l', classification=classification ) competition.save() season_1 = Season(label='s1', start_date=datetime.date.today(), end_date=datetime.date.today() + datetime.timedelta(365), competition=competition, published=True ) season_2 = Season(label='s2', start_date=datetime.date.today() + datetime.timedelta(365), end_date=datetime.date.today() + datetime.timedelta(730), competition=competition ) season_1.save() season_2.save() self.assertIn(season_1, Season.get_current_season_by_slugs('test-mens', 'div-1')) self.assertNotIn(season_2, Season.get_current_season_by_slugs('test-mens', 'div-1'))
class Match(Model): table_name = "matches" id = Field(int, modifiable=False) date = Field(datetime, default=datetime.now()) matchee_id = Field(int) matcher_id = Field(int) rating = Field(int, default=0) @staticmethod def get_likes(self, user_id): connection = pool.get_conn() with connection.cursor() as c: date_format = '%e %b %Y' c.execute( """ SELECT m.id, m.matcher_id, m.matchee_id, u.fname AS 'matchee_first_name', u.lname AS 'matchee_last_name', u.username AS 'matchee_username', DATE_FORMAT(m.date, %s) as date FROM matches m INNER JOIN users u ON m.matchee_id = u.id WHERE m.matcher_id = %s """, ( date_format, user_id, )) pool.release(connection) return c.fetchall() pool.release(connection) return None @staticmethod def get_liked_by(self, user_id): connection = pool.get_conn() with connection.cursor() as c: date_format = '%e %b %Y' c.execute( """ SELECT m.id, m.matcher_id, u.fname AS 'matcher_first_name', u.lname AS 'matcher_last_name', u.username AS 'matcher_username', m.matchee_id, DATE_FORMAT(m.date, %s) as date FROM matches m INNER JOIN users u ON m.matcher_id = u.id WHERE m.matchee_id = %s """, ( date_format, user_id, )) pool.release(connection) return c.fetchall() pool.release(connection) return None @classmethod def check_match(cls, matcher_id, matchee_id): temp = cls() connection = temp.pool.get_conn() with connection.cursor() as c: c.execute( """ SELECT EXISTS(SELECT * FROM matches WHERE matcher_id=%s and matchee_id=%s) as liked, EXISTS(SELECT * FROM matches WHERE matcher_id=%s and matchee_id=%s and liked=1) as matched from matches """, [matcher_id, matchee_id, matchee_id, matcher_id]) temp.pool.release(connection) return c.fetchone() temp.pool.release(connection) return None
def main(): pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Minesweeper") surface = pygame.display.get_surface() clock = pygame.time.Clock() field = Field() screen = pygame.display.set_mode(field.bound[2:]) mouse = (0, 0, 0) game_over = False while 1: clock.tick(60) surface.fill((255, 255, 255)) field.render(surface) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == KEYDOWN and event.key == K_r: field = Field() game_over = False elif event.type == KEYDOWN: mx, my = pygame.mouse.get_pos() if event.key == K_q: game_over = field.handle_open_left(mx, my) elif event.key == K_z: game_over = field.handle_press(mx, my) elif game_over: continue elif event.type == MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pressed() elif event.type == MOUSEBUTTONUP: mx, my = pygame.mouse.get_pos() if mouse[0] and mouse[2]: mouse = (0, 0, 0) game_over = field.handle_open_left(mx, my) elif mouse[0]: game_over = field.handle_press(mx, my) elif mouse[2]: field.handle_flag(mx, my)
def _create_form(form, title=None, description=None, readonly=False): """ Creates a form class object. Usage:: FormClass = _create_form(dataform="myForm") form = FormClass(data=request.POST) :param form: a data form slug or object :param title: optional title; pulled from DB by default :param description: optional description; pulled from DB by default :param readonly: optional readonly; converts form fields to be readonly. Usefull for display only logic. """ # Make sure the form definition exists before continuing # Slightly evil, do type checking to see if form is a DataForm object or string # If form object is a slug then get the form object and reassign if isinstance(form, str) or isinstance(form, unicode): try: form = DataForm.objects.get(visible=True, slug=form) except DataForm.DoesNotExist: raise DataForm.DoesNotExist( 'DataForm %s does not exist. Make sure the slug name is correct and the form is visible.' % form) # Otherwise it should be a form model object, if not raise elif not isinstance(form, DataForm): raise AttributeError('Dataform %s is not a valid data form object.' % form) meta = {} slug = form if isinstance(form, str) or isinstance(form, unicode) else form.slug final_fields = SortedDict() choices_dict = defaultdict(tuple) attrs = { 'declared_fields': final_fields, 'base_fields': final_fields, 'meta': meta, 'slug': slug, } # Parse the slug and create a class title form_class_title = create_form_class_title(slug) # Set the title and/or the description from the DB (but only if it wasn't given) meta['title'] = safe(form.title if not title else title) meta['description'] = safe( form.description if not description else description) meta['slug'] = form.slug # Get all the fields fields_qs = Field.objects.filter( dataformfield__data_form__slug=slug, visible=True).order_by('dataformfield__order') fields = [field for field in fields_qs.values()] if not fields: raise Field.DoesNotExist( 'Field for %s do not exist. Make sure the slug name is correct and the fields are visible.' % slug) # Get all the choices associated to fields choices_qs = (FieldChoice.objects.select_related( 'choice', 'field').filter(field__dataformfield__data_form__slug=slug, field__visible=True).order_by('order')) # Get the bindings for use in the Field Loop bindings = get_bindings(form=form) # Add a hidden field used for passing information to the JavaScript bindings function fields.append({ 'field_type': 'HiddenInput', 'slug': 'js_dataform_bindings', 'initial': safe(force_escape(json.dumps(bindings))), 'required': False, }) # Populate our choices dictionary for row in choices_qs: choices_dict[row.field.pk] += (row.choice.value, safe(row.choice.title)), # Process the field mappings and import any modules specified by string name for key in FIELD_MAPPINGS: # Replace the string arguments with the actual modules or classes for sub_key in ('class', 'widget'): if not FIELD_MAPPINGS[key].has_key(sub_key): continue value = FIELD_MAPPINGS[key][sub_key] if isinstance(value, str) or isinstance(value, unicode): names = value.split(".") module_name = ".".join(names[:-1]) class_name = names[-1] module = __import__(module_name, fromlist=[class_name]) # Replace the string with a class pointer FIELD_MAPPINGS[key][sub_key] = getattr(module, class_name) # Handle widget arguments if not FIELD_MAPPINGS[key].has_key('widget_kwargs'): # Initialize all field-mappings that don't have a 'widget_kwargs' key FIELD_MAPPINGS[key]['widget_kwargs'] = {} # ----- Field Loop ----- # Populate our fields dictionary for this form for row in fields: form_field_name = _field_for_form(name=row['slug'], form=slug) field_kwargs = {} field_map = FIELD_MAPPINGS[row['field_type']] widget_attrs = field_map.get('widget_attrs', {}) if row.has_key('label'): field_kwargs['label'] = safe(row['label']) if row.has_key('help_text'): field_kwargs['help_text'] = safe(row['help_text']) if row.has_key('initial'): field_kwargs['initial'] = row['initial'] if row.has_key('required'): field_kwargs['required'] = row['required'] additional_field_kwargs = {} if row.has_key('arguments') and row['arguments'].strip(): # Parse any additional field arguments as JSON and include them in field_kwargs temp_args = json.loads(str(row['arguments'])) for arg in temp_args: additional_field_kwargs[str(arg)] = temp_args[arg] # Update the field arguments with the "additional arguments" JSON in the DB field_kwargs.update(additional_field_kwargs) # Get the choices for single and multiple choice fields if row['field_type'] in CHOICE_FIELDS: choices = () # We add a separator for select boxes if row['field_type'] == 'Select': choices += ('', '--------'), # Populate our choices tuple choices += choices_dict[row['id']] field_kwargs['choices'] = choices if row['field_type'] in MULTI_CHOICE_FIELDS: # Get all of the specified default selected values (as a list, even if one element) field_kwargs['initial'] = (field_kwargs['initial'].split(',') if ',' in field_kwargs['initial'] else [ field_kwargs['initial'], ]) # Remove whitespace so the user can use spaces field_kwargs['initial'] = [ element.strip() for element in field_kwargs['initial'] ] else: field_kwargs['initial'] = ''.join(field_kwargs['initial']) if readonly: widget_attrs['readonly'] = 'readonly' widget_attrs['disabled'] = "disabled" # Add our additional css classes if row.has_key('classes'): existing_widget_attrs = widget_attrs.get('class', '') widget_attrs['class'] = existing_widget_attrs + ' '.join( row['classes'].split(',')).strip() # Add bindings css class #FIXME: Should we be adding this on the widget or field? if row['field_type'] != 'HiddenInput': if not 'dataform-field' in widget_attrs['class']: widget_attrs['class'] += " dataform-field" # Instantiate the widget that this field will use # TODO: Possibly create logic that passes submissionid to file upload widget to handle file # paths without enforcing a redirect. if field_map.has_key('widget'): field_kwargs['widget'] = field_map['widget']( attrs=widget_attrs, **field_map['widget_kwargs']) # Add this field, including any widgets and additional arguments # (initial, label, required, help_text, etc) final_field = field_map['class'](**field_kwargs) final_field.is_checkbox = (row['field_type'] == 'CheckboxInput') final_field.dataform_key = row['field_type'] final_fields[form_field_name] = final_field # Grab the dynamic validation function from validation.py if validation: validate = getattr(validation, form_class_title, None) if validate: # Pull the "clean_" functions from the validation # for this form and inject them into the form object for attr_name in dir(validate): if attr_name.startswith('clean'): attrs[attr_name] = getattr(validate, attr_name) # Return a class object of this form with all attributes DataFormClass = type(form_class_title, (BaseDataForm, ), attrs) # Also return the querysets so that they can be re-used query_data = { 'dataform_query': form, 'choice_query': choices_qs, 'field_query': fields_qs, 'fields_list': fields, } return DataFormClass, query_data
def pipeline(abspath,session): #par() is parseXML_diclist() import from parse.py d=par(abspath) # d["Document"] is a list of dictionary # as there is only one dict in this list. # so by d['Document'][0] # we directly get a document_dictionary: doc. doc=d["Document"][0] # the argument **doc is keyword argument. # we initialize Document with dictionary: doc # then we get a model object doc_t doc_t=Document(**doc) # this object should be add to session, otherwise you cannot find it in session. session.add(doc_t) # jour is the same pattern. jour=d['Journal'][0] jour_t=Journal(**jour) # here, for the documents column, we add doc_t to it. jour_t.documents.append(doc_t) session.add(jour_t) # we use loop here, because len(d['Author']) != 1 for auth in d["Author"]: # we first check whether there is the same author in this session auth_t = session.query(Author).filter_by(full_name=auth["full_name"]).first() if auth_t == None: auth_t = Author(**auth) # if there exits this author, update his or her information else: for k, v in auth.items(): auth_t.__setattr__(k,v) # append doc_t auth_t.documents.append(doc_t) session.add(auth_t) for key in d["Keyword"]: # some documents may not have keywords # if we omit this line, an Error will be raised. if len(key) != 0: key_t=session.query(Keyword).filter_by(keyword=key["keyword"]).first() if key_t == None: key_t = Keyword(**key) else: for k,v in key.items(): key_t.__setattr__(k,v) key_t.documents.append(doc_t) session.add(key_t) for fld in d["Field"]: fld_t=session.query(Field).filter_by(name=fld["name"],value=fld["value"],type=fld["type"]).first() if fld_t == None: fld_t = Field(**fld) else: for k,v in fld.items(): fld_t.__setattr__(k,v) fld_t.documents.append(doc_t) session.add(fld_t)
# # Hard: Solved with brute force # field_data = [ # [0, 0, 8, 0, 5, 0, 0, 0, 2], # [0, 2, 0, 0, 9, 0, 0, 4, 1], # [0, 0, 4, 0, 3, 0, 0, 0, 9], # # [0, 0, 0, 0, 0, 0, 0, 1, 8], # [0, 0, 0, 0, 0, 0, 0, 0, 0], # [5, 7, 0, 4, 0, 0, 2, 0, 0], # # [0, 0, 0, 0, 0, 7, 0, 0, 3], # [0, 0, 7, 0, 6, 0, 4, 0, 0], # [0, 6, 1, 3, 0, 0, 0, 9, 0], # ] # Extreme: Solved with brute force field_data = [ [0, 6, 0, 4, 0, 3, 0, 7, 0], [7, 5, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 0, 0, 0], [0, 0, 0, 0, 0, 9, 8, 6, 0], [0, 0, 0, 0, 8, 1, 0, 0, 7], [4, 0, 0, 0, 5, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 8, 0], [0, 2, 0, 0, 0, 0, 1, 0, 0], [6, 3, 0, 0, 0, 0, 5, 0, 0], ] sudoku_field = Field.init_from_data(field_data) SudokuSolver.solve(sudoku_field, with_brute_force=True)
class User(Model): username = Field("") password = Field("") email = Field("")
class PlaceField(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.field = Field() self.buttons = {} self.next_btn = None self.init_visual() def init_visual(self): main_layout = QGridLayout() label = QLabel('Place your ships.') randomize_btn = QPushButton(text='randomize') randomize_btn.clicked.connect(self.randomize_field) internal_layout = QGridLayout() internal_layout.setSpacing(0) for row in range(10): for column in range(10): button = QPushButton() button.setFixedSize(20, 20) button.setObjectName(f'{row}_{column}') button.installEventFilter(self) self.buttons[(row, column)] = button internal_layout.addWidget(button, row, column) self.next_btn = QPushButton(text='Start') self.next_btn.clicked.connect(root_widget.start_battle) self.next_btn.setEnabled(False) main_layout.addWidget(label, 0, 0, Qt.AlignCenter) main_layout.addWidget(randomize_btn, 1, 0) main_layout.addLayout(internal_layout, 3, 0) main_layout.addWidget(self.next_btn, 5, 0) self.setLayout(main_layout) def randomize_field(self): self.field = Field.randomize() for button in self.buttons.values(): button.setText('') for ship in self.field.ships: for row, col in ship.coordinates: self.buttons[(row, col)].setText(str(ship.length)) self.next_btn.setEnabled(True) def rotate_ship(self, ship): old_coordinates = ship.coordinates try: new_coordinates = self.field.rotate_ship(ship) except ValueError: return for _row, _col in old_coordinates: if (_row, _col) not in new_coordinates: self.buttons[_row, _col].setText('') for _row, _col in new_coordinates: self.buttons[_row, _col].setText(str(ship.length)) def place_ship(self, row, col): try: unplaced_ship: Ship = next(self.field.unplaced_ships()) except StopIteration: return try: fields = self.field.place(unplaced_ship, row, col, Direction.horizontal) except ValueError: try: fields = self.field.place(unplaced_ship, row, col, Direction.vertical) except ValueError: return for _row, _col in fields: self.buttons[_row, _col].setText(str(unplaced_ship.length)) try: next(self.field.unplaced_ships()) except StopIteration: self.next_btn.setEnabled(True) def delete_ship(self, ship): old_coordinates = ship.coordinates for _row, _col in old_coordinates: self.buttons[_row, _col].setText('') ship.unplace() self.next_btn.setEnabled(False) def eventFilter(self, obj, event): if event.type() == QEvent.MouseButtonPress: row, col = map(int, obj.objectName().split('_')) covering_ship: Ship = self.field.covering_ship(row, col) if event.button() == Qt.LeftButton: if covering_ship: self.rotate_ship(covering_ship) else: self.place_ship(row, col) elif event.button() == Qt.RightButton and covering_ship: self.delete_ship(covering_ship) return QObject.event(obj, event)
def test_field(self): field = Field(name='BMW', number='5544', date='2018-09-17') db.session.add(field) db.session.commit() assert field.name == 'BMW'
paradigm_persp = dict() group_to_group = dict() for table in [Group]: DBSession.execute( 'select setval (\'%s_id_seq\', %s);' % ( table.__tablename__, DBSession.query(func.max(table.id).label("id")).one().id + 1)) for field in old_DBSession.query(old_Field).filter_by(marked_for_deletion=False).all(): parent_ids = perspective_ids.get(str(field.parent_client_id) + '_' + str(field.parent_object_id), None) if not parent_ids: parent_ids = {'client_id': None, 'object_id': None} continue new_field = fields.get(field.entity_type, None) if not new_field: new_field = Field(client_id=field.client_id, translation_gist_client_id=translation_strings[field.entity_type]['ids']['client_id'], translation_gist_object_id=translation_strings[field.entity_type]['ids']['object_id'], data_type_translation_gist_client_id=translation_strings[field.data_type]['ids']['client_id'], data_type_translation_gist_object_id=translation_strings[field.data_type]['ids']['object_id']) if 'translation' in field.entity_type.lower() or field.entity_type.lower() == 'text': # todo: looks too bad new_field.is_translatable = True DBSession.add(new_field) DBSession.flush() fields[field.entity_type] = {'client_id': new_field.client_id, 'object_id': new_field.object_id} else: new_field = DBSession.query(Field).filter_by(client_id=new_field['client_id'], object_id=new_field['object_id']).first() if 'aradigm' in field.entity_type: parent_ids = paradigm_persp.get(str(field.parent_client_id) + '_' + str(field.parent_object_id), None) if not parent_ids: