def interface(object_file_names, settings, sections, board, demo_id): while True: cmd = input("\n[t][s][q][enter]=> ") if cmd == "t": tickets = Section.tickets_keys_on_board(sections) print(f"Tickets: {tickets}") if len(tickets) > 0: cmd = input("Choose a ticket=> ") while cmd not in tickets: cmd = input("Not a valid number. Choose again=> ") print(Section.get_ticket(cmd, sections)) elif cmd == "s": print(f"Sections: {sections.keys()}") if len(sections.keys()) > 0: cmd = input("Choose a section=> ") while cmd not in sections.keys(): cmd = input("Not a valid number. Choose again=> ") print(sections[cmd]) elif cmd == "q": board.ticket_collection = None board.section_collection = None save_pickle_files(object_file_names, settings, sections, board) logging.warning("Exiting program!") sys.exit() else: return cmd = ""
def create_section_from_info(info): section = Section(info["start_point"], get_end_point(), info["is_steps"], 0, info["ground_type"]) if "steps_num" in info.keys(): section.steps_num = info["steps_num"] if "rail" in info.keys(): section.rail = info["rail"] return section
def get_note_and_section_name(self, section_name): note_name = self.get_text("یادداشت جدید", "نام یادداشت:") if not note_name: reply = QMessageBox.question( self, 'پیام', "نام خالی است. دوباره امتحان میکنید؟", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.get_note_and_section_name() else: return if section_name is None: section_name = self.get_text("بخش", "نام بخش:") if not note_name: reply = QMessageBox.question( self, 'پیام', "نام بخش خالی است. دوباره امتحان میکنید؟", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.get_note_and_section_name() else: return section = None for s in self.notebook.sections: if s.name == section_name: section = s if section is None: section = Section(section_name) self.notebook.add_section(section) note = Note(note_name, "") section.add_note(note) return note, section_name
def __init__(self, fileName, keys, stick, stones, helps, ball, bar, rightBall, level, game): """ Initialize a challenge @param self -- the challenge @param fileName -- a string that contains the sound name @param keys -- the key vector @param stick -- the stick @param stones -- the stones @param helps -- the helps @param ball -- the left ball that it is used in the animation @param bar -- the grey bar that it is used in the animation @param rightBall -- the right ball that it is used in the animation @param level -- the challenge level @param game -- the game """ self.fileName = fileName self.music = Sound() self.music.setFileName("sound/music/" + fileName) self.section = Section() self.section.setFileName("sound/section/" + fileName) self.section.setKeys(keys) self.stick = stick self.animation = Animation(stones, keys, helps, ball, rightBall, bar, game) self.ball = ball self.level = level self.attempts = 0 self.game = game
def setSound(self, sectionFileName): """ Set a sound ball @param self -- the ball @param sectionFileName -- a related section filename """ self.sectionFileName = sectionFileName self.section = Section() self.section.setFileName("sound/section/" + sectionFileName)
def createSection(self, boardId, sectionTitle): section = Section(title=sectionTitle) section.save() sectionId = section.id board = self.__getBoardById(boardId) board.addSectionId(sectionId) return sectionId
def __init__(self, name, colour, startAngle, angle): Section.__init__(self, name, colour) self.angle = angle self.startAngle = startAngle self.endAngle = (startAngle+angle) self.centerX = 11989.075 self.centerY = 4827.0225 self.radius = 2705.4143 self.realCenterX = SettingsCloud.getParameter("centerCoordinateX") self.realCenterY = SettingsCloud.getParameter("centerCoordinateY") if self.realCenterX == None: self.realCenterX = 0 if self.realCenterY == None: self.realCenterY = 0
def __init__(self, name, colour, startAngle, angle): Section.__init__(self, name, colour) self.angle = angle self.startAngle = startAngle self.endAngle = (startAngle + angle) self.centerX = 11989.075 self.centerY = 4827.0225 self.radius = 2705.4143 self.realCenterX = SettingsCloud.getParameter("centerCoordinateX") self.realCenterY = SettingsCloud.getParameter("centerCoordinateY") if self.realCenterX == None: self.realCenterX = 0 if self.realCenterY == None: self.realCenterY = 0
def __init__(self, name, size): """Инициализация Организации Параметры функции: - name - название организации - size - количество отделов Свойства: _name - название организации _size - максимальное количество отделов _section - ссылка на список отделов _count - количество добавленных отделов""" self._name = name self._size = size self._section = Section("start") self._count = 0
def Add_section(self): """Метод добавления нового отдела""" os.system("clear") # Проверка на заполненность списка отделов if self._count < self._size: # Добавление первого отдела if self._count == 0: section_name = "" # Ввод названия отдела while not section_name.isalpha(): os.system("clear") section_name = input("Введите название отдела: ") new_section = Section(section_name) self._section.Set_right(new_section) self._count += 1 # Добавление 2-го и более отдела else: search = "" # Поиск отдела while not search.isalpha(): os.system("clear") print("Поиск отдела до или после которого хотите добавить") search = input("Название отдела: ") choice = 0 # Выбор добавления до или после while choice != 1 and choice != 2: # Защита от ввода букв try: print("1 - добавить до\n2 - добавить после") choice = int(input("Ваш ответ: ")) except ValueError: os.system("clear") print("Ошибка! Введите число 1 или 2") finded_section = self.Check_add_section(search, choice) # Отдел найден if finded_section != False: new_name = "" # Ввод названия нового отдела while not new_name.isalpha(): new_name = input("Введите название отдела: ") new_section = Section(new_name) new_section.Set_right(finded_section.Get_right()) finded_section.Set_right(new_section) self._count += 1 # Отдел не найден else: print("Отдел не найден!") # Список заполнен else: print("Количество отделов заполнено")
def find_sections(image, border, sections, board_settings): thresholded = utils.threshold(image, board_settings["grid_color"]) dilated = utils.dilate(thresholded, iter_num=int(board_settings["dilation"])) eroded = utils.erode(dilated, iter_num=int(board_settings["erosion"])) black_sections = cv2.bitwise_or(eroded, border) white_sections = cv2.bitwise_not(black_sections) im, contours, hierarchy = cv2.findContours(white_sections.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) contours = sorted(contours, key=cv2.contourArea, reverse=True) for i in range(len(contours)): if cv2.contourArea(contours[i]) * int(board_settings[ "min_section_scale"]) > image.shape[0] * image.shape[1]: section_num = i + 1 cimg = np.zeros_like(white_sections) cv2.drawContours(cimg, contours, i, color=255, thickness=-1) rect = cv2.boundingRect(contours[i]) sections[str(section_num)] = Section(cimg, str(section_num), rect) else: break return sections
def split_to_sections(points_list, nodes_info) -> list: """ :param points_list: list of points of type Point (from Section) :return list of sections, such that each geographical parameter is valid to all of it """ sections = [] start = points_list[0] info = fetch_point_info(start, nodes_info) sec = create_section_from_info(info) sections.append(sec) for point in points_list[1:]: info = fetch_point_info(point, nodes_info) if info: next_sec = create_section_from_info(info) if Section.check_if_dff(sec, next_sec): sections.append(next_sec) sec = next_sec start_sec = sections[0] for section in sections[1:]: end_sec = section start_sec.end_point = end_sec.start_point start_sec.length = Point.calc_distance(start_sec.start_point, start_sec.end_point) start_sec = end_sec return sections
def populateSections(newsDate, articlesInSection): """Returns a list of Section objects """ sections = [] for section_title, articles in list(articlesInSection.items()): sectionObj = Section(section_title,articles, newsDate) sections.append(sectionObj) return sections
def load_sections(filename): filepath = basepath + filename df = pandas.read_csv(filepath) sections = {} for _, row in df.iterrows(): section = Section(row['SEC11'], row['lat'], row['lon']) sections[row['SEC11']] = section return sections
def __init__(self, json_data): self.boardNum = 0 self.array = [] self.lowProbabilityCell = None self.newSolvedQueue = [] self.oldSolvedQueue = [] self.sections = [] # Populate cells onto the board for row in range(9): row_array = [] for col in range(9): row_array.append(Cell(row, col)) self.array.append(row_array) # Set initial conditions for jsonObj in json_data: self.array[jsonObj['row']][jsonObj['column']].set_value( jsonObj['value']) self.newSolvedQueue.append( self.array[jsonObj['row']][jsonObj['column']]) # Setup sections for rowSection in range(3): for colSection in range(3): current_section = [] for actualRow in range(3): for actualCol in range(3): current_section.append( self.array[rowSection * 3 + actualRow][colSection * 3 + actualCol]) self.sections.append(Section(current_section)) for rowSection in range(9): current_section = [] for curCol in range(9): current_section.append(self.array[rowSection][curCol]) self.sections.append(Section(current_section)) for colSection in range(9): current_section = [] for curRow in range(9): current_section.append(self.array[curRow][colSection]) self.sections.append(Section(current_section))
def json_to_notebook(nb): nb = json.loads(nb) notebook = Notebook(nb[0]) for s in nb[1]: print(s[0]) notebook.add_section(Section(s[0])) for n in s[1]: print(n) notebook.sections[-1].add_note(Note(n[0], n[1])) return notebook
def handle_add_section(self): section_name = self.get_text("بخش جدید", "نام بخش:") if not section_name: reply = QMessageBox.question( self, 'پیام', "نام بخش خالی است. دوباره امتحان میکنید؟", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.handle_add_section() else: return self.notebook.add_section(Section(section_name)) self.network.update_notebook(self.notebook)
def section_start(self): """Create new section instance and start it.""" sectioninfo = self.data[self.section_num] # generate the object for the next section self.section = Section(self.mediadir, sectioninfo.copy(), self.on_section_end, self.ctrl.timestamp) self.ctrl.add_model(self.section) for view in self.views: view.add_model(self.section) self.section.run()
def parse_section(soup, section_number): curr_section = Section() curr_section.section_number = section_number curr_section.type = get_soup_string_value(soup.find("type")) curr_section.days_of_the_week = get_soup_string_value( soup.find("daysoftheweek")) startString = get_soup_string_value(soup.find("start")) curr_section.start_time = parse_time(startString) endString = get_soup_string_value(soup.find("end")) curr_section.end_time = parse_time(endString) return curr_section
def find_limits(state, sections, ticket_settings, section_data): c_i = state.curr_image.copy() b_i = state.background_image.copy() diff_mask = difference_mask(c_i, b_i, ticket_settings) limit = "" for section_num, section in sections.items(): if section.function == Function.LIMIT: mask = cv2.bitwise_and(section.mask, diff_mask) _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) contour = sorted(contours, key=cv2.contourArea, reverse=True) if len(contour) > 0: contour = contour[0] else: continue x, y, w, h = cv2.boundingRect(contour) if h > 40 and w > 40: thresh_limit, colored_limit = cluster(c_i[y:y + h, x:x + w]) limit = find_numbers_in_mask(thresh_limit, colored_limit, state.classifier, ticket_settings["Digits"]) if limit != "" and limit != 0: prev_limit = section_data[section.name] section_data[section.name] = int(limit) Section.map_section_names(sections, section_data) if int(prev_limit) != int(limit): logging.info( f"SECTION - The \"{section.name}\" has changed from {prev_limit} to {limit} (ID:#{section_num})" ) state.board_sections = state.draw_section_rectangles( sections) return sections, section_data
def Download_from_file(self): """Загрузка из файла""" self.All_dell() section = self._section # Обработчик исключений try: new_line = "" # Открытие файла data.txt на чтение with open("data.txt", "r") as f: # Проход по строкам файла while True: new_line = f.readline() new_line = new_line.strip(" \n") # Если строка пуста, то завершается загрузка из файла if len(new_line) == 0: break # Строка содержит метку отдела if new_line == "Отдел:": new_line = f.readline() new_line = new_line.strip(" \n") # проверка на наличие ошибок в названии отдела if not new_line.isalpha(): print("Ошибка в названии отдела в файле!") break # Добавление отдела, если список не заполнен if self._count < self._size: new_section = Section(new_line) section.Set_right(new_section) section = new_section self._count += 1 # Максимальное количество отделов заполнено else: print("Ошибка! Число отдедов превышено.") break # Строка содержит метку сотрудника elif new_line == "Сотрудник:": new_line = f.readline() new_line = new_line.strip(" \n") major_line = f.readline() major_line = major_line.strip(" \n") # Данные полей сотрудника имеют ошибки if not new_line.isalpha() or not major_line.isalpha(): print("Ошибка в файле!В полях сотрудника должны быть только буквы!") break section.Download_add(new_line, major_line) # Строка не равна ни одной метке else: print("Ошибка!") except FileNotFoundError: print("Файл не найден в данной директории!")
def __init__(self, survey_name): self.survey_sections = {} self.survey_name = survey_name self.user_q_answers = [] self.eligiable_section = 'You are not qualified' self.questions_section_1 = [ 'Q1-1?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', 'Q1-2?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', 'Q1-3?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', ] self.section_1 = Section( 'section1', 'This is section 1 and because of the quilifying question 1', self.questions_section_1) self.questions_section_2 = [ 'Q2-1?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', 'Q2-2?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', 'Q2-3?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', ] self.section_2 = Section( 'section2', 'This is section 2 and because of the quilifying question 2', self.questions_section_2) self.questions_section_3 = [ 'Q3-1?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', 'Q3-2?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', 'Q3-3?\n a: Answer 1\n b: Answer 2\n c: Answer 3\n', ] self.section_3 = Section( 'section3', 'This is section 3 and because of the quilifying question 3', self.questions_section_3) self.survey_sections = { 0: self.section_1, 1: self.section_2, 2: self.section_3 }
def default(self, d): if d is None: return None if 'name' in d and 'section_list' in d: object = Course(d) section_list_dict = d["section_list"] object.section_list = list() for section_dict in section_list_dict: object.section_list.append(self.default(section_dict)) return object elif 'section_number' in d and 'type' in d: object = Section(d) return object else: return d
def test_get_internal_force(self): true = self.assertTrue n1 = Node(1, Point()) n2 = Node(2, Point(4, 3, 0)) section = Section(1, 0, 1000, 0, 0.1, 0, 0.001, 0) beam = Beam2D(1, n1, n2, section, 0) dofs1 = beam.node1.dofs dofs1[0].d = 0.1 dofs1[1].d = 0.1 force = beam.get_internal_force('d', 'pos_origin') ans = array([[2.238848], [1.681536], [-0.0048], [-2.238848], [-1.681536], [-0.0048]]) for i in range(6): true(isclose(force[i, 0], ans[i, 0]))
def test_get_global_stiffness(self): true = self.assertTrue n1 = Node(1, Point()) n2 = Node(2, Point(4, 3, 0)) section = Section(1, 0, 1000, 0, 0.1, 0, 0.001, 0) beam = Beam2D(1, n1, n2, section, 0) q = beam.get_global_stiffness('pos_origin') a = array([[12.83456, 9.55392, 0.144, -12.83456, -9.55392, 0.144], [9.55392, 7.26144, -0.192, -9.55392, -7.26144, -0.192], [0.144, -0.192, 0.8, -0.144, 0.192, 0.4], [-12.83456, -9.55392, -0.144, 12.83456, 9.55392, -0.144], [-9.55392, -7.26144, 0.192, 9.55392, 7.26144, 0.192], [0.144, -0.192, 0.4, -0.144, 0.192, 0.8]]) for i in range(6): for j in range(6): true(isclose(q[i, j], a[i, j]))
def load_sections(self): """ This method will load all of the sections to the template. Each section will become its own attribute according to the template e.g. logon_username section will turn into t.logon_username which is type(t.logon_username) == Sections() """ config = RawConfigParser() config.read(self.file_path) sections = config._sections for sec in sections: new_section = Section() new_section.set_name(sec) new_section.template = self for attr in sections[sec]: new_section.set_attribute(attr, sections[sec][attr]) setattr(self, sec, new_section)
def __init__(self, config): """ The class is initialized with a path to a configuration file passed via config, or a file-like object. """ self.parser = SafeConfigParser() if isinstance(config, basestring): self.config_path = config config = open(self.config_path, "r") else: self.config_path = None self.parser.readfp(config) for section in self.parser.sections(): options = self.parser.items(section) options = map(lambda op: Option(*op), options) self.add_section(Section(section, options))
def add_section(self, section): """ Adds a new section to the config. If section is str, it's converted to Section object. If section is Section, it's left untouched. If a section with the same name does not already exists in the config, it's added, and the function returns True. If such section already exists, the call is ignored, and the function return False. """ if isinstance(section, Section): section_name = section.name elif isinstance(section, str): section_name = section section = Section(section) else: raise TypeError("section should be either str or Section") if not self.__dict__.has_key(section_name): setattr(self, section_name, section) return True else: return False
) # under construction # 目標はradare2の劣化版みたいな解析機能 parser.add_argument("--detail", help="analyze binary for detail information", action="store_true") args = parser.parse_args() # analyze binary # todo: 不要な解析を無視 elf = ELF(args.elf) # _write4 libc = ELF(args.libc) if args.libc else None sect = Section(elf) functions = Functions(elf) plt = elf.plt got = elf.got # dump simple if not args.symbols: print("") # dump sections print("[+]: all sections") sect.dump_all_sections() print("") # all functions # todo: 関数の中身を調べる方法(ローカル変数の数やできるなら初期値も調べたい) print("[+]: all functions")
Question('Question 2', '(a) \n(b) \n(c) \n(d) \n'), Question('Question 3', '(a) \n(b) \n(c) \n(d) \n') ] # Create a new instance of the Survey class called my_survey and pass it the qualifying questions my_survey = Survey(qualifying_questions) # Run the start survey method on the new instance of Survey my_survey.start_survey() # Run the ask qualifying questions method my_survey.ask_qualifying_questions() # Create a new instance of the Section class called wednesday_section wednesday_section = Section( 'This section will ask you 3 questions about the Wednesday night tutorials', wednesday_questions) saturday_section = Section( 'This section will ask you 3 questions about the Saturday workshops', saturday_questions) # Run the wednesday section IF qualifying question 1 was answered with 'a' if my_survey.user_answers_qualifying[0] == 'a': wednesday_section.start_wednesday_section() else: print('Catch up section') if my_survey.user_answers_qualifying[1] == 'a': saturday_section.start_saturday_section() else: print('Catch up section')
def __init__(self, name, colour, startCoordinate, width): Section.__init__(self, name, colour) self.startCoordinate = startCoordinate self.width = width
class Experiment: """ Experiment class. Takes care of the experiment presentation (window, ... control) will work one experiment file and control the flow of sections. "Experiment"-level stuff. """ def __init__(self, views, ctrl, experiment_data, filename, mediadir, on_experiment_done): """Constructor.""" self.experiment_id = filename self.data = experiment_data self.ctrl = ctrl self.on_experiment_done = on_experiment_done self.section_num = -1 self.section = None self.views = views self.mediadir = mediadir self.section_prepare(0) def stop(self): """Stop experiment.""" if self.section is not None: self.section.stop() def next_phase(self): """Jump to next phase.""" if self.section is not None: self.section.next_phase() def section_prepare(self, nextsection): """Perform pre-section opearations.""" # end experiment? if nextsection >= len(self.data): glib.idle_add(self.on_experiment_done) return False self.section_num = nextsection sectioninfo = self.data[self.section_num] if "collect_data" in sectioninfo["options"]: # check if the user wanted to start data collection on all devices # or just one? self.ctrl.start_collecting_data(sectioninfo["name"]) glib.idle_add(self.section_start) def section_start(self): """Create new section instance and start it.""" sectioninfo = self.data[self.section_num] # generate the object for the next section self.section = Section(self.mediadir, sectioninfo.copy(), self.on_section_end, self.ctrl.timestamp) self.ctrl.add_model(self.section) for view in self.views: view.add_model(self.section) self.section.run() def on_section_end(self): """Callback for section_end.""" for view in self.views: view.remove_model(self.section) self.section = None sectioninfo = self.data[self.section_num] if "collect_data" in sectioninfo["options"]: glib.idle_add(self.ctrl.stop_collecting_data, self.on_saving_data_completed) else: glib.idle_add(self.on_saving_data_completed) def on_saving_data_completed(self): """Callback for saving_data_completed.""" sectioninfo = self.data[self.section_num] # check if next section to begin automatically if "autocontinue" in sectioninfo["options"] and \ self.section_num != len(self.data): self.section_prepare(self.section_num+1) else: self.ctrl.on_section_completed(self.section_num, len(self.data)) def __del__(self): """Destructor for the experiment class.""" for view in self.views: view.stop() self.views = None print "Experiment finished."
class Challenge: def __init__(self, fileName, keys, stick, stones, helps, ball, bar, rightBall, level, game): """ Initialize a challenge @param self -- the challenge @param fileName -- a string that contains the sound name @param keys -- the key vector @param stick -- the stick @param stones -- the stones @param helps -- the helps @param ball -- the left ball that it is used in the animation @param bar -- the grey bar that it is used in the animation @param rightBall -- the right ball that it is used in the animation @param level -- the challenge level @param game -- the game """ self.fileName = fileName self.music = Sound() self.music.setFileName("sound/music/" + fileName) self.section = Section() self.section.setFileName("sound/section/" + fileName) self.section.setKeys(keys) self.stick = stick self.animation = Animation(stones, keys, helps, ball, rightBall, bar, game) self.ball = ball self.level = level self.attempts = 0 self.game = game def start(self): """ Start a challenge @param self -- the challenge """ if os.path.exists("sound/section/" + self.fileName + ".wav"): self.section.play() self.game.statusBar.setText(_("Discover the next musical note")) self.animation.playIntroduction() self.ball.setSound(self.fileName) def change(self): """ Change a challenge @param self -- the challenge """ if os.path.exists("sound/section/" + self.fileName + ".wav"): self.section.play() self.game.statusBar.setText(_("Discover the next musical note")) self.animation.playIntroduction() self.ball.setSound(self.fileName) def finish(self): """ Finish a challenge @param self -- the challenge """ if os.path.exists("sound/music/" + self.fileName + ".ogg"): self.music.play() self.game.currentChallenge = None self.game.statusBar.setText(_("Congratulations!!! You completed the challenge! Choose other to continue playing.")) self.stick.setVisible(False) self.animation.playClosing() self.game.setPoints(self.level, self.attempts) def attempt(self, id): """ Verify a attempt @param self -- the challenge @param id -- the key index """ if self.section.isCurrentKey(id): self.game.setBufferPoints(self.level, self.attempts) self.attempts = 0 if self.section.isLastKey(): self.finish() else: self.animation.lowStone(self.section.currentKey) self.section.currentKey = self.section.currentKey + 1 self.game.statusBar.setText(_("Discover the next musical note")) else: self.attempts = self.attempts + 1 if self.section.moreThan(id): self.game.statusBar.setText(_("Try a lower note")) else: self.game.statusBar.setText(_("Try a higher note")) def getBall(self): """ Get the ball @param self -- the challenge """ return self.ball