def test_loads_valid_toml_files(toml_file): with open(str(toml_file), "r") as f: table = pytomlpp.load(f) table_json = json.loads(toml_file.with_suffix(".json").read_text()) table_expected = value_from_json(table_json) assert table == table_expected table = pytomlpp.load(toml_file) assert table == table_expected
def test_invalid_toml_files(invalid_toml_files): for t in invalid_toml_files: if t.stem in INVALID_EXCLUDE_FILE: print(f"skiping {t.stem}") continue print(f"parsing {t}") with pytest.raises(RuntimeError): pytomlpp.load(str(t))
def bar2vtk_main(args=None): """Function that runs the "binary" bar2vtk""" argsdict = bar2vtk_parse(args) if argsdict['subparser_name'] == 'cli': bar2vtkargs = argsdict.copy() bar2vtkargs['asciidata'] = bar2vtkargs.pop('ascii') for key in list(bar2vtkargs.keys()): if key not in bar2vtk_function.__code__.co_varnames: del bar2vtkargs[key] elif argsdict['subparser_name'] == 'toml': if argsdict['blank']: blankToml(argsdict['tomlfile']) return assert argsdict['tomlfile'].is_file() with argsdict['tomlfile'].open() as tomlfile: tomldict = pytomlpp.load(tomlfile) bar2vtkargs = tomldict['arguments'] for key, val in bar2vtkargs.items(): if key in [ 'barfiledir', 'outpath', 'blankvtmfile', 'velbar', 'stsbar' ]: if isinstance(val, list): for i, item in enumerate(val): val[i] = Path(item) else: bar2vtkargs[key] = Path(val) tomlMetadata = bar2vtk_function(**bar2vtkargs, returnTomlMetadata=True) tomlReceipt(bar2vtkargs, tomlMetadata)
def _load_file_as_dict(file_path: Path) -> Dict: if not file_path.exists(): return {} with open(file_path, 'r') as config_file: dict_from_toml = pytomlpp.load(config_file) return dict_from_toml
def __resolve(_dict, resolving): if resolving is None: resolving = [] included = None for key in _dict: if key == '__include__': val = _dict['__include__'] if str(val) in resolving: raise RuntimeError('Encountered __include__ cycle:\n' f' {" -> ".join(resolving)} -> {val}') with open(val, 'r') as f: # noinspection PyTypeChecker included = __resolve(pytomlpp.load(f), resolving + [val]) else: val = _dict[key] if isinstance(val, dict): _dict[key] = __resolve(val, resolving) elif isinstance(val, list) and any(isinstance(it, dict) for it in val): _dict[key] = [it if not isinstance(it, dict) else __resolve(it, resolving) for it in val] if included is not None: _dict = _merge(included, _dict) return _dict
def test_valid_toml_files(valid_toml_files): for t in valid_toml_files: if t.stem in VALID_EXCLUDE_FILE: continue print(f"parsing {t}") table = pytomlpp.load(str(t)) assert type(table) == dict
def _load(self, path: str) -> Dict: """TOML load function Args: path: path to TOML file Returns: base_payload: dictionary of read file """ base_payload = pytomlpp.load(path) return base_payload
def generate_curated_words_study(*, words_toml_path: str, curated_words_study_path: str): _md_template = [ f"""{h1(f"A Subset of Curated Words Extracted From Tweets")} To learn how the words are used in context, read the tweets by clicking or tapping on the Chinese words. For a complete list of the curated words, check it out {link('here', 'words_tweets_stats.md')}. """ ] toml_words = toml.load(words_toml_path) fields_align = [MdCellAlign.left, MdCellAlign.center] pprint(toml_words) for name, heading in toml_words['category-names'].items(): _md_template.append(h2(heading)) _md_template.append(table_header(['', ''], fields_align)) for word in toml_words[name]: _md_template.append( table_row([link(word['hz'], f"{word['hz']}.md"), word['en']])) with open(curated_words_study_path, "w") as fh: fh.writelines('\n'.join(_md_template))
def load(self, fp): return deserialize(pytomlpp.load(fp))
def test_loads_invalid_toml_files(toml_file): with pytest.raises(pytomlpp.DecodeError): with open(str(toml_file), "r") as f: pytomlpp.load(f)
def main(): global field sg.theme("Reddit") window = create_window() viewport = ph.DrawOptions(window["-VIEWPORT-"].TKCanvas, 200, (5, 5)) viewport_items = [] evolving_population = False field = ph.Field(pytomlpp.load(open("items.toml"))) last_frame = 0 text_box = {} text_box["iddle_gui_time"] = 0 text_box["loop_time"] = 0 text_box["vis_time"] = 0 text_box["vis_car_score"] = 0 text_box["generation"] = 0 iddle_gui_time = 0 gen_start = 0 keys = {"w": False, "a": False, "s": False, "d": False} def on_press(key): if key.char in {"w", "a", "s", "d"}: keys[key.char] = True def on_release(key): if key.char in {"w", "a", "s", "d"}: keys[key.char] = False keyboard_listener = pynput.keyboard.Listener(on_press, on_release) keyboard_listener.start() while True: t0 = millis() event, values = window.read(timeout=iddle_gui_time) if event == sg.WIN_CLOSED: break elif event == "-RESET_CAR-": with field_lock: field.reset() # Input if keys["w"]: field.car.push(10) elif keys["s"]: field.car.push(-10) else: field.car.push(0) if keys["a"]: field.car.steer(-field.car.max_steer_angle) elif keys["d"]: field.car.steer(+field.car.max_steer_angle) else: field.car.steer(0) # Drawing if millis() - last_frame > FRAME_TIME: draw_t0 = millis() draw_time = millis() - draw_t0 viewport.canvas.delete("all") field.show(viewport) field.step() text_box["vis_car_score"] = round(field.score(), 2) text_box["vis_time"] = draw_time loop_time = millis() - t0 iddle_gui_time = max(0, round(FRAME_TIME - loop_time)) text_box["iddle_gui_time"] = iddle_gui_time text_box["loop_time"] = round(loop_time) text_box["keys"] = keys window["-VALUES-"].update("\n".join(f"{n}: {v}" for n, v in text_box.items()))
import time import threading import multiprocessing import itertools import pytomlpp import PySimpleGUI as sg import pynput import viroro.physics as ph FRAME_TIME = 1 / 60 * 1000 FIELD_CONFIG = pytomlpp.load(open("items.toml")) FIELD_STEPS = 100 def millis(): return int(time.time() * 1000) def create_window(): vp_size = (800, 400) viewport = sg.Graph(vp_size, (0, 0), vp_size, key="-VIEWPORT-") layout = [[ sg.Frame("Viewport", [[viewport]]), sg.Column([ [sg.B("Dump"), sg.B("Load"), sg.B("Reset car", key="-RESET_CAR-")], [ sg.Frame("Values",
def test_decode_encode_binary(toml_file, tmp_path): data = pytomlpp.load(toml_file) pytomlpp.dump(data, str(tmp_path / "tmp.toml"), mode="wb") assert pytomlpp.load(str(tmp_path / "tmp.toml"), mode="rb") == data
from pathlib import Path import pytomlpp from appdirs import user_data_dir class Directories: user = Path(user_data_dir("pynfogen", "PHOENiX")) artwork = user / "artwork" templates = user / "templates" class Files: config = Directories.user / "config.toml" artwork = Directories.artwork / "{name}.nfo" template = Directories.templates / "{name}.nfo" description = Directories.templates / "{name}.txt" if Files.config.exists(): config = pytomlpp.load(Files.config) else: config = {} __ALL__ = (config, Directories, Files)
def load() -> 'ConfigObject': with open('config.toml', 'r') as f: # noinspection PyTypeChecker _dict = __resolve(pytomlpp.load(f), ['config.toml']) return ConfigObject({key: _to_config_value(value) for key, value in _dict.items()})
def main(population, config): global cur_frame global cur_frame_lock global cur_frame_ready global send_frames global cur_progress global cur_generation global best_field sg.theme("Reddit") window = create_window() viewport = ph.DrawOptions(window["-VIEWPORT-"].TKCanvas, 84, (5, 5)) viewport_items = [] evolving_population = False best_field = ph.Field(pytomlpp.load(open("items.toml"))) best_field.algo = lambda x: (30, -50) evolving_thread = threading.Thread(target=calc_thread, args=(), daemon=True) last_frame = 0 last_vis_mode = "-VIS_MODE_NONE-" text_box = {} text_box["iddle_gui_time"] = 0 text_box["loop_time"] = 0 text_box["vis_time"] = 0 text_box["vis_car_score"] = 0 text_box["since_starting_gen"] = millis() + 9000 text_box["generation"] = 0 iddle_gui_time = 0 gen_start = 0 while True: t0 = millis() event, values = window.read(timeout=iddle_gui_time) if event == sg.WIN_CLOSED: break elif event == "-STARTSTOP-": evolving_population = not evolving_population window['-STARTSTOP-'].update( "Run" if not evolving_population else "Stop") elif event == "-RESET_BEST_CAR-": with best_field_lock: best_field.reset() # Evolving if evolving_population and not evolving_thread.is_alive(): evolving_thread = threading.Thread(target=calc_thread, args=(population, ), daemon=True) evolving_thread.start() gen_start = millis() # Drawing if millis() - last_frame > FRAME_TIME: draw_t0 = millis() window["-PROGRESS-"].update(cur_progress) if values["-VIS_MODE_NONE-"]: cur_mode = "-VIS_MODE_NONE-" elif values["-VIS_MODE_FULL-"]: cur_mode = "-VIS_MODE_FULL-" elif values["-VIS_MODE_BEST-"]: cur_mode = "-VIS_MODE_BEST-" send_frames = cur_mode == "-VIS_MODE_FULL-" if cur_mode != last_vis_mode: viewport.canvas.delete("all") last_vis_mode = cur_mode if not values["-VIS_MODE_FULL-"] and not cur_frame_ready.is_set(): cur_frame_ready.set() if values["-VIS_MODE_FULL-"]: if not cur_frame_ready.is_set(): with cur_frame_lock: if cur_frame: cur_frame[0].show(viewport) for field in cur_frame[1:]: field.car.show(viewport) else: viewport.canvas.delete("all") cur_frame_ready.set() elif values["-VIS_MODE_BEST-"]: with best_field_lock: viewport.canvas.delete("all") best_field.show(viewport) best_field.step() text_box["vis_car_score"] = round(best_field.score(), 2) draw_time = millis() - draw_t0 text_box["vis_time"] = draw_time text_box["since_starting_gen"] = round( (millis() - gen_start) / 1000) loop_time = millis() - t0 iddle_gui_time = max(0, round(FRAME_TIME - loop_time)) text_box["iddle_gui_time"] = iddle_gui_time text_box["loop_time"] = round(loop_time) text_box["generation"] = cur_generation window["-VALUES-"].update("\n".join(f"{n}: {v}" for n, v in text_box.items()))
def load(fp): result = toml.load(fp) print(result) replace_values(result, NULL_STRING, None) return result
def load(file="testtoml.toml"): with open(file, 'r+') as fr: packed = pytomlpp.load(fr) return deconvert(packed)
def read_config(config_file: TextIO) -> dict: return pytomlpp.load(config_file)