def _edit(): ''' Edit existing Index object Step 1: Index name. Valid characters are a-z, A-Z, whitespace and commas. Step 2: Ticker list. Valid commands are \'add\' and \'remove\' ''' print('Choose Index to edit.') print('Available indices: {}'.format(CACHED_IND_NAMES)) response = parse_input('>>> ', lambda s: s in CACHED_IND_NAMES, 'Index does not exist', _edit) if response: idx = CACHED_IND_NAMES.index(response) ind = CACHED_INDICES[idx] print('Index name: {}'.format(ind.name)) print('Tickers: {}'.format(list(ind.tick_items.keys()))) print('Enter \'add\' or \'remove\' to edit ticker list') action = True while action: action = parse_input('>>> ', lambda s: s in ['ADD', 'REMOVE'], 'Invalid command.', _edit) if action == 'ADD': _add_tickers(ind) elif action == 'REMOVE': _remove_tickers(ind)
def test_parse_input(self): """Test utils input parser. Test input parser with valid and invalid sequences. Returns OK when successful. """ self.assertEqual(utils.parse_input("E"), (True, ["E"])) self.assertEqual(utils.parse_input("NESO"), (True, ["N", "E", "S", "O"])) self.assertEqual(utils.parse_input("EQ"), (False, ["E"])) self.assertEqual(utils.parse_input("QE"), (False, [])) self.assertEqual(utils.parse_input("1"), (False, []))
def setData(self, index: QModelIndex, value: str, role=Qt.EditRole): if not index.isValid() or role != Qt.EditRole or self.rowCount() <= index.row(): return False try: float_value = utils.parse_input(value) if index.column() in (self.Column.AMPLITUDE, self.Column.DOWN_VALUE, self.Column.UP_VALUE): float_value = clb.bound_amplitude(float_value, self.signal_type) elif index.column() == self.Column.FREQUENCY: float_value = clb.bound_frequency(float_value, self.signal_type) self.__points[index.row()][index.column()] = float_value self.dataChanged.emit(index, index) if index.column() in (self.Column.AMPLITUDE, self.Column.DOWN_VALUE, self.Column.UP_VALUE): if index.column() != self.Column.DOWN_VALUE: self.__recalculate_parameters(index.row(), PointData.ApproachSide.UP) if index.column() != self.Column.UP_VALUE: self.__recalculate_parameters(index.row(), PointData.ApproachSide.DOWN) if index.column() == self.Column.AMPLITUDE: # Это нужно, чтобы цвета ячеек Нижнее значение и Верхнее значение обновлялись сразу после изменения # ячейки Поверяемая точка up_value_index = self.index(index.row(), self.Column.UP_VALUE) down_value_index = self.index(index.row(), self.Column.DOWN_VALUE) self.dataChanged.emit(up_value_index, up_value_index) self.dataChanged.emit(down_value_index, down_value_index) return True except ValueError: return False
def examples_with_aggregated_gauss(subset): planets = get_planets(subset) os.makedirs('gauss_aggregated', exist_ok=True) for planet in tqdm(planets): pickle_path = 'gauss_aggregated/{}.pickle'.format(planet) if not os.path.exists(pickle_path): data = None planet_matrix = np.zeros((10, 55, 300), dtype=np.float32) for spot in range(1, 11): spot_matrix = np.zeros((55, 300), dtype=np.float32) for gaus in range(1, 11): data = parse_input( '../database/noisy_{}/{}_{:0>2}_{:0>2}.txt'.format( subset, planet, spot, gaus)) spot_matrix += data['matrix'] spot_matrix /= 10 planet_matrix[spot - 1] = 1 - spot_matrix data['matrix'] = planet_matrix out_path = '../database/params_train/{}_01_01.txt'.format(planet) if os.path.exists(out_path): data.update(parse_output(out_path)) data['planet'] = planet pickle.dump(data, open(pickle_path, 'wb'))
def main(): # Parse program flags parser = argparse.ArgumentParser(description="Ash goes looking for pokemons in bidimensional field. Each position around him has one single pokemon.") parser.add_argument("-b", "--benchmark", action="store_true", help="benchmark time") args = parser.parse_args() ash = Ash() print("Bem-vindo Ash!") while True: sequence = utils.read_input() start = time.perf_counter() #start timer for benchamrk validated_sequence = utils.parse_input(sequence) if validated_sequence[0]: for direction in validated_sequence[1]: ash.move(direction) else: print("Sequência inválida") break end = time.perf_counter() #end timer for benchmark print("Total de pokemons apanhados: " + str(ash.get_pokemons())) if args.benchmark: #if program in benchmark mode print("Tempo de execução: " + str(end-start) + " segundos") continue_flag = str(input("\nContinuar(s/n): ")) if re.match("[s]", continue_flag) and len(continue_flag) == 1: pass elif re.match("[n]", continue_flag) and len(continue_flag) == 1: print("\nAdeus Ash!") break else: print("Comando inválido") break
def solve_it(input_data): # Read the inputs inputs = parse_input(input_data) capacity = inputs.capacity items = inputs.items # Solver Example #value, taken = solver_example(capacity, items) # Solver DP print("Capacity:", capacity, " | N:", len(items)) start = time.time() if capacity * len(items) < 10000 * 10000: print("Solver DP") value, taken = solver_dp(capacity, items) else: print("Solver Tree") value, taken = solver_depth_first_branch(capacity, items) end = time.time() print("Time:", end - start) # Parse outputs output_data = parse_output(value, taken) return output_data
def amplitude_edit_text_changed(self): try: parsed = utils.parse_input(self.ui.amplitude_edit.text()) except ValueError: parsed = "" qt_utils.update_edit_color(self.calibrator.amplitude, parsed, self.ui.amplitude_edit)
def extract_params(self) -> List[Scale.Limit]: try: scales = [] for row_idx in range(self.ui.limits_table.rowCount()): limit = utils.parse_input( self.ui.limits_table.item( row_idx, ScaleLimitsDialog.Column.LIMIT).text()) device_class = self.ui.limits_table.cellWidget( row_idx, ScaleLimitsDialog.Column.CLASS).value() signal_type = \ self.ui.limits_table.cellWidget(row_idx, ScaleLimitsDialog.Column.SIGNAL_TYPE).currentIndex() frequency = \ self.ui.limits_table.cellWidget(row_idx, ScaleLimitsDialog.Column.FREQUENCY).get_frequency_text() limit_id = int( self.ui.limits_table.item( row_idx, ScaleLimitsDialog.Column.ID).text()) scales.append( Scale.Limit(a_id=limit_id, a_limit=limit, a_device_class=device_class, a_signal_type=clb.SignalType(signal_type), a_frequency=frequency)) return scales except Exception as err: utils.exception_handler(err)
def apply_amplitude_button_clicked(self): try: new_amplitude = utils.parse_input(self.ui.amplitude_edit.text()) self.set_amplitude(new_amplitude) except ValueError: # Отлавливает некорректный ввод pass
def save_params(self): limit = utils.parse_input(self.ui.limit_edit.text()) if limit != 0: if self.case.limit != limit: # Это сбрасывает точки шкалы в таблице self.case.scale_coef = 0 self.case.limit = limit self.case.minimal_discrete = utils.parse_input(self.ui.minimal_discrete_edit.text()) self.case.signal_type = clb.SignalType(self.ui.signal_type_combobox.currentIndex()) self.case.device_class = self.ui.device_class_spinbox.value() self.accept() else: QtWidgets.QMessageBox.critical(self, "Ошибка", "Предел не может быть равен нулю", QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def get_data(): input = request.args.get('d', None, type=str) app.logger.info('get_data input: {}'.format(input)) if input is None or input == '': return jsonify("No input data"), 422 else: try: input_tidy = tidy_input(input) app.logger.debug('input_tidy: {}'.format(input_tidy)) input_parsed = parse_input(input_tidy, sides=SIDES_LIST, max_dice=MAX_DICE_TOTAL) app.logger.debug('input_parsed: {}'.format(input_parsed)) rolls_output = read_data_from_db(app, db, RollModel, input_parsed) app.logger.debug('rolls_output: {}'.format(rolls_output)) stats_output = calc_stats(roll_name=input_tidy, rolls=rolls_output) app.logger.debug('stats_output: {}'.format(stats_output)) return json.dumps({ 'rolls': rolls_output, 'stats': stats_output }, cls=DecimalEncoder) except InvalidInput as e: app.logger.debug('Caught error: {}'.format(str(e))) return jsonify(str(e)), 422 except Exception as e: app.logger.debug('Other unknown error') return jsonify(f"Unknown error: {str(e)}"), 400
def process_input(self, a_input: str): try: processed_value = utils.parse_input(a_input) processed_value = self.bound_input(processed_value) except ValueError: processed_value = self.bound_input(0) return self.value_to_user(processed_value)
def main(): genes = utils.parse_input(input_path) print("Running Genetic Algorithm on TSP problem with {} cities.".format( len(genes))) result = TSP.run(genes, population_size, n_generation, tournament_size, mutation_rate)
def normalize_edit_value(self, edit: QtWidgets.QLineEdit): try: value = utils.parse_input(edit.text()) value = clb.bound_amplitude(value, self.case.signal_type) edit.setText(utils.value_to_user_with_units(clb.signal_type_to_units[self.case.signal_type])(value)) self.update_edit_color(edit) except ValueError: pass
def apply_frequency_button_clicked(self): try: new_frequency = utils.parse_input(self.ui.frequency_edit.text()) self.set_frequency(new_frequency) self.frequency_edit_text_changed() except ValueError: # Отлавливает некорректный ввод pass
def normalize_edit_value(self, edit: QtWidgets.QLineEdit): try: value = utils.parse_input(edit.text()) value = clb.bound_amplitude(value, self.fast_params.signal_type) edit.setText(self.value_to_user(value)) self.update_edit_color(edit) except ValueError: pass
def message_getter(self, file): #TODO: распознование стикеров messages_list = vkr.get_messages_list() print('Обнаружено {} диалогов'.format(messages_list['count'])) for k in range(messages_list['count'] // 200 + 1): for d in range(len(messages_list['items'])): msg_list = messages_list['items'][d] messages = vkr.get_messages(uid=msg_list['message']['user_id']) time.sleep(0.33) if 'chat_id' in msg_list['message']: print('Сообщения из беседы, пропускаю') continue else: uname = vkr.get_user_name( uid=msg_list['message']['user_id']) print('Сообщений в диалоге: {}::{}'.format(\ messages['count'], uname ) ) file.write('### {}::{}\n'.format( uname, msg_list['message']['user_id'])) for i in range(messages['count'] // 200 + 1): for j in range(len(messages['items'])): msg = messages['items'][j] text = msg['body'] if text != '': text = parse_input(text) file.write( '{} {}\n'.format(\ '<A>' if msg['from_id'] == self.SELF_ID else '<Q>', text ) ) elif 'attachments' in msg and msg['attachments'][0][ 'type'] == 'sticker': text = get_sticker_meaning( msg['attachments'][0]['sticker']) file.write( '{} {}\n'.format(\ '<A>' if msg['from_id'] == self.SELF_ID else '<Q>', text ) ) print('Iteration {}.{}'.format(i + 1, len(messages['items']))) messages = vkr.get_messages( offset=(i + 1) * 200, uid=msg_list['message']['user_id']) time.sleep(0.33) file.write('### {}::{}\n\n'.format( uname, msg_list['message']['user_id'])) print('Завершена обработка диалога №{}/{}'.format( k * 200 + d + 1, messages_list['count'])) messages_list = vkr.get_messages_list(offset=(k + 1) * 200)
def loop(): status = True while status: prompt = parse_prompt() line = parse_input(input(prompt).strip()) add_history(line) args = line.split(' ') # args value sample: ['ls', '-la'] args_list = parse_args(args) status = execute(args_list)
def get_list(self) -> List[float]: out_list = [] try: for idx in range(self.ui.list_widget.count()): item = self.ui.list_widget.item(idx).text() if item not in out_list: out_list.append(utils.parse_input(item)) return out_list except ValueError: return list()
def sort_list(self): items = OrderedDict() for idx in range(self.ui.list_widget.count()): text = self.ui.list_widget.item(idx).text() value = utils.parse_input(text) items[value] = text self.ui.list_widget.clear() items = OrderedDict(sorted(items.items())) for value in items.values(): self.ui.list_widget.addItem(QtWidgets.QListWidgetItem(value)) return list(items.keys())
def solve_it(input_data): # Modify this code to run your optimization algorithm node_count, edge_count, edges = parse_input(input_data) #optimal, solution = solve_it_trivial(node_count, edge_count, edges) optimal, solution = solve_it_nontrivial(node_count, edge_count, edges) # prepare the solution in the specified output format output_data = str(len(set(solution))) + ' ' + str(optimal) + '\n' output_data += ' '.join(map(str, solution)) return output_data
def _build(): ''' Build new Index object Step 1: Index name. Valid characters are a-z, A-Z, whitespace and commas. Step 2: Ticker list. Valid commands are \'add\' and \'remove\' ''' print('Enter a name for your index.') response = parse_input('>>> ', lambda s: s not in CACHED_IND_NAMES, 'Index already exists.', _build) if response: ind = build_index(response) CACHED_INDICES.append(ind) CACHED_IND_NAMES.append(response) print('Enter \'add\' or \'remove\' to edit tickers') action = True while action: action = parse_input('>>> ', lambda s: s in ['ADD', 'REMOVE'], 'Invalid command.', _build) if action == 'ADD': _add_tickers(ind) elif action == 'REMOVE': _remove_tickers(ind)
def signal_type_changed(self, a_idx): try: sender_table_row = self.ui.limits_table.currentRow() row_limit_item = self.ui.limits_table.item( sender_table_row, ScaleLimitsDialog.Column.LIMIT) value_f = utils.parse_input(row_limit_item.text()) signal_type = clb.SignalType(a_idx) units = clb.signal_type_to_units[signal_type] value_str = utils.value_to_user_with_units(units)(value_f) row_limit_item.setText(value_str) except Exception as err: utils.exception_handler(err)
def write_variable(self, a_item: QtWidgets.QTableWidgetItem): try: if self.netvars.connected(): variable_number = int( self.ui.variables_table.item(a_item.row(), self.Column.NUMBER).text()) try: variable_value = utils.parse_input(a_item.text()) self.netvars.write_variable(variable_number, variable_value) except ValueError: pass except Exception as err: logging.debug(utils.exception_handler(err))
def _remove_tickers(ind): ''' Remove ticker(s) from Index. Valid characters are a-z, A-Z, whitespace and commas. ''' pattern = re.compile('^[a-zA-Z, ]+$') print('Enter tickers to remove.') response = parse_input('>>> ', pattern.match, 'Invalid characters entered.', _remove_tickers) if response: response = parse_tickers(response) for ticker in response: if ticker in list(ind.tick_items.keys()): ind.remove_company(ticker) print('Index name: {}'.format(ind.name)) print('Tickers: {}'.format(list(ind.tick_items.keys())))
def search(input_path, output_path): words, grid = parse_input(input_path) max_row = len(grid) max_col = len(grid[0]) solution = {} for word in words: for r in range(max_row): for c in range(max_col): if grid[r][c] == word[0]: coords = find_word(r, c, max_row, max_col, word, grid) if coords: solution[word] = coords write_output(solution, output_path)
def _add_tickers(ind): ''' Add ticker(s) to Index. Valid characters are a-z, A-Z, whitespace and commas. ''' pattern = re.compile('^[a-zA-Z, ]+$') print('Enter tickers to add.') response = parse_input('>>> ', pattern.match, 'Invalid characters entered.', _add_tickers) if response: response = parse_tickers(response) for ticker in response: ind.add_company(ticker) check_for_real_ticker(ind) print('Index name: {}'.format(ind.name)) print('Tickers: {}'.format(list(ind.tick_items.keys())))
def save_config(self): try: self.fast_params.upper_bound = utils.parse_input( self.ui.upper_bound_edit.text()) self.fast_params.accuracy_class = self.ui.accuracy_class_spinbox.value( ) self.fast_params.minimal_discrete = utils.parse_input( self.ui.minimal_discrete.text()) self.fast_params.comment = self.ui.comment_edit.text() self.fast_params.auto_calc_points = bool( self.ui.auto_calc_points_checkbox.isChecked()) self.fast_params.lower_bound = utils.parse_input( self.ui.lower_bound_edit.text()) self.fast_params.points_step = utils.parse_input( self.ui.step_edit.text()) self.fast_params.frequency = self.ui.frequency_edit.text() self.fast_params.start_point_side = FastMeasureParams.StartPoint.UPPER if \ self.ui.start_point_up_radio.isChecked() else FastMeasureParams.StartPoint.LOWER return True except ValueError: return False
def examples_with_aggregated_matrices(subset): planets = get_planets(subset) os.makedirs('../database/completely_aggregated', exist_ok=True) for planet in tqdm(planets): data = None planet_matrix = np.zeros((10, 55, 300), dtype=np.float64) for spot in range(1, 11): spot_matrix = np.zeros((55, 300), dtype=np.float64) for gaus in range(1, 11): data = parse_input( '../database/noisy_{}/{}_{:0>2}_{:0>2}.txt'.format( subset, planet, spot, gaus)) spot_matrix += data['matrix'] spot_matrix /= 10 planet_matrix[spot - 1] = spot_matrix planet_matrix = 1 - np.median(planet_matrix, axis=0) data['matrix'] = planet_matrix window_size = 3 temp = np.zeros((55, 300)) for i in range(300): temp[:, i] = np.mean(planet_matrix[:, max(0, i - window_size):i + window_size], axis=1) data['maxes'] = np.max(temp, axis=1) data['relative_means'] = np.mean(temp, axis=1) / data['maxes'] frequencies = create_ariel_frequencies(equidistant_frequency=True) radiations = [ black_body_radiation(frequencies[i], data['misc_inputs'][0]) for i in NOISE_ORDER ] data['radiation'] = np.array(radiations) out_path = '../database/params_train/{}_01_01.txt'.format(planet) if os.path.exists(out_path): data.update(parse_output(out_path)) data['planet'] = planet pickle.dump( data, open('../database/completely_aggregated/{}.pickle'.format(planet), 'wb'))
def _remove(): ''' Delete Index object Valid input: name of Index ''' print('Type the name of the Index you\'d like to remove.') print('Current indices are {}.'.format(CACHED_IND_NAMES)) response = parse_input('>>> ', lambda s: s in CACHED_IND_NAMES, 'Index does not exist.', _remove) if response: print('Are you sure you want to delete {}?'.format(response)) confirm = yes_no_prompt('>>> ') if confirm: remove_index = CACHED_IND_NAMES.index(response) CACHED_INDICES.pop(remove_index) CACHED_IND_NAMES.remove(response) print('Index {} has been removed.'.format(response)) print('Current indices are {}.'.format(CACHED_IND_NAMES))
) parser.add_argument('--serial', required=True, type=str, help=""" Where the serial port is. Should be in the form of /dev/cu.usbmodem1431 or similar """) parser.add_argument('--x', required=True, type=float, help=""" X value of person position """) parser.add_argument('--y', required=True, type=float, help=""" Y value of person position """) args = parser.parse_args() serial_port = args.serial x = args.x y = args.y ser = serial.Serial(serial_port, 9600) time.sleep(2) while True: print ser.readline() val = ser.readline() time.sleep(1) break val_list = parse_input(val) with open('training_data.csv', 'ab') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow([x,y,val_list])
soup = BeautifulSoup(resp.content) return soup def _get_title(self, soup): """ get title from soup """ title = soup.find('title').text try: return title.split('|')[0] except AttributeError: raise Exception('AttributeError Occured') def score(self): """ get score from time """ soup = self._get_soup() title = self._get_title(soup) while title: return title def get_live_score(self): """ show live notification score """ while True: if self.score(): score = self.score() Notifier.notify(score, title=self.match_title) time.sleep(self.delay) if __name__=="__main__": USER_INPUT = parse_input() CNOTIFIER = CrickNotfier(USER_INPUT.url, int(USER_INPUT.delay)) CNOTIFIER.get_live_score()
Where the serial port is. Should be in the form of /dev/cu.usbmodem1431 or similar """) args = parser.parse_args() room_in = args.room loc = args.location serial_port = args.serial ## Serial and Logging Stufff ser = serial.Serial(serial_port, 9600) logging.basicConfig(filename='arudino_recorder.log',level=logging.DEBUG) while True: try: load_input(parse_input(ser.readline()),room_in,loc) except serial.serialutil.SerialException: logging.warning("Arudino Failed to Report Data") pass except IndexError: logging.warning("Bad Input Error") pass except sqlalchemy.exc.DataError: logging.warning("SQL Alchemy Error") pass except KeyboardInterrupt: print "You have quit the program. It will now exit. Goodbye" sys.exit() except: print sys.exc_info()[0] logging.info(sys.exc_info()[0])